Compare commits
70
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
901cca5eb9 | ||
|
|
a1b1cf0473 | ||
|
|
653dcb0a14 | ||
|
|
91ec7d841c | ||
|
|
d8a991cc3a | ||
|
|
6d25d5c51f | ||
|
|
3d8fc2431f | ||
|
|
8390764ff4 | ||
|
|
699dc32b0d | ||
|
|
bea26c70ec | ||
|
|
40fcdba595 | ||
|
|
81441dc588 | ||
|
|
ad697e8a8b | ||
|
|
9025852972 | ||
|
|
7a137deb71 | ||
|
|
9905750d75 | ||
|
|
03e21fcb32 | ||
|
|
ddb3439324 | ||
|
|
6ea5ac1b17 | ||
|
|
95a9dcceff | ||
|
|
38896304e8 | ||
|
|
e8c0144441 | ||
|
|
e76a33d28f | ||
|
|
278e0f529d | ||
|
|
9c75728bbf | ||
|
|
1ab51196ce | ||
|
|
043db9b7cc | ||
|
|
c222d422a9 | ||
|
|
d1310f24ff | ||
|
|
fbf5dbefe3 | ||
|
|
387cab897a | ||
|
|
d78aef8df1 | ||
|
|
1a34333c63 | ||
|
|
882b681036 | ||
|
|
1b77071dc4 | ||
|
|
f8c7b1daac | ||
|
|
7e95b46779 | ||
|
|
70ed62a220 | ||
|
|
9d1ab1babb | ||
|
|
6651737b65 | ||
|
|
6d2b7a9873 | ||
|
|
7a7e04d2f0 | ||
|
|
424918404f | ||
|
|
d7a269589c | ||
|
|
84747b9efb | ||
|
|
3596c42947 | ||
|
|
3249a8569b | ||
|
|
479c144c8b | ||
|
|
d89d1ded98 | ||
|
|
5b37115e46 | ||
|
|
8f707df86f | ||
|
|
c30208e61e | ||
|
|
8c61b4d54f | ||
|
|
535e5d165f | ||
|
|
2bd12e447a | ||
|
|
b79816bafe | ||
|
|
522c8ca3e8 | ||
|
|
110977c847 | ||
|
|
79854123b6 | ||
|
|
ae04eae6e6 | ||
|
|
123db12ac4 | ||
|
|
5def7ac5f1 | ||
|
|
013a3bd2a2 | ||
|
|
eba2b73c6b | ||
|
|
c62f284866 | ||
|
|
6e3c5107f1 | ||
|
|
2eac8dc215 | ||
|
|
6a6e07a0dc | ||
|
|
d2aeb970da | ||
|
|
dc573433d9 |
+3
-2
@@ -13,8 +13,9 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
|
||||
"pytest~=8.1.0" \
|
||||
"httpx~=0.27.0" \
|
||||
"python-multipart~=0.0.19"\
|
||||
"elasticsearch~=9.4.0" \
|
||||
"openai~=2.41.0"
|
||||
"openai~=2.41.0" \
|
||||
"sqlmodel~=0.0.33" \
|
||||
"argon2-cffi~=25.1.0"
|
||||
|
||||
COPY [ "src/main", "/home" ]
|
||||
COPY [ "src/data", "/data" ]
|
||||
|
||||
@@ -49,7 +49,7 @@ task exportOpenApiSpec(type: Exec) {
|
||||
commandLine 'docker', 'run', '--rm',
|
||||
'--platform', "${targetPlatform}",
|
||||
'-w', '/home',
|
||||
'-v', "${projectDir}/src/main:/home",
|
||||
//'-v', "${projectDir}/src/main:/home", the source code is already baked into the image at build time
|
||||
'-v', "${openApiDir}:/mnt/openapi",
|
||||
'-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'",
|
||||
'--name', "${imageName}-service-openapi",
|
||||
|
||||
@@ -7,7 +7,6 @@ requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"cryptography~=42.0.0",
|
||||
"dotenv>=0.9.9",
|
||||
"elasticsearch~=9.4.0",
|
||||
"fastapi~=0.115.0",
|
||||
"httpx~=0.27.0",
|
||||
"openai~=2.41.0",
|
||||
@@ -17,10 +16,11 @@ dependencies = [
|
||||
"pytest~=8.1.0",
|
||||
"python-multipart~=0.0.19",
|
||||
"pyyaml~=6.0.1",
|
||||
"sqlalchemy~=2.0.0",
|
||||
"uvicorn~=0.29.0",
|
||||
"sentence-transformers~=5.5.1",
|
||||
"torch",
|
||||
"sqlmodel~=0.0.33",
|
||||
"argon2-cffi~=25.1.0",
|
||||
]
|
||||
|
||||
[[tool.uv.index]]
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
One-time script to fetch all topics from 'openalex-topics',
|
||||
vectorize display names and chunked descriptions using the sentence-transformers model,
|
||||
and push them to the 'topicvectors' index with multi-vector hybrid mapping.
|
||||
Script to fetch all topics from 'openalex-topics',
|
||||
vectorize display names, full descriptions, and individual keywords using the sentence-transformers model,
|
||||
and push them to the 'topicvectors' index with multi-vector mapping.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import base64
|
||||
import re
|
||||
from pathlib import Path
|
||||
import httpx
|
||||
import numpy as np
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Add service/src/main to python path to load settings
|
||||
@@ -24,8 +20,10 @@ sys.path.append(str(project_root / "service" / "src" / "main"))
|
||||
from inse.config import settings
|
||||
|
||||
ELASTIC_URL = settings.elasticsearch_url
|
||||
if ELASTIC_URL and not ELASTIC_URL.endswith("/"):
|
||||
ELASTIC_URL += "/"
|
||||
API_KEY = settings.elasticsearch_api_key
|
||||
MODEL_NAME = "paraphrase-multilingual-mpnet-base-v2"
|
||||
MODEL_NAME = settings.sentence_transformers_model_name
|
||||
|
||||
# Import sentence-transformers
|
||||
from sentence_transformers import SentenceTransformer
|
||||
@@ -35,20 +33,12 @@ headers = {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
def split_into_sentences(text):
|
||||
if not text:
|
||||
return []
|
||||
# Split on period, exclamation, or question mark followed by whitespace
|
||||
sentences = re.split(r'(?<=[.!?])\s+', text.strip())
|
||||
# Filter out empty or extremely short sentences
|
||||
return [s for s in sentences if len(s.strip()) > 3]
|
||||
|
||||
def fetch_all_topics():
|
||||
print("Fetching topics from 'openalex-topics'...")
|
||||
topics = []
|
||||
size = 1000
|
||||
offset = 0
|
||||
|
||||
|
||||
with httpx.Client(timeout=60.0) as client:
|
||||
while True:
|
||||
payload = {
|
||||
@@ -71,42 +61,104 @@ def fetch_all_topics():
|
||||
print(f"Fetched {len(topics)} topics so far...")
|
||||
if len(hits) < size:
|
||||
break
|
||||
|
||||
|
||||
print(f"Total topics fetched: {len(topics)}")
|
||||
return topics
|
||||
|
||||
def bulk_index_topics(topics, display_name_vectors, nested_description_vectors):
|
||||
def update_mappings():
|
||||
print("Checking/updating mappings for 'topicvectors'...")
|
||||
mapping_payload = {
|
||||
"properties": {
|
||||
"display_name_vector": {
|
||||
"type": "dense_vector",
|
||||
"dims": 768,
|
||||
"index": True,
|
||||
"similarity": "cosine",
|
||||
"index_options": {
|
||||
"type": "int8_hnsw",
|
||||
"m": 16,
|
||||
"ef_construction": 100
|
||||
}
|
||||
},
|
||||
"description_vector": {
|
||||
"type": "dense_vector",
|
||||
"dims": 768,
|
||||
"index": True,
|
||||
"similarity": "cosine",
|
||||
"index_options": {
|
||||
"type": "int8_hnsw",
|
||||
"m": 16,
|
||||
"ef_construction": 100
|
||||
}
|
||||
},
|
||||
"keyword_vectors": {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"vector": {
|
||||
"type": "dense_vector",
|
||||
"dims": 768,
|
||||
"index": True,
|
||||
"similarity": "cosine",
|
||||
"index_options": {
|
||||
"type": "int8_hnsw",
|
||||
"m": 16,
|
||||
"ef_construction": 100
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
with httpx.Client(timeout=30.0) as client:
|
||||
# Check if index exists
|
||||
check_resp = client.get(f"{ELASTIC_URL}topicvectors", headers=headers)
|
||||
if check_resp.status_code == 404:
|
||||
print("Index 'topicvectors' does not exist. Creating it...")
|
||||
create_payload = {
|
||||
"mappings": mapping_payload
|
||||
}
|
||||
resp = client.put(f"{ELASTIC_URL}topicvectors", json=create_payload, headers=headers)
|
||||
resp.raise_for_status()
|
||||
else:
|
||||
print("Index 'topicvectors' exists. Updating mappings...")
|
||||
resp = client.put(f"{ELASTIC_URL}topicvectors/_mapping", json=mapping_payload, headers=headers)
|
||||
resp.raise_for_status()
|
||||
print("Mappings update process completed.")
|
||||
|
||||
def bulk_index_topics(topics, display_name_vectors, description_vectors, keyword_vectors_list):
|
||||
print("Bulk indexing vectorized topics into 'topicvectors'...")
|
||||
batch_size = 500
|
||||
|
||||
|
||||
with httpx.Client(timeout=60.0) as client:
|
||||
for i in range(0, len(topics), batch_size):
|
||||
batch_topics = topics[i:i+batch_size]
|
||||
batch_name_vecs = display_name_vectors[i:i+batch_size]
|
||||
batch_desc_vecs_list = nested_description_vectors[i:i+batch_size]
|
||||
|
||||
batch_desc_vecs = description_vectors[i:i+batch_size]
|
||||
batch_kw_vecs_list = keyword_vectors_list[i:i+batch_size]
|
||||
|
||||
bulk_lines = []
|
||||
for t, name_vec, desc_vecs in zip(batch_topics, batch_name_vecs, batch_desc_vecs_list):
|
||||
for t, name_vec, desc_vec, kw_vecs in zip(batch_topics, batch_name_vecs, batch_desc_vecs, batch_kw_vecs_list):
|
||||
source = t["_source"]
|
||||
|
||||
# Remove deprecated single vector if present
|
||||
if "vector" in source:
|
||||
del source["vector"]
|
||||
|
||||
|
||||
source.pop("siblings", None) # drop siblings field when making the copy
|
||||
|
||||
# Assign name vector as a standard float list
|
||||
source["display_name_vector"] = name_vec.tolist()
|
||||
|
||||
# Assign nested description vectors as standard float lists
|
||||
source["description_vectors"] = [
|
||||
{"vector": vec.tolist()} for vec in desc_vecs
|
||||
|
||||
# Assign description vector
|
||||
source["description_vector"] = desc_vec.tolist()
|
||||
|
||||
# Assign nested keyword vectors
|
||||
source["keyword_vectors"] = [
|
||||
{"vector": vec.tolist()} for vec in kw_vecs
|
||||
]
|
||||
|
||||
|
||||
# Meta line
|
||||
meta = {"index": {"_index": "topicvectors", "_id": t["_id"]}}
|
||||
bulk_lines.append(json.dumps(meta))
|
||||
# Document line
|
||||
bulk_lines.append(json.dumps(source))
|
||||
|
||||
|
||||
payload = "\n".join(bulk_lines) + "\n"
|
||||
resp = client.post(
|
||||
f"{ELASTIC_URL}_bulk",
|
||||
@@ -124,53 +176,61 @@ def bulk_index_topics(topics, display_name_vectors, nested_description_vectors):
|
||||
print(f"Indexed batch {i} to {i + len(batch_topics)}")
|
||||
|
||||
def main():
|
||||
update_mappings()
|
||||
|
||||
topics = fetch_all_topics()
|
||||
if not topics:
|
||||
print("No topics found. Exiting.")
|
||||
return
|
||||
|
||||
|
||||
print(f"Initializing SentenceTransformer model '{MODEL_NAME}'...")
|
||||
model = SentenceTransformer(MODEL_NAME)
|
||||
|
||||
|
||||
# 1. Gather all texts to embed
|
||||
display_names = []
|
||||
description_sentences_by_topic = []
|
||||
keywords_by_topic = []
|
||||
all_texts_to_embed = []
|
||||
|
||||
|
||||
for t in topics:
|
||||
source = t["_source"]
|
||||
|
||||
name = source.get("display_name") or ""
|
||||
display_names.append(name)
|
||||
all_texts_to_embed.append(name)
|
||||
|
||||
|
||||
desc = source.get("description") or ""
|
||||
sentences = split_into_sentences(desc)
|
||||
description_sentences_by_topic.append(sentences)
|
||||
all_texts_to_embed.extend(sentences)
|
||||
|
||||
print(f"Embedding {len(all_texts_to_embed)} texts (display names and description passages)...")
|
||||
all_texts_to_embed.append(desc)
|
||||
|
||||
kws = source.get("keywords") or []
|
||||
if not isinstance(kws, list):
|
||||
kws = [kws] if kws else []
|
||||
keywords_by_topic.append(kws)
|
||||
all_texts_to_embed.extend(kws)
|
||||
|
||||
print(f"Embedding {len(all_texts_to_embed)} texts (display names, descriptions, and keywords)...")
|
||||
all_vectors = model.encode(all_texts_to_embed, show_progress_bar=True, batch_size=32)
|
||||
|
||||
|
||||
# 2. Map embeddings back to topics
|
||||
display_name_vectors = []
|
||||
nested_description_vectors = []
|
||||
|
||||
description_vectors = []
|
||||
keyword_vectors_list = []
|
||||
|
||||
vector_idx = 0
|
||||
for idx, t in enumerate(topics):
|
||||
# First vector is the display name
|
||||
|
||||
display_name_vectors.append(all_vectors[vector_idx])
|
||||
vector_idx += 1
|
||||
|
||||
# Next N vectors are the description chunks
|
||||
sentences = description_sentences_by_topic[idx]
|
||||
topic_desc_vecs = []
|
||||
for _ in range(len(sentences)):
|
||||
topic_desc_vecs.append(all_vectors[vector_idx])
|
||||
|
||||
description_vectors.append(all_vectors[vector_idx])
|
||||
vector_idx += 1
|
||||
|
||||
kws = keywords_by_topic[idx]
|
||||
topic_kw_vecs = []
|
||||
for _ in range(len(kws)):
|
||||
topic_kw_vecs.append(all_vectors[vector_idx])
|
||||
vector_idx += 1
|
||||
nested_description_vectors.append(topic_desc_vecs)
|
||||
|
||||
keyword_vectors_list.append(topic_kw_vecs)
|
||||
|
||||
# Bulk index
|
||||
bulk_index_topics(topics, display_name_vectors, nested_description_vectors)
|
||||
bulk_index_topics(topics, display_name_vectors, description_vectors, keyword_vectors_list)
|
||||
print("Done!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"organizations": [
|
||||
{
|
||||
"id": "c001beef-cafe-4000-8000-d34db33f000d",
|
||||
"name": "The Super Admin Organization"
|
||||
}
|
||||
],
|
||||
"accounts": [
|
||||
{
|
||||
"email": "super@admin.com",
|
||||
"password": "superadmin",
|
||||
"name": "Super Admin",
|
||||
"organization_id": "c001beef-cafe-4000-8000-d34db33f000d",
|
||||
"role": "SUPER_ADMIN"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
{
|
||||
"query": "localization",
|
||||
"max_score": 23.237041,
|
||||
"results": [
|
||||
{
|
||||
"topic_name": "Indoor and Outdoor Localization Technologies",
|
||||
"score": 23.237041
|
||||
},
|
||||
{
|
||||
"topic_name": "Robotics and Sensor-Based Localization",
|
||||
"score": 21.511477
|
||||
},
|
||||
{
|
||||
"topic_name": "Spectral Theory in Mathematical Physics",
|
||||
"score": 14.039959
|
||||
},
|
||||
{
|
||||
"topic_name": "Socioeconomic Development in MENA",
|
||||
"score": 11.518878
|
||||
},
|
||||
{
|
||||
"topic_name": "Electrical Fault Detection and Protection",
|
||||
"score": 10.770052
|
||||
},
|
||||
{
|
||||
"topic_name": "Machine Learning in Bioinformatics",
|
||||
"score": 10.322677
|
||||
},
|
||||
{
|
||||
"topic_name": "Software System Performance and Reliability",
|
||||
"score": 10.112644
|
||||
},
|
||||
{
|
||||
"topic_name": "Quantum many-body systems",
|
||||
"score": 10.112644
|
||||
},
|
||||
{
|
||||
"topic_name": "Random lasers and scattering media",
|
||||
"score": 10.112644
|
||||
},
|
||||
{
|
||||
"topic_name": "Insect Pheromone Research and Control",
|
||||
"score": 9.910988
|
||||
},
|
||||
{
|
||||
"topic_name": "Tactile and Sensory Interactions",
|
||||
"score": 9.910988
|
||||
},
|
||||
{
|
||||
"topic_name": "Handwritten Text Recognition Techniques",
|
||||
"score": 9.910988
|
||||
},
|
||||
{
|
||||
"topic_name": "Integrated Circuits and Semiconductor Failure Analysis",
|
||||
"score": 9.910988
|
||||
},
|
||||
{
|
||||
"topic_name": "Medical Imaging and Analysis",
|
||||
"score": 9.7172165
|
||||
},
|
||||
{
|
||||
"topic_name": "Microwave Imaging and Scattering Analysis",
|
||||
"score": 9.7172165
|
||||
},
|
||||
{
|
||||
"topic_name": "Neurology and Historical Studies",
|
||||
"score": 9.7172165
|
||||
},
|
||||
{
|
||||
"topic_name": "High-Velocity Impact and Material Behavior",
|
||||
"score": 9.7172165
|
||||
},
|
||||
{
|
||||
"topic_name": "Software Engineering Research",
|
||||
"score": 9.530875
|
||||
},
|
||||
{
|
||||
"topic_name": "Software Testing and Debugging Techniques",
|
||||
"score": 9.530875
|
||||
},
|
||||
{
|
||||
"topic_name": "Digital Media Forensic Detection",
|
||||
"score": 9.530875
|
||||
},
|
||||
{
|
||||
"topic_name": "Infrared Thermography in Medicine",
|
||||
"score": 9.351548
|
||||
},
|
||||
{
|
||||
"topic_name": "Explainable Artificial Intelligence (XAI)",
|
||||
"score": 9.351548
|
||||
},
|
||||
{
|
||||
"topic_name": "Underwater Vehicles and Communication Systems",
|
||||
"score": 9.351548
|
||||
},
|
||||
{
|
||||
"topic_name": "Diffusion and Search Dynamics",
|
||||
"score": 8.8518915
|
||||
},
|
||||
{
|
||||
"topic_name": "Direction-of-Arrival Estimation Techniques",
|
||||
"score": 5.968384
|
||||
},
|
||||
{
|
||||
"topic_name": "Retinal Imaging and Analysis",
|
||||
"score": 5.6107
|
||||
},
|
||||
{
|
||||
"topic_name": "Radar Systems and Signal Processing",
|
||||
"score": 4.721418
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,6 +1,3 @@
|
||||
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic/
|
||||
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
|
||||
|
||||
LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/
|
||||
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
|
||||
LLM_MODEL=gemma4-e4b
|
||||
@@ -8,12 +5,15 @@ LLM_MODEL=gemma4-e4b
|
||||
# Patent search (EPO + USPTO)
|
||||
PATENT_ELASTICSEARCH_URL=https://inse.nes.uni-due.de/elastic
|
||||
PATENT_ELASTICSEARCH_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
|
||||
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic
|
||||
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
|
||||
|
||||
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
|
||||
ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
|
||||
LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/
|
||||
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
|
||||
LLM_MODEL=gemma4-e4b
|
||||
# Sentence Transformers Configuration
|
||||
SENTENCE_TRANSFORMERS_MODEL_NAME=paraphrase-multilingual-mpnet-base-v2
|
||||
|
||||
TOKEN_ISSUER_ID=inse
|
||||
TOKEN_HMAC_KEY=9dd09c80dd0796fa24bd2007f4cf57fc28c9a38909b7e83bb2d73121c5bc69c7
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from inse.auth.model import UserRole
|
||||
|
||||
|
||||
class OrganizationProfile(BaseModel):
|
||||
id: uuid.UUID
|
||||
name: str
|
||||
openalex_institution_id: Optional[str] = None
|
||||
|
||||
|
||||
class AccountProfile(BaseModel):
|
||||
id: uuid.UUID
|
||||
email: str
|
||||
name: str
|
||||
role: UserRole
|
||||
organization_id: uuid.UUID
|
||||
organization_name: str
|
||||
deleted: bool
|
||||
is_current: bool = False
|
||||
is_real_account: bool = False
|
||||
is_impersonating: bool = False
|
||||
|
||||
|
||||
class AccountPage(BaseModel):
|
||||
items: List[AccountProfile]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
|
||||
|
||||
class CreateAccountRequest(BaseModel):
|
||||
email: str = Field(min_length=3)
|
||||
name: str = Field(min_length=1)
|
||||
role: UserRole = UserRole.USER
|
||||
organization_id: uuid.UUID
|
||||
password: str = Field(min_length=8)
|
||||
openalex_person_id: Optional[str] = None
|
||||
|
||||
|
||||
class UpdateAccountRequest(BaseModel):
|
||||
email: Optional[str] = Field(default=None, min_length=3)
|
||||
name: Optional[str] = Field(default=None, min_length=1)
|
||||
role: Optional[UserRole] = None
|
||||
organization_id: Optional[uuid.UUID] = None
|
||||
password: Optional[str] = Field(default=None, min_length=8)
|
||||
openalex_person_id: Optional[str] = None
|
||||
deleted: Optional[bool] = None
|
||||
@@ -0,0 +1,125 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
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.database import get_session
|
||||
from inse.tags import Tags
|
||||
|
||||
from . import service
|
||||
from .model import (
|
||||
AccountPage,
|
||||
AccountProfile,
|
||||
CreateAccountRequest,
|
||||
OrganizationProfile,
|
||||
UpdateAccountRequest,
|
||||
)
|
||||
|
||||
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,
|
||||
) -> AccountProfile:
|
||||
return service.get_current_account(session=session, access_token=access_token)
|
||||
|
||||
|
||||
@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,
|
||||
) -> AccountPage:
|
||||
return service.list_accounts(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
offset=offset,
|
||||
search=search,
|
||||
organization_id=organization_id,
|
||||
)
|
||||
|
||||
|
||||
@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,
|
||||
) -> AccountProfile:
|
||||
return service.create_account(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
payload=payload,
|
||||
)
|
||||
|
||||
|
||||
@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,
|
||||
) -> list[OrganizationProfile]:
|
||||
return service.list_organizations(session=session, access_token=access_token)
|
||||
|
||||
|
||||
@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,
|
||||
) -> AccountProfile:
|
||||
return service.update_account(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
account_id=account_id,
|
||||
payload=payload,
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{account_id}",
|
||||
operation_id="deleteAccount",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
)
|
||||
async def delete_account(
|
||||
account_id: uuid.UUID,
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> Response:
|
||||
service.delete_account(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
account_id=account_id,
|
||||
)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -0,0 +1,311 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
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 .model import (
|
||||
AccountPage,
|
||||
AccountProfile,
|
||||
CreateAccountRequest,
|
||||
OrganizationProfile,
|
||||
UpdateAccountRequest,
|
||||
)
|
||||
|
||||
|
||||
def _is_admin(role: UserRole) -> bool:
|
||||
return role in {UserRole.SUPER_ADMIN, UserRole.ADMIN}
|
||||
|
||||
|
||||
def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool:
|
||||
if editor_role == UserRole.SUPER_ADMIN:
|
||||
return True
|
||||
if editor_role == UserRole.ADMIN:
|
||||
return role in {UserRole.MANAGER, UserRole.USER}
|
||||
return False
|
||||
|
||||
|
||||
def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile:
|
||||
organization_name = account.organization.name if account.organization else ""
|
||||
return AccountProfile(
|
||||
id=account.id,
|
||||
email=account.email,
|
||||
name=account.name,
|
||||
role=account.role,
|
||||
organization_id=account.organization_id,
|
||||
organization_name=organization_name,
|
||||
deleted=account.deleted,
|
||||
is_current=account.id == token.effective_account_id,
|
||||
is_real_account=account.id == token.real_account_id,
|
||||
is_impersonating=token.is_impersonating(),
|
||||
)
|
||||
|
||||
|
||||
def _get_account_or_404(session: Session, account_id: uuid.UUID) -> Account:
|
||||
account = session.get(Account, account_id)
|
||||
if account is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Account not found.",
|
||||
)
|
||||
return account
|
||||
|
||||
|
||||
def _ensure_account_in_editor_scope(account: Account, token: AccessToken) -> None:
|
||||
if token.effective_role == UserRole.SUPER_ADMIN:
|
||||
return
|
||||
if (
|
||||
token.effective_role == UserRole.ADMIN
|
||||
and account.organization_id == token.effective_organization_id
|
||||
):
|
||||
return
|
||||
if account.id == token.effective_account_id:
|
||||
return
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account is outside your scope.",
|
||||
)
|
||||
|
||||
|
||||
def _ensure_email_available(
|
||||
session: Session,
|
||||
email: str,
|
||||
excluded_account_id: Optional[uuid.UUID] = None,
|
||||
) -> None:
|
||||
normalized_email = email.lower().strip()
|
||||
if "@" not in normalized_email or "." not in normalized_email.rsplit("@", 1)[-1]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Invalid email address.",
|
||||
)
|
||||
|
||||
statement = select(Account).where(Account.email == normalized_email)
|
||||
if excluded_account_id is not None:
|
||||
statement = statement.where(Account.id != excluded_account_id)
|
||||
|
||||
existing = session.exec(statement).first()
|
||||
if existing is not None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Email address is already used by another account.",
|
||||
)
|
||||
|
||||
|
||||
def get_current_account(session: Session, access_token: AccessToken) -> 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,
|
||||
page: int,
|
||||
page_size: int,
|
||||
offset: Optional[int] = None,
|
||||
search: Optional[str] = None,
|
||||
organization_id: Optional[uuid.UUID] = None,
|
||||
) -> AccountPage:
|
||||
if not _is_admin(access_token.effective_role):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only admins can list accounts.",
|
||||
)
|
||||
|
||||
statement = select(Account)
|
||||
count_statement = select(func.count()).select_from(Account)
|
||||
|
||||
filters = []
|
||||
if access_token.effective_role == UserRole.ADMIN:
|
||||
filters.append(Account.organization_id == access_token.effective_organization_id)
|
||||
elif organization_id is not None:
|
||||
filters.append(Account.organization_id == organization_id)
|
||||
|
||||
if search:
|
||||
pattern = f"%{search.lower().strip()}%"
|
||||
filters.append(
|
||||
or_(
|
||||
func.lower(Account.name).like(pattern),
|
||||
func.lower(Account.email).like(pattern),
|
||||
)
|
||||
)
|
||||
|
||||
for filter_expression in filters:
|
||||
statement = statement.where(filter_expression)
|
||||
count_statement = count_statement.where(filter_expression)
|
||||
|
||||
total = session.exec(count_statement).one()
|
||||
effective_offset = offset if offset is not None else page * page_size
|
||||
accounts = session.exec(
|
||||
statement.order_by(Account.name).offset(effective_offset).limit(page_size)
|
||||
).all()
|
||||
|
||||
return AccountPage(
|
||||
items=[_account_to_profile(account, access_token) for account in accounts],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
|
||||
def create_account(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
payload: CreateAccountRequest,
|
||||
) -> AccountProfile:
|
||||
if not _is_admin(access_token.effective_role):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only admins can create accounts.",
|
||||
)
|
||||
|
||||
if (
|
||||
access_token.effective_role == UserRole.ADMIN
|
||||
and payload.organization_id != access_token.effective_organization_id
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Admins can only create accounts in their own organization.",
|
||||
)
|
||||
|
||||
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You cannot assign this role.",
|
||||
)
|
||||
|
||||
organization = session.get(Organization, payload.organization_id)
|
||||
if organization is None or organization.deleted:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Organization not found.",
|
||||
)
|
||||
|
||||
email = payload.email.lower().strip()
|
||||
_ensure_email_available(session, email)
|
||||
|
||||
account = Account(
|
||||
email=email,
|
||||
name=payload.name.strip(),
|
||||
role=payload.role,
|
||||
organization_id=payload.organization_id,
|
||||
password_hash=auth_service._hash_password(payload.password),
|
||||
openalex_person_id=payload.openalex_person_id,
|
||||
)
|
||||
session.add(account)
|
||||
session.commit()
|
||||
session.refresh(account)
|
||||
return _account_to_profile(account, access_token)
|
||||
|
||||
|
||||
def list_organizations(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
) -> list[OrganizationProfile]:
|
||||
if access_token.effective_role == UserRole.SUPER_ADMIN:
|
||||
organizations = session.exec(
|
||||
select(Organization)
|
||||
.where(Organization.deleted == False) # noqa: E712
|
||||
.order_by(Organization.name)
|
||||
).all()
|
||||
elif access_token.effective_role == UserRole.ADMIN:
|
||||
organization = session.get(Organization, access_token.effective_organization_id)
|
||||
organizations = [organization] if organization and not organization.deleted else []
|
||||
else:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
return [
|
||||
OrganizationProfile(
|
||||
id=organization.id,
|
||||
name=organization.name,
|
||||
openalex_institution_id=organization.openalex_institution_id,
|
||||
)
|
||||
for organization in organizations
|
||||
]
|
||||
|
||||
|
||||
def update_account(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
account_id: uuid.UUID,
|
||||
payload: UpdateAccountRequest,
|
||||
) -> AccountProfile:
|
||||
account = _get_account_or_404(session, account_id)
|
||||
_ensure_account_in_editor_scope(account, access_token)
|
||||
|
||||
is_self_update = account.id == access_token.effective_account_id
|
||||
can_admin_update = _is_admin(access_token.effective_role)
|
||||
|
||||
if not can_admin_update and not is_self_update:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
if payload.email is not None:
|
||||
email = payload.email.lower().strip()
|
||||
_ensure_email_available(session, email, excluded_account_id=account.id)
|
||||
account.email = email
|
||||
|
||||
if payload.name is not None:
|
||||
account.name = payload.name.strip()
|
||||
|
||||
if payload.password is not None:
|
||||
account.password_hash = auth_service._hash_password(payload.password)
|
||||
account.epoch += 1
|
||||
|
||||
if payload.openalex_person_id is not None:
|
||||
account.openalex_person_id = payload.openalex_person_id
|
||||
|
||||
if payload.role is not None:
|
||||
if not can_admin_update:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You cannot assign this role.",
|
||||
)
|
||||
account.role = payload.role
|
||||
account.epoch += 1
|
||||
|
||||
if payload.organization_id is not None:
|
||||
if access_token.effective_role != UserRole.SUPER_ADMIN:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
organization = session.get(Organization, payload.organization_id)
|
||||
if organization is None or organization.deleted:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Organization not found.",
|
||||
)
|
||||
account.organization_id = payload.organization_id
|
||||
account.epoch += 1
|
||||
|
||||
if payload.deleted is not None:
|
||||
if not can_admin_update or is_self_update:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
account.deleted = payload.deleted
|
||||
account.epoch += 1
|
||||
|
||||
session.add(account)
|
||||
session.commit()
|
||||
session.refresh(account)
|
||||
return _account_to_profile(account, access_token)
|
||||
|
||||
|
||||
def delete_account(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
account_id: uuid.UUID,
|
||||
) -> None:
|
||||
account = _get_account_or_404(session, account_id)
|
||||
_ensure_account_in_editor_scope(account, access_token)
|
||||
|
||||
if (
|
||||
not _is_admin(access_token.effective_role)
|
||||
or account.id == access_token.effective_account_id
|
||||
):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
account.deleted = True
|
||||
account.epoch += 1
|
||||
session.add(account)
|
||||
session.commit()
|
||||
@@ -0,0 +1,191 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
from sqlmodel import Field, Relationship, SQLModel
|
||||
|
||||
|
||||
class UserRole(StrEnum):
|
||||
SUPER_ADMIN = "SUPER_ADMIN"
|
||||
ADMIN = "ADMIN"
|
||||
MANAGER = "MANAGER"
|
||||
USER = "USER"
|
||||
|
||||
|
||||
class TokenType(StrEnum):
|
||||
ID_TOKEN = "ID"
|
||||
REFRESH_TOKEN = "REFRESH"
|
||||
ACCESS_TOKEN = "ACCESS"
|
||||
|
||||
|
||||
class Durable(SQLModel):
|
||||
deleted: bool = Field(
|
||||
default=False,
|
||||
nullable=False,
|
||||
index=True,
|
||||
description="Indicates whether the record is marked as deleted.",
|
||||
)
|
||||
|
||||
|
||||
class Organization(Durable, table=True):
|
||||
id: uuid.UUID | None = Field(
|
||||
default_factory=uuid.uuid4,
|
||||
primary_key=True,
|
||||
description="Unique identifier for the organization. Generated automatically if not provided.",
|
||||
)
|
||||
name: str = Field(
|
||||
index=True, nullable=False, description="The name of the organization."
|
||||
)
|
||||
openalex_institution_id: str | None = Field(
|
||||
default=None,
|
||||
index=True,
|
||||
description="The OpenAlex ID of the institution associated with the organization.",
|
||||
)
|
||||
|
||||
accounts: List["Account"] = Relationship(back_populates="organization")
|
||||
|
||||
|
||||
class Account(Durable, table=True):
|
||||
id: uuid.UUID | None = Field(
|
||||
default_factory=uuid.uuid4,
|
||||
primary_key=True,
|
||||
description="Unique identifier for the account. Generated automatically if not provided.",
|
||||
)
|
||||
email: str = Field(
|
||||
index=True,
|
||||
unique=True,
|
||||
nullable=False,
|
||||
description="The email address associated with the account.",
|
||||
)
|
||||
name: str = Field(
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The name of the account holder.",
|
||||
)
|
||||
openalex_person_id: str | None = Field(
|
||||
default=None,
|
||||
index=True,
|
||||
description="The OpenAlex ID of the person associated with the account.",
|
||||
)
|
||||
epoch: int = Field(
|
||||
default=0,
|
||||
nullable=False,
|
||||
description="The epoch value for the account. Used for versioning of tokens.",
|
||||
)
|
||||
password_hash: str = Field(
|
||||
index=False,
|
||||
nullable=False,
|
||||
description="The hashed password for the account using Argon2id algorithm.",
|
||||
# https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
|
||||
)
|
||||
|
||||
organization_id: uuid.UUID = Field(
|
||||
foreign_key="organization.id",
|
||||
nullable=False,
|
||||
description="The unique identifier of the organization strictly associated with this account.",
|
||||
)
|
||||
role: UserRole = Field(
|
||||
default=UserRole.USER,
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The specific role this account holds within its organization.",
|
||||
)
|
||||
|
||||
organization: Organization = Relationship(back_populates="accounts")
|
||||
|
||||
|
||||
class Secret(SQLModel, table=True):
|
||||
id: uuid.UUID | None = Field(
|
||||
default_factory=uuid.uuid4,
|
||||
primary_key=True,
|
||||
description="Unique identifier for the secret. Generated automatically if not provided.",
|
||||
)
|
||||
account_id: uuid.UUID = Field(
|
||||
foreign_key="account.id",
|
||||
unique=True, # Ensure that each account can have only one associated secret
|
||||
nullable=False,
|
||||
description="The unique identifier of the account associated with this secret.",
|
||||
)
|
||||
secret_value: str = Field(
|
||||
index=False,
|
||||
nullable=False,
|
||||
description="The actual secret value. This should be stored securely and encrypted.",
|
||||
)
|
||||
expires_at: datetime = Field(
|
||||
index=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(
|
||||
nullable=False,
|
||||
description="The unique identifier of the real account associated with this token.",
|
||||
)
|
||||
expires_at: datetime = Field(
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The timestamp indicating when the token will expire.",
|
||||
)
|
||||
epoch: int = Field(
|
||||
default=0,
|
||||
nullable=False,
|
||||
description="The epoch value for the token. Used for versioning of tokens.",
|
||||
)
|
||||
user_fingerprint_hash: str = Field(
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="A hash of the user's fingerprint to ensure the token is used by the same user.",
|
||||
)
|
||||
|
||||
|
||||
class IdToken(Token):
|
||||
token_type: TokenType = Field(
|
||||
default=TokenType.ID_TOKEN,
|
||||
const=True,
|
||||
description="The type of the token, which is always ID_TOKEN for this class.",
|
||||
)
|
||||
|
||||
|
||||
class AccessToken(Token):
|
||||
token_type: TokenType = Field(
|
||||
default=TokenType.ACCESS_TOKEN,
|
||||
const=True,
|
||||
description="The type of the token, which is always ACCESS_TOKEN for this class.",
|
||||
)
|
||||
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.",
|
||||
)
|
||||
|
||||
def is_impersonating(self) -> bool:
|
||||
"""Determine if the access token is being used for impersonation.
|
||||
|
||||
Returns:
|
||||
bool: True if the effective account ID differs from the real account ID, indicating impersonation; False otherwise.
|
||||
"""
|
||||
return self.effective_account_id != self.real_account_id
|
||||
|
||||
|
||||
class RefreshToken(AccessToken):
|
||||
token_type: TokenType = Field(
|
||||
default=TokenType.REFRESH_TOKEN,
|
||||
const=True,
|
||||
description="The type of the token, which is always REFRESH_TOKEN for this class.",
|
||||
)
|
||||
@@ -0,0 +1,156 @@
|
||||
import logging
|
||||
from typing import Annotated, Dict
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Response, status
|
||||
from sqlmodel import Session
|
||||
|
||||
from inse.tags import Tags
|
||||
|
||||
import inse.auth.service as auth_service
|
||||
from inse.database import SessionDep, get_session
|
||||
from inse.auth.model import AccessToken, IdToken, RefreshToken
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/auth/v2", tags=[Tags.AUTH])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health_check():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post(
|
||||
"/request-otk",
|
||||
summary="Request One-Time Key",
|
||||
description="Request a one-time key (OTK) for authentication using email and password.",
|
||||
operation_id="requestOtk",
|
||||
responses={
|
||||
status.HTTP_200_OK: {"description": "One-time key requested successfully."}
|
||||
},
|
||||
)
|
||||
async def request_otk(
|
||||
session: SessionDep,
|
||||
email: Annotated[str, Body(description="User's email address")],
|
||||
password: Annotated[str, Body(description="User's password")],
|
||||
):
|
||||
return auth_service.request_otk(session=session, email=email, password=password)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/login",
|
||||
summary="Login with One-Time Key",
|
||||
description="Login using a one-time key (OTK) sent to the user's email.",
|
||||
operation_id="login",
|
||||
responses={status.HTTP_200_OK: {"description": "Login successful."}},
|
||||
)
|
||||
async def login(
|
||||
session: SessionDep,
|
||||
response: Response,
|
||||
account_id: Annotated[uuid.UUID, Body(description="User's account ID")],
|
||||
email_code: Annotated[
|
||||
str, Body(embed=True, description="One-time code sent to user's email")
|
||||
],
|
||||
):
|
||||
return auth_service.login(
|
||||
session=session, response=response, account_id=account_id, email_code=email_code
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/access",
|
||||
summary="Get Access Token",
|
||||
description="Retrieve an access token for the authenticated user.",
|
||||
operation_id="getAccessToken",
|
||||
responses={
|
||||
status.HTTP_200_OK: {"description": "Access token retrieved successfully."}
|
||||
},
|
||||
)
|
||||
async def get_action_tokens(
|
||||
response: Response,
|
||||
session: SessionDep,
|
||||
real_account_id: Annotated[uuid.UUID, Body(description="User's account ID")],
|
||||
effective_account_id: Annotated[
|
||||
uuid.UUID, Body(description="Effective account ID for the access token")
|
||||
],
|
||||
id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep],
|
||||
) -> Dict[str, str]:
|
||||
logger.debug(
|
||||
"Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s",
|
||||
real_account_id,
|
||||
effective_account_id,
|
||||
id_token,
|
||||
)
|
||||
|
||||
return auth_service.get_access_token(
|
||||
response=response,
|
||||
session=session,
|
||||
real_account_id=real_account_id,
|
||||
effective_account_id=effective_account_id,
|
||||
id_token=id_token,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/refresh",
|
||||
summary="Refresh Access Token",
|
||||
description="Refresh the access token using a valid refresh token.",
|
||||
operation_id="refreshAccessToken",
|
||||
responses={
|
||||
status.HTTP_200_OK: {"description": "Access token refreshed successfully."}
|
||||
},
|
||||
)
|
||||
async def refresh_access_token(
|
||||
refresh_token: Annotated[
|
||||
RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep
|
||||
],
|
||||
) -> str:
|
||||
return auth_service.refresh_access_token(refresh_token=refresh_token)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/logout",
|
||||
summary="Logout",
|
||||
description="Logout the authenticated user.",
|
||||
operation_id="logout",
|
||||
responses={status.HTTP_200_OK: {"description": "Logout successful."}},
|
||||
)
|
||||
async def logout(
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
access_token: Annotated[
|
||||
AccessToken,
|
||||
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
],
|
||||
):
|
||||
return auth_service.logout(session=session, access_token=access_token)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/change-password",
|
||||
summary="Change Password",
|
||||
description="Change the user's password and invalidate existing tokens.",
|
||||
operation_id="changePassword",
|
||||
responses={status.HTTP_200_OK: {"description": "Password changed successfully."}},
|
||||
)
|
||||
async def change_password(
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
current_password: Annotated[
|
||||
str,
|
||||
Body(description="Current password"),
|
||||
],
|
||||
new_password: Annotated[
|
||||
str,
|
||||
Body(description="New password", min_length=8),
|
||||
],
|
||||
access_token: Annotated[
|
||||
AccessToken,
|
||||
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
],
|
||||
):
|
||||
return auth_service.change_password(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
current_password=current_password,
|
||||
new_password=new_password,
|
||||
)
|
||||
@@ -0,0 +1,948 @@
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
import uuid
|
||||
import logging
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.text import MIMEText
|
||||
from typing import Annotated, Any, Dict, Literal, Optional
|
||||
|
||||
import jwt
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
||||
from fastapi import Depends, HTTPException, Request, Response, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from inse.auth.model import (
|
||||
AccessToken,
|
||||
Account,
|
||||
IdToken,
|
||||
Organization,
|
||||
RefreshToken,
|
||||
Secret,
|
||||
TokenType,
|
||||
UserRole,
|
||||
)
|
||||
from inse.config import get_settings
|
||||
from inse.database import get_session
|
||||
from sqlmodel import Session, select, func
|
||||
|
||||
ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days
|
||||
REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes
|
||||
ACCESS_TOKEN_EXPIRATION_MINUTES = 5 # 5 minutes
|
||||
|
||||
OTK_EXPIRATION_MINUTES = 15 # 15 minutes
|
||||
|
||||
REAL_ACCOUNT_ID_KEY = "real_account_id"
|
||||
EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id"
|
||||
EFFECTIVE_ROLE_KEY = "effective_role"
|
||||
EPOCH_KEY = "epoch"
|
||||
ORGANIZATION_ID_KEY = "organization_id"
|
||||
USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash"
|
||||
|
||||
ID_FP_COOKIE_KEY = "_Secure-Fgp-ID"
|
||||
ACT_FP_COOKIE_KEY = "_Secure-Fgp-Act"
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
security_scheme = HTTPBearer()
|
||||
|
||||
_password_hasher = PasswordHasher()
|
||||
|
||||
AccountNotFoundException = HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Account not found.",
|
||||
)
|
||||
|
||||
|
||||
def create_predefined_accounts(session: Session, file_path: str):
|
||||
"""Creates predefined accounts and organizations in the database from a JSON file. This function is intended to be used for development and testing purposes, and it will not run in a production environment.
|
||||
|
||||
Args:
|
||||
session (Session): The database session used to add the predefined accounts and organizations.
|
||||
file_path (str): The path to the JSON file containing the predefined accounts and organizations.
|
||||
"""
|
||||
|
||||
if settings.environment == "prod":
|
||||
logger.info(
|
||||
"Skipping predefined accounts population in production environment."
|
||||
)
|
||||
return
|
||||
|
||||
account_count = session.exec(select(func.count()).select_from(Account)).one()
|
||||
if account_count > 0:
|
||||
logger.info(
|
||||
"Skipping predefined accounts population as accounts already exist in the database."
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
with open(file_path, "r") as file:
|
||||
data = json.loads(file.read())
|
||||
for organization_data in data.get("organizations", []):
|
||||
organization_id = uuid.UUID(organization_data["id"])
|
||||
organization_name = organization_data["name"]
|
||||
organization = Organization(id=organization_id, name=organization_name)
|
||||
session.add(organization)
|
||||
for account_data in data.get("accounts", []):
|
||||
organization_id = uuid.UUID(account_data["organization_id"])
|
||||
role = UserRole(account_data["role"])
|
||||
email = account_data["email"]
|
||||
password_hash = _hash_password(account_data["password"])
|
||||
account = Account(
|
||||
email=email,
|
||||
name=account_data["name"],
|
||||
organization_id=organization_id,
|
||||
role=role,
|
||||
password_hash=password_hash,
|
||||
epoch=0,
|
||||
)
|
||||
session.add(account)
|
||||
|
||||
session.commit()
|
||||
logger.info("Predefined accounts and organizations populated successfully.")
|
||||
except FileNotFoundError:
|
||||
logger.error(
|
||||
"Predefined accounts file not found at %s. Skipping population.",
|
||||
file_path,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception(
|
||||
"Error occurred while populating predefined accounts: %s. Skipping population.",
|
||||
str(e),
|
||||
)
|
||||
|
||||
|
||||
def _hash_password(password: str) -> str:
|
||||
"""Hashes the provided password using Argon2 and returns the hashed value.
|
||||
|
||||
Args:
|
||||
password (str): The password to hash.
|
||||
|
||||
Returns:
|
||||
str: The hashed password.
|
||||
"""
|
||||
return _password_hasher.hash(password)
|
||||
|
||||
|
||||
def _verify_password(password: str, password_hash: str) -> bool:
|
||||
"""Verifies the provided password against the stored password hash using Argon2.
|
||||
|
||||
Args:
|
||||
password (str): The password to verify.
|
||||
password_hash (str): The stored password hash to verify against.
|
||||
|
||||
Returns:
|
||||
bool: True if the password is correct, False otherwise.
|
||||
"""
|
||||
try:
|
||||
return _password_hasher.verify(password_hash, password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
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.
|
||||
|
||||
Args:
|
||||
session (Session): The database session used to query the account and secret.
|
||||
email (str): The user's email address.
|
||||
password (str): The user's password.
|
||||
|
||||
|
||||
Raises:
|
||||
HTTPException: If the email or password is invalid.
|
||||
HTTPException: If the account is not found.
|
||||
"""
|
||||
email = email.lower().strip()
|
||||
|
||||
logger.debug("OTK request for email %s: starting validation", email)
|
||||
account = session.exec(
|
||||
select(Account).where(
|
||||
Account.email == email,
|
||||
Account.deleted == False, # noqa: E712
|
||||
)
|
||||
).first()
|
||||
|
||||
logger.debug("OTK request for email %s: account found: %s", email, account)
|
||||
|
||||
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,
|
||||
detail="Invalid email or password",
|
||||
)
|
||||
|
||||
if not _verify_password(password, account.password_hash):
|
||||
logger.warning(
|
||||
"OTK request failed for email %s: password verification failed", email
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid email or password",
|
||||
)
|
||||
|
||||
otk_code = f"{secrets.randbelow(1_000_000):06d}"
|
||||
print(otk_code)
|
||||
|
||||
secret = session.exec(select(Secret).where(Secret.account_id == account.id)).first()
|
||||
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
minutes=OTK_EXPIRATION_MINUTES
|
||||
)
|
||||
|
||||
if secret is None:
|
||||
secret = Secret(
|
||||
account_id=account.id,
|
||||
secret_value=otk_code,
|
||||
expires_at=expires_at,
|
||||
)
|
||||
session.add(secret)
|
||||
else:
|
||||
secret.secret_value = otk_code
|
||||
secret.expires_at = expires_at
|
||||
|
||||
session.commit()
|
||||
|
||||
if settings.environment == "prod":
|
||||
logger.info(
|
||||
"Saved OTK for account %s with expiration at %s",
|
||||
account.id,
|
||||
expires_at,
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
"OTK code for account %s: %s, expires at %s",
|
||||
account.id,
|
||||
otk_code,
|
||||
expires_at,
|
||||
)
|
||||
|
||||
return {"status": "ok", "account_id": str(account.id)}
|
||||
|
||||
|
||||
def login(session: Session, response: Response, account_id: uuid.UUID, email_code: str):
|
||||
"""Login using a one-time key (OTK) sent to the user's email. Validates the OTK and generates an ID token for the user.
|
||||
|
||||
Args:
|
||||
session (Session): The database session used to query the account and secret.
|
||||
response (Response): The response object to set the ID token cookie.
|
||||
account_id (uuid.UUID): The unique identifier of the account associated with the one-time code.
|
||||
email_code (str): The one-time code sent to the user's email.
|
||||
|
||||
Raises:
|
||||
HTTPException: If the code is invalid or expired.
|
||||
HTTPException: If the account is not active.
|
||||
"""
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
|
||||
secret = session.exec(
|
||||
select(Secret).where(
|
||||
Secret.account_id == account_id,
|
||||
Secret.secret_value == email_code,
|
||||
# Validating the code and ensuring it matches the account ID
|
||||
)
|
||||
).first()
|
||||
|
||||
if not settings.skip_otk_validation:
|
||||
if secret is None or secret.expires_at <= now:
|
||||
logger.warning("Login failed: invalid or expired code %s", email_code)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired code",
|
||||
)
|
||||
session.delete(secret)
|
||||
|
||||
else:
|
||||
if settings.environment == "prod":
|
||||
logger.warning(
|
||||
"Skipping OTK validation in production environment for account %s.",
|
||||
account_id,
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
"Skipping OTK validation for account %s due to configuration setting.",
|
||||
account_id,
|
||||
)
|
||||
|
||||
account = _get_active_account(session, account_id)
|
||||
if not account or account.deleted or account.id is None:
|
||||
logger.warning("Login failed: account is not active %s", account_id)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account is not active.",
|
||||
)
|
||||
|
||||
id_token = _build_id_token(
|
||||
response,
|
||||
account.id,
|
||||
account.epoch,
|
||||
)
|
||||
|
||||
session.commit()
|
||||
|
||||
return {"id_token": id_token}
|
||||
|
||||
|
||||
def _get_current_user_access_token_payload(
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
request: Request,
|
||||
credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)],
|
||||
) -> AccessToken:
|
||||
"""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:
|
||||
session (Annotated[Session, Depends): The database session used to query the account and secret.
|
||||
request (Request): The request object containing the access token.
|
||||
credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the access token.
|
||||
|
||||
Returns:
|
||||
AccessToken: The verified access token payload.
|
||||
"""
|
||||
|
||||
token = credentials.credentials
|
||||
|
||||
access_token_payload = _verify_fp_token(
|
||||
request=request,
|
||||
cookie_key=ACT_FP_COOKIE_KEY,
|
||||
token=token,
|
||||
session=session,
|
||||
)
|
||||
# If reaches here, the access token is valid and the fingerprint matches
|
||||
|
||||
return AccessToken(
|
||||
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(
|
||||
access_token_payload["exp"], tz=datetime.timezone.utc
|
||||
),
|
||||
epoch=access_token_payload[EPOCH_KEY],
|
||||
effective_role=UserRole(access_token_payload[EFFECTIVE_ROLE_KEY]),
|
||||
effective_organization_id=uuid.UUID(access_token_payload[ORGANIZATION_ID_KEY]),
|
||||
user_fingerprint_hash=access_token_payload[USER_FINGERPRINT_HASH_KEY],
|
||||
)
|
||||
|
||||
|
||||
def _get_current_user_refresh_token_payload(
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
request: Request,
|
||||
credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)],
|
||||
) -> RefreshToken:
|
||||
"""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:
|
||||
session (Annotated[Session, Depends): The database session used to query the account and secret.
|
||||
request (Request): The request object containing the refresh token.
|
||||
credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the refresh token.
|
||||
|
||||
Returns:
|
||||
RefreshToken: The verified refresh token payload.
|
||||
"""
|
||||
token = credentials.credentials
|
||||
|
||||
refresh_token_payload = _verify_fp_token(
|
||||
request=request,
|
||||
cookie_key=ACT_FP_COOKIE_KEY,
|
||||
token=token,
|
||||
session=session,
|
||||
)
|
||||
# If reaches here, the refresh token is valid and the fingerprint matches
|
||||
refresh_token = RefreshToken(
|
||||
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(
|
||||
refresh_token_payload["exp"], tz=datetime.timezone.utc
|
||||
),
|
||||
epoch=refresh_token_payload[EPOCH_KEY],
|
||||
effective_role=UserRole(refresh_token_payload[EFFECTIVE_ROLE_KEY]),
|
||||
effective_organization_id=uuid.UUID(refresh_token_payload[ORGANIZATION_ID_KEY]),
|
||||
user_fingerprint_hash=refresh_token_payload[USER_FINGERPRINT_HASH_KEY],
|
||||
)
|
||||
|
||||
logger.debug("Extracted refresh token payload: %s", refresh_token)
|
||||
|
||||
return refresh_token
|
||||
|
||||
|
||||
def _get_current_user_id_token_payload(
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
request: Request,
|
||||
credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)],
|
||||
) -> IdToken:
|
||||
"""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:
|
||||
session (Annotated[Session, Depends): The database session used to query the account and secret.
|
||||
request (Request): The request object containing the ID token.
|
||||
credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the ID token.
|
||||
|
||||
Returns:
|
||||
Dict[str, Any]: 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)
|
||||
|
||||
id_token_payload = _verify_fp_token(
|
||||
request=request,
|
||||
cookie_key=ID_FP_COOKIE_KEY,
|
||||
token=token,
|
||||
session=session,
|
||||
)
|
||||
# If reaches here, the ID token is valid and the fingerprint matches
|
||||
|
||||
return IdToken(
|
||||
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],
|
||||
)
|
||||
|
||||
|
||||
CurrentUserAccessTokenPayloadDep = Depends(_get_current_user_access_token_payload)
|
||||
CurrentUserRefreshTokenPayloadDep = Depends(_get_current_user_refresh_token_payload)
|
||||
CurrentUserIdTokenPayloadDep = Depends(_get_current_user_id_token_payload)
|
||||
|
||||
|
||||
def _get_account_epoch(
|
||||
session: Session,
|
||||
account_id: uuid.UUID,
|
||||
) -> int:
|
||||
"""Retrieves the current epoch value for the specified account ID, ensuring that the account exists and is not deleted.
|
||||
|
||||
Args:
|
||||
session (Session): The database session used to query the account.
|
||||
account_id (uuid.UUID): The unique identifier of the account for which to retrieve the epoch.
|
||||
|
||||
Raises:
|
||||
HTTPException: If the account does not exist, is deleted, or has no valid ID.
|
||||
|
||||
Returns:
|
||||
int: The current epoch value for the account.
|
||||
"""
|
||||
account = session.get(Account, account_id)
|
||||
|
||||
if account is None or account.deleted or account.id is None:
|
||||
raise AccountNotFoundException
|
||||
|
||||
return account.epoch
|
||||
|
||||
|
||||
def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole:
|
||||
"""Retrieves the role for the given account ID.
|
||||
|
||||
Args:
|
||||
session (Session): The database session.
|
||||
account_id (uuid.UUID): The unique identifier of the account for which to retrieve the role.
|
||||
|
||||
Returns:
|
||||
UserRole: The role associated with the given account ID.
|
||||
"""
|
||||
account = session.get(Account, account_id)
|
||||
|
||||
if not account or account.deleted or account.id is None:
|
||||
raise AccountNotFoundException
|
||||
|
||||
return account.role
|
||||
|
||||
|
||||
def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.UUID:
|
||||
"""Retrieves the organization ID for the given account ID.
|
||||
|
||||
Args:
|
||||
session (Session): The database session.
|
||||
account_id (uuid.UUID): The unique identifier of the account for which to retrieve the organization ID.
|
||||
|
||||
Returns:
|
||||
uuid.UUID: The organization ID associated with the given account ID.
|
||||
"""
|
||||
account = session.get(Account, account_id)
|
||||
|
||||
if not account or account.deleted or account.id is None:
|
||||
raise AccountNotFoundException
|
||||
|
||||
return account.organization_id
|
||||
|
||||
|
||||
def _is_valid_impersonation(
|
||||
session: Session, real_account_id: uuid.UUID, effective_account_id: uuid.UUID
|
||||
) -> bool:
|
||||
"""Checks if the real account is allowed to impersonate the effective account.
|
||||
|
||||
Args:
|
||||
session (Session): The database session.
|
||||
real_account_id (uuid.UUID): The unique identifier of the real account.
|
||||
effective_account_id (uuid.UUID): The unique identifier of the effective account.
|
||||
|
||||
Returns:
|
||||
bool: True if impersonation is allowed, False otherwise.
|
||||
"""
|
||||
real_account = session.get(Account, real_account_id)
|
||||
if not real_account or real_account.deleted or real_account.id is None:
|
||||
raise AccountNotFoundException
|
||||
effective_account = session.get(Account, effective_account_id)
|
||||
if (
|
||||
not effective_account
|
||||
or effective_account.deleted
|
||||
or effective_account.id is None
|
||||
):
|
||||
raise AccountNotFoundException
|
||||
|
||||
if real_account.role == UserRole.SUPER_ADMIN:
|
||||
return True # Super admins can impersonate any account
|
||||
|
||||
if real_account.organization_id != effective_account.organization_id:
|
||||
return False # Cannot impersonate accounts from different organizations
|
||||
|
||||
if real_account.role == UserRole.ADMIN and effective_account.role in [
|
||||
UserRole.MANAGER,
|
||||
UserRole.USER,
|
||||
]:
|
||||
return True # Admins can impersonate managers and users within the same organization
|
||||
|
||||
if (
|
||||
real_account.role == UserRole.MANAGER
|
||||
and effective_account.role == UserRole.USER
|
||||
):
|
||||
return True # Managers can impersonate users within the same organization
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def get_access_token(
|
||||
response: Response,
|
||||
session: Session,
|
||||
id_token: IdToken,
|
||||
real_account_id: uuid.UUID,
|
||||
effective_account_id: Optional[uuid.UUID] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""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:
|
||||
Dict[str, Any]: A dictionary 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:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Real account ID does not match ID token",
|
||||
)
|
||||
|
||||
if effective_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",
|
||||
)
|
||||
else:
|
||||
# No impersonation, set effective_account_id to real_account_id
|
||||
effective_account_id = real_account_id
|
||||
|
||||
role = _get_account_role(session=session, account_id=effective_account_id)
|
||||
epoch = _get_account_epoch(account_id=effective_account_id, session=session)
|
||||
organization_id = _get_account_organization(
|
||||
session=session, account_id=effective_account_id
|
||||
)
|
||||
|
||||
user_fingerprint_hash = _set_act_fp_cookie(response=response)
|
||||
|
||||
access_token_payload = {
|
||||
REAL_ACCOUNT_ID_KEY: str(real_account_id),
|
||||
EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id),
|
||||
EPOCH_KEY: epoch,
|
||||
EFFECTIVE_ROLE_KEY: role.value,
|
||||
ORGANIZATION_ID_KEY: str(organization_id),
|
||||
USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
|
||||
}
|
||||
|
||||
return _build_action_tokens(
|
||||
payload=access_token_payload,
|
||||
)
|
||||
|
||||
|
||||
def _set_id_fp_cookie(response: Response) -> str:
|
||||
"""Sets a secure fingerprint cookie for ID 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, ID_FP_COOKIE_KEY, max_age=ID_TOKEN_EXPIRATION_MINUTES * 60
|
||||
)
|
||||
|
||||
|
||||
def _set_act_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,
|
||||
value=user_fingerprint,
|
||||
httponly=True,
|
||||
secure=secure,
|
||||
samesite="strict",
|
||||
max_age=max_age,
|
||||
)
|
||||
return hashlib.sha256(user_fingerprint.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def refresh_access_token(refresh_token: RefreshToken) -> str:
|
||||
"""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.
|
||||
session (Session): The database session.
|
||||
refresh_token (RefreshToken): The refresh token to verify.
|
||||
|
||||
Returns:
|
||||
str: The refreshed access token.
|
||||
"""
|
||||
# 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,
|
||||
) -> str:
|
||||
"""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:
|
||||
str: The refreshed access token.
|
||||
"""
|
||||
# IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here.
|
||||
|
||||
access_payload = {
|
||||
REAL_ACCOUNT_ID_KEY: str(refresh_token.real_account_id),
|
||||
EFFECTIVE_ACCOUNT_ID_KEY: str(refresh_token.effective_account_id),
|
||||
EPOCH_KEY: refresh_token.epoch,
|
||||
EFFECTIVE_ROLE_KEY: refresh_token.effective_role,
|
||||
ORGANIZATION_ID_KEY: str(refresh_token.effective_organization_id),
|
||||
USER_FINGERPRINT_HASH_KEY: refresh_token.user_fingerprint_hash,
|
||||
}
|
||||
return _build_token(
|
||||
payload=access_payload,
|
||||
expiration_min=ACCESS_TOKEN_EXPIRATION_MINUTES,
|
||||
token_type=TokenType.ACCESS_TOKEN,
|
||||
)
|
||||
|
||||
|
||||
def _build_id_token(response: Response, real_account_id: uuid.UUID, epoch: int) -> str:
|
||||
"""Builds an ID token for the specified real account ID and sets the appropriate fingerprint cookie.
|
||||
|
||||
Args:
|
||||
response (Response): The FastAPI response object to which the cookie will be added.
|
||||
real_account_id (uuid.UUID): The UUID of the real account.
|
||||
epoch (int): The epoch value for the tokens.
|
||||
|
||||
Returns:
|
||||
str: The built ID token.
|
||||
"""
|
||||
|
||||
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,
|
||||
}
|
||||
return _build_token(
|
||||
payload=payload,
|
||||
expiration_min=ID_TOKEN_EXPIRATION_MINUTES,
|
||||
token_type=TokenType.ID_TOKEN,
|
||||
)
|
||||
|
||||
|
||||
def _build_action_tokens(
|
||||
payload: Dict[str, Any],
|
||||
) -> Dict[str, str]:
|
||||
"""Builds both access and refresh tokens for the specified account IDs and sets the appropriate fingerprint cookies.
|
||||
|
||||
Args:
|
||||
response (Response): The FastAPI response object to which the cookies will be added.
|
||||
real_account_id (uuid.UUID): The UUID of the real account.
|
||||
effective_account_id (uuid.UUID): The UUID of the effective account.
|
||||
epoch (int): The epoch value for the tokens.
|
||||
|
||||
Returns:
|
||||
Dict[str, str]: A dictionary containing the built access and refresh tokens.
|
||||
"""
|
||||
|
||||
return {
|
||||
"access_token": _build_token(
|
||||
payload=payload,
|
||||
expiration_min=ACCESS_TOKEN_EXPIRATION_MINUTES,
|
||||
token_type=TokenType.ACCESS_TOKEN,
|
||||
),
|
||||
"refresh_token": _build_token(
|
||||
payload=payload,
|
||||
expiration_min=REFRESH_TOKEN_EXPIRATION_MINUTES,
|
||||
token_type=TokenType.REFRESH_TOKEN,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _build_token(
|
||||
payload: Dict[str, Any], expiration_min: int, token_type: TokenType
|
||||
) -> str:
|
||||
"""Builds a JWT token with the given payload and expiration time.
|
||||
|
||||
Args:
|
||||
payload (Dict[str, Any]): The payload to encode in the JWT.
|
||||
expiration_min (int): The expiration time in minutes.
|
||||
token_type (TokenType): The type of the token to build.
|
||||
|
||||
Returns:
|
||||
str: The encoded JWT token.
|
||||
"""
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
expiration_date = now + datetime.timedelta(minutes=expiration_min)
|
||||
payload.update(
|
||||
{
|
||||
"exp": expiration_date,
|
||||
"iss": settings.token_issuer_id,
|
||||
"iat": now,
|
||||
"nbf": now,
|
||||
"type": token_type.value,
|
||||
}
|
||||
)
|
||||
if not settings.token_hmac_key:
|
||||
raise ValueError("Token HMAC key is not set in the configuration.")
|
||||
token = jwt.encode(payload, settings.token_hmac_key, algorithm="HS256")
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
Raises:
|
||||
ValueError: If the token HMAC key is not set in the configuration.
|
||||
HTTPException: If the fingerprint cookie is missing or does not match the token's fingerprint.
|
||||
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 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()
|
||||
|
||||
try:
|
||||
payload = jwt.decode(
|
||||
token,
|
||||
settings.token_hmac_key,
|
||||
algorithms=["HS256"],
|
||||
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)
|
||||
if effective_account_id:
|
||||
epoch_account_id = uuid.UUID(effective_account_id)
|
||||
|
||||
current_account_epoch = _get_account_epoch(
|
||||
session=session,
|
||||
account_id=epoch_account_id,
|
||||
)
|
||||
|
||||
token_epoch = payload.get(EPOCH_KEY)
|
||||
if token_epoch is None or token_epoch != current_account_epoch:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token epoch mismatch",
|
||||
)
|
||||
|
||||
return payload
|
||||
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has expired",
|
||||
)
|
||||
except jwt.InvalidTokenError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid token",
|
||||
)
|
||||
|
||||
|
||||
def _get_active_account(session: Session, account_id: uuid.UUID) -> Account:
|
||||
"""Gets the active account for the given account ID, ensuring that the account exists and is not deleted.
|
||||
|
||||
Args:
|
||||
session (Session): The database session used to query the account.
|
||||
account_id (uuid.UUID): The ID of the account to retrieve.
|
||||
|
||||
Raises:
|
||||
HTTPException: If the account does not exist or is deleted.
|
||||
|
||||
Returns:
|
||||
Account: The active account if it exists and is not deleted.
|
||||
"""
|
||||
account = session.get(Account, account_id)
|
||||
|
||||
if account is None or account.deleted or account.id is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account is not active.",
|
||||
)
|
||||
|
||||
return account
|
||||
|
||||
|
||||
def logout(session: Session, access_token: AccessToken) -> 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:
|
||||
request (Request): The FastAPI request object.
|
||||
session (Session): The database session used to query the account.
|
||||
access_token (AccessToken): The access token for the user to logout.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary containing the status of the logout operation.
|
||||
"""
|
||||
|
||||
account = _get_active_account(session, access_token.effective_account_id)
|
||||
|
||||
account.epoch += 1
|
||||
|
||||
session.add(account)
|
||||
session.commit()
|
||||
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
def change_password(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
current_password: str,
|
||||
new_password: str,
|
||||
) -> Dict[str, str]:
|
||||
"""Change the password for the user associated with the provided access token.
|
||||
|
||||
Args:
|
||||
request (Request): The FastAPI request object.
|
||||
session (Session): The database session used to query the account.
|
||||
access_token (AccessToken): The access token for the user.
|
||||
current_password (str): The current password for the user.
|
||||
new_password (str): The new password for the user.
|
||||
|
||||
Raises:
|
||||
HTTPException: If the access token is invalid or the current password is incorrect.
|
||||
|
||||
Returns:
|
||||
Dict[str, str]: A dictionary containing the status of the password change operation.
|
||||
"""
|
||||
account = _get_active_account(session, access_token.effective_account_id)
|
||||
|
||||
if not _verify_password(current_password, account.password_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Current password is incorrect.",
|
||||
)
|
||||
|
||||
account.password_hash = _hash_password(new_password)
|
||||
account.epoch += 1
|
||||
|
||||
session.add(account)
|
||||
session.commit()
|
||||
|
||||
return {"status": "ok"}
|
||||
@@ -7,7 +7,7 @@ that can be adjusted via environment variables.
|
||||
|
||||
from functools import lru_cache
|
||||
import logging
|
||||
from typing import Dict, List, Optional
|
||||
from typing import Dict, List, Literal, Optional
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -34,17 +34,18 @@ class Settings(BaseSettings):
|
||||
openalex_api_key: Optional[str] = None
|
||||
openalex_api_timeout_seconds: float = 30.0
|
||||
|
||||
|
||||
# Patent Elasticsearch config
|
||||
patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic"
|
||||
patent_elasticsearch_api_key: Optional[str] = None
|
||||
|
||||
|
||||
# LLM config
|
||||
llm_api_url: Optional[str] = None
|
||||
llm_api_key: Optional[str] = None
|
||||
llm_model: Optional[str] = None
|
||||
|
||||
# Sentence Transformers config
|
||||
sentence_transformers_model_name: str = "paraphrase-multilingual-mpnet-base-v2"
|
||||
|
||||
# Elasticsearch config
|
||||
elasticsearch_url: str = "https://project.nes.uni-due.de/elastic"
|
||||
elasticsearch_api_key: Optional[str] = None
|
||||
@@ -61,6 +62,13 @@ class Settings(BaseSettings):
|
||||
|
||||
logging_level: str = "DEBUG"
|
||||
|
||||
environment: Literal["dev", "prod"] = "dev"
|
||||
|
||||
token_issuer_id: Optional[str] = None
|
||||
token_hmac_key: Optional[str] = None
|
||||
|
||||
skip_otk_validation: bool = True
|
||||
|
||||
|
||||
settings = Settings()
|
||||
|
||||
|
||||
@@ -1,25 +1,33 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
This module contains the code to bootstrap the database
|
||||
using our schema and sqlalchemy.
|
||||
"""
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from . import schema
|
||||
from . import config
|
||||
from typing import Annotated
|
||||
|
||||
engine = create_engine(config.settings.database_url, echo=config.settings.database_debug)
|
||||
from fastapi import Depends
|
||||
from sqlmodel import SQLModel, Session, create_engine
|
||||
|
||||
if config.settings.database_init:
|
||||
schema.Base.metadata.create_all(engine)
|
||||
from inse import config
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
def get():
|
||||
''' Returns a database connection and closes it when done. '''
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
settings = config.get_settings()
|
||||
|
||||
connect_args = {"check_same_thread": False}
|
||||
engine = create_engine(
|
||||
url=settings.database_url,
|
||||
echo=settings.database_debug,
|
||||
connect_args=connect_args,
|
||||
)
|
||||
|
||||
|
||||
def create_db_and_tables():
|
||||
"""Creates the database and tables based on the SQLModel metadata."""
|
||||
SQLModel.metadata.create_all(engine)
|
||||
|
||||
|
||||
def get_session():
|
||||
"""Yields a database session for use in FastAPI endpoints.
|
||||
|
||||
Yields:
|
||||
Session: A SQLModel session connected to the database.
|
||||
"""
|
||||
with Session(engine) as session:
|
||||
yield session
|
||||
|
||||
|
||||
SessionDep = Annotated[Session, Depends(get_session)]
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
class NotFoundException(Exception):
|
||||
"""Exception raised when a requested resource is not found.
|
||||
|
||||
Args:
|
||||
Exception (_type_): Base exception class.
|
||||
"""
|
||||
def __init__(self, message: str):
|
||||
super().__init__(message)
|
||||
|
||||
@@ -6,17 +6,10 @@ web service.
|
||||
"""
|
||||
|
||||
from typing import List
|
||||
from typing import TypeVar
|
||||
from typing import Optional
|
||||
from typing import Type
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import func
|
||||
import logging
|
||||
import httpx
|
||||
import json
|
||||
from . import schema
|
||||
from . import model
|
||||
|
||||
from . import config
|
||||
|
||||
|
||||
@@ -29,68 +22,13 @@ from inse.models.openalex.topic_domain import TopicDomain
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
|
||||
topic_cache_filename: str = "topic_hierarchy_cache.json"
|
||||
|
||||
S = TypeVar('S', bound=schema.Base)
|
||||
M = TypeVar('M', bound=model.BaseModel)
|
||||
|
||||
def filter_none():
|
||||
return True
|
||||
|
||||
|
||||
def get_page(
|
||||
db: Session,
|
||||
schema_type: Type[S],
|
||||
model_type: Type[M],
|
||||
offset: int,
|
||||
limit: int,
|
||||
filter=filter_none,
|
||||
) -> model.Page[M]:
|
||||
result = model.Page[model_type]()
|
||||
result.offset = offset
|
||||
result.total = get_count(db, schema_type, filter)
|
||||
result.size = limit
|
||||
if result.total > result.offset:
|
||||
result.elements = get_elements(db, schema_type, offset, limit, filter)
|
||||
else:
|
||||
result.elements = []
|
||||
return result
|
||||
|
||||
|
||||
def get_count(db: Session, schema_type: Type[S], filter=filter_none) -> int:
|
||||
return db.scalar(select(func.count()).select_from(schema_type).where(filter))
|
||||
|
||||
|
||||
def get_elements(
|
||||
db: Session, schema_type: Type[S], offset: int, limit: int, filter=filter_none
|
||||
) -> List[S]:
|
||||
return db.scalars(
|
||||
select(schema_type).where(filter).offset(offset).limit(limit)
|
||||
).all()
|
||||
|
||||
|
||||
def get_element(db: Session, schema_type: Type[S], element_id: int) -> Optional[S]:
|
||||
return db.scalars(
|
||||
select(schema_type).where(schema_type.id == element_id).limit(1)
|
||||
).first()
|
||||
|
||||
|
||||
def delete_element(db: Session, schema_type: Type[S], element_id: int):
|
||||
element = get_element(db, schema_type, element_id)
|
||||
db.delete(element)
|
||||
|
||||
|
||||
def insert_element(db: Session, value: S) -> S:
|
||||
db.add(value)
|
||||
db.flush()
|
||||
db.refresh(value)
|
||||
return value
|
||||
|
||||
|
||||
def _load_topic_cache() -> dict:
|
||||
"""Loads the topic hierarchy cache from a JSON file."""
|
||||
import os
|
||||
|
||||
try:
|
||||
cache_path = "/data/" + topic_cache_filename
|
||||
if not os.path.exists(cache_path):
|
||||
@@ -231,6 +169,7 @@ def count_topic_hierarchy(topic_names: List[str]) -> dict:
|
||||
|
||||
return counts
|
||||
|
||||
|
||||
def get_topic_hierarchy() -> dict:
|
||||
"""
|
||||
Builds and returns a hierarchical tree structure of topics:
|
||||
@@ -238,28 +177,25 @@ def get_topic_hierarchy() -> dict:
|
||||
"""
|
||||
flat_cache = _load_topic_cache()
|
||||
tree = {}
|
||||
|
||||
|
||||
for topic_name, info in flat_cache.items():
|
||||
domain = info.get("domain") or "Unbekannter Bereich"
|
||||
field = info.get("field") or "Unbekanntes Feld"
|
||||
subfield = info.get("subfield") or "Unbekanntes Teilfeld"
|
||||
topic_id = info.get("topic_id", "")
|
||||
|
||||
|
||||
# Clean topic ID to just be the trailing ID or keep full URL
|
||||
# For querying, display name is used in persons search, but ID is useful
|
||||
|
||||
|
||||
if domain not in tree:
|
||||
tree[domain] = {}
|
||||
if field not in tree[domain]:
|
||||
tree[domain][field] = {}
|
||||
if subfield not in tree[domain][field]:
|
||||
tree[domain][field][subfield] = []
|
||||
|
||||
tree[domain][field][subfield].append({
|
||||
"id": topic_id,
|
||||
"name": topic_name
|
||||
})
|
||||
|
||||
|
||||
tree[domain][field][subfield].append({"id": topic_id, "name": topic_name})
|
||||
|
||||
formatted_domains = []
|
||||
for d_name, d_fields in tree.items():
|
||||
formatted_fields = []
|
||||
@@ -267,20 +203,11 @@ def get_topic_hierarchy() -> dict:
|
||||
formatted_subfields = []
|
||||
for sf_name, sf_topics in f_subfields.items():
|
||||
sf_topics.sort(key=lambda x: x["name"])
|
||||
formatted_subfields.append({
|
||||
"name": sf_name,
|
||||
"topics": sf_topics
|
||||
})
|
||||
formatted_subfields.append({"name": sf_name, "topics": sf_topics})
|
||||
formatted_subfields.sort(key=lambda x: x["name"])
|
||||
formatted_fields.append({
|
||||
"name": f_name,
|
||||
"subfields": formatted_subfields
|
||||
})
|
||||
formatted_fields.append({"name": f_name, "subfields": formatted_subfields})
|
||||
formatted_fields.sort(key=lambda x: x["name"])
|
||||
formatted_domains.append({
|
||||
"name": d_name,
|
||||
"fields": formatted_fields
|
||||
})
|
||||
formatted_domains.append({"name": d_name, "fields": formatted_fields})
|
||||
formatted_domains.sort(key=lambda x: x["name"])
|
||||
|
||||
|
||||
return {"domains": formatted_domains}
|
||||
|
||||
@@ -6,6 +6,7 @@ for fastapi that loads the service and the
|
||||
webapp.
|
||||
"""
|
||||
|
||||
from contextlib import asynccontextmanager, contextmanager
|
||||
import logging
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
@@ -18,21 +19,25 @@ from inse.exceptions import NotFoundException
|
||||
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
|
||||
|
||||
# caching
|
||||
from inse.middleware.etag_cache import ETagCacheMiddleware
|
||||
from inse.persons.service import router as persons_service_router
|
||||
from inse.projects.router import router as projects_router
|
||||
from inse.topics.service import router as topics_service_router
|
||||
from inse.works.service import router as works_service_router
|
||||
from inse.persons.service import router as persons_service_router
|
||||
from inse.funders.service import router as funders_service_router
|
||||
from inse.news.service import router as news_service_router
|
||||
from inse.projects.router import router as projects_router
|
||||
from inse.patents.service import router as patents_service_router
|
||||
|
||||
from inse.auth.router import router as auth_router
|
||||
from inse.account_management.router import router as account_management_router
|
||||
|
||||
|
||||
from inse.institutions.router import router as institutions_router
|
||||
from inse.database import create_db_and_tables, get_session
|
||||
from inse.auth.service import create_predefined_accounts
|
||||
from . import config
|
||||
from .account.service import router as account_router
|
||||
|
||||
from .service import router as service_router
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -41,12 +46,24 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
settings = config.get_settings()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
logger.info("Starting up the application...")
|
||||
create_db_and_tables()
|
||||
with contextmanager(get_session)() as session:
|
||||
create_predefined_accounts(session, "../data/predefined_accounts.json")
|
||||
yield
|
||||
logger.info("Shutting down the application...")
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
redoc_url=None,
|
||||
title="Innovation Search Engine API",
|
||||
description="API for the Innovation Search Engine (INSE) application.",
|
||||
version="0.1.0",
|
||||
servers=settings.servers,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
app.include_router(collaboration_network_router)
|
||||
app.include_router(institutions_router)
|
||||
@@ -56,12 +73,16 @@ app.include_router(persons_service_router)
|
||||
app.include_router(funders_service_router)
|
||||
app.include_router(news_service_router)
|
||||
app.include_router(company_connections_router)
|
||||
app.include_router(service_router)
|
||||
app.include_router(account_router)
|
||||
app.include_router(patents_service_router)
|
||||
app.include_router(university_ranking_router)
|
||||
app.include_router(projects_router)
|
||||
|
||||
app.include_router(service_router)
|
||||
|
||||
app.include_router(auth_router)
|
||||
app.include_router(account_management_router)
|
||||
|
||||
app.add_middleware(
|
||||
ETagCacheMiddleware,
|
||||
ttl=300, # 5 minutes expiration time
|
||||
|
||||
@@ -4,6 +4,7 @@ from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
|
||||
|
||||
class ETagCacheMiddleware(BaseHTTPMiddleware):
|
||||
def __init__(self, app, ttl: int = 60):
|
||||
super().__init__(app)
|
||||
@@ -14,6 +15,9 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
|
||||
# Include query params and relevant headers in the key
|
||||
return f"{request.url.path}?{request.url.query}"
|
||||
|
||||
def _content_type(self, response: Response) -> str | None:
|
||||
return response.headers.get("content-type")
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
if request.method != "GET":
|
||||
return await call_next(request)
|
||||
@@ -25,28 +29,37 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
|
||||
# Cache hit + not expired
|
||||
if entry and time.time() < entry["expires"]:
|
||||
if client_etag == entry["etag"]:
|
||||
return Response(status_code=304, headers={"ETag": entry["etag"]})
|
||||
|
||||
headers = {"ETag": entry["etag"]}
|
||||
if entry.get("content_type"):
|
||||
headers["Content-Type"] = entry["content_type"]
|
||||
return Response(status_code=304, headers=headers)
|
||||
|
||||
# Client has stale ETag - return fresh cached body
|
||||
headers = {"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"}
|
||||
if entry.get("content_type"):
|
||||
headers["Content-Type"] = entry["content_type"]
|
||||
return Response(
|
||||
content=entry["body"],
|
||||
media_type="application/json",
|
||||
headers={"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"}
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
# Cache miss or expired → hit the actual route
|
||||
response = await call_next(request)
|
||||
body = b"".join([chunk async for chunk in response.body_iterator])
|
||||
etag = f'"{hashlib.md5(body).hexdigest()}"'
|
||||
content_type = self._content_type(response)
|
||||
|
||||
self.cache[key] = {
|
||||
"body": body,
|
||||
"etag": etag,
|
||||
"expires": time.time() + self.ttl
|
||||
"expires": time.time() + self.ttl,
|
||||
"content_type": content_type,
|
||||
}
|
||||
headers = {"ETag": etag, "Cache-Control": f"max-age={self.ttl}"}
|
||||
if content_type:
|
||||
headers["Content-Type"] = content_type
|
||||
return Response(
|
||||
content=body,
|
||||
status_code=response.status_code,
|
||||
media_type="application/json",
|
||||
headers={"ETag": etag, "Cache-Control": f"max-age={self.ttl}"}
|
||||
)
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
@@ -8,41 +8,20 @@ our api using pydantic.
|
||||
from enum import StrEnum
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic import ConfigDict
|
||||
from pydantic import Field
|
||||
from typing import List
|
||||
from typing import TypeVar
|
||||
from typing import Generic
|
||||
from typing import Optional
|
||||
|
||||
|
||||
T = TypeVar("T", bound=BaseModel)
|
||||
|
||||
|
||||
class Entity(BaseModel):
|
||||
id: int = Field(description="The id of the entity.")
|
||||
|
||||
|
||||
class Item(Entity):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
name: str = Field(description="The name of the item.")
|
||||
description: str = Field(description="The description of the item.")
|
||||
|
||||
|
||||
class ItemCreate(BaseModel):
|
||||
name: str = Field(description="The name of the item.")
|
||||
description: str = Field(description="The description of the item.")
|
||||
|
||||
|
||||
class Page(BaseModel, Generic[T]):
|
||||
elements: List[T] = Field(default=[], description="The elements of the page.")
|
||||
offset: int = Field(default=0, description="The page offset in elements.")
|
||||
total: int = Field(default=0, description="The total number of elements.")
|
||||
offset: int = Field(default=0, description="The page number. (0-based)")
|
||||
size: int = Field(default=20, description="The page size in elements.")
|
||||
|
||||
|
||||
class ItemPage(Page[Item]):
|
||||
pass
|
||||
total: int = Field(default=0, description="The total number of elements.")
|
||||
|
||||
|
||||
class ESCluster(StrEnum):
|
||||
@@ -55,10 +34,10 @@ class ESIndex(StrEnum):
|
||||
OPENALEX_AUTHORS = "openalex-authors"
|
||||
OPENALEX_INSTITUTIONS = "openalex-institutions"
|
||||
OPENALEX_PUBLICATIONS = "openalex-publications"
|
||||
|
||||
|
||||
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
|
||||
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
|
||||
CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications"
|
||||
|
||||
PROJECTS_BUND_V1 = "projects_bund_v1"
|
||||
PROJECTS_DFG_ALL = "projects_dfg_all"
|
||||
PROJECTS_DFG_ALL = "projects_dfg_all"
|
||||
|
||||
@@ -8,3 +8,39 @@ class TopicCount(BaseModel):
|
||||
name: str = Field(description="The topic display name.")
|
||||
count: int = Field(default=0, description="The number of occurrences.")
|
||||
description: Optional[str] = Field(default=None, description="The topic description.")
|
||||
subfield_id: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The topic subfield id.",
|
||||
)
|
||||
subfield_name: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The topic subfield display name.",
|
||||
)
|
||||
subfield_description: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The topic subfield description.",
|
||||
)
|
||||
field_id: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The topic field id.",
|
||||
)
|
||||
field_name: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The topic field display name.",
|
||||
)
|
||||
field_description: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The topic field description.",
|
||||
)
|
||||
domain_id: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The topic domain id.",
|
||||
)
|
||||
domain_name: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The topic domain display name.",
|
||||
)
|
||||
domain_description: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The topic domain description.",
|
||||
)
|
||||
|
||||
@@ -147,7 +147,7 @@ def _build_mentioned_persons(author_names: list) -> list:
|
||||
|
||||
ude_persons = []
|
||||
other_persons = []
|
||||
|
||||
|
||||
for name in author_names:
|
||||
match = find_ude_author_by_name(name)
|
||||
if match:
|
||||
|
||||
@@ -8,8 +8,7 @@ import json
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime
|
||||
from typing import Optional, Callable, Any, List
|
||||
from elasticsearch import ApiError, NotFoundError
|
||||
from typing import Optional, List
|
||||
import hashlib
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
@@ -20,14 +19,12 @@ from .. import util
|
||||
from ..integrations import llm
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.models.openalex.authors_list_response import AuthorsListResponse
|
||||
from inse import util
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.models.openalex.meta import Meta
|
||||
from inse.persons.query_builder import build_authors_search_rescored
|
||||
from inse.persons.model import (
|
||||
CustomAuthor,
|
||||
CustomAuthorsListResponse,
|
||||
PersonSearchRequest,
|
||||
CareerMetrics,
|
||||
)
|
||||
|
||||
@@ -35,17 +32,14 @@ logger = logging.getLogger(__name__)
|
||||
INDEX_NAME = "openalex-authors"
|
||||
UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen
|
||||
|
||||
|
||||
def find_ude_author_by_name(display_name: str) -> Optional[dict]:
|
||||
query = {
|
||||
"_source": ["display_name"],
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"match_phrase": {
|
||||
"display_name": display_name
|
||||
}
|
||||
},
|
||||
{"match_phrase": {"display_name": display_name}},
|
||||
{
|
||||
"nested": {
|
||||
"path": "affiliations",
|
||||
@@ -82,7 +76,7 @@ def find_ude_author_by_name(display_name: str) -> Optional[dict]:
|
||||
return None
|
||||
|
||||
hit = exact_matches[0]
|
||||
|
||||
|
||||
return {
|
||||
"id": hit.get("_id"),
|
||||
"display_name": hit.get("_source", {}).get("display_name"),
|
||||
@@ -304,15 +298,15 @@ def _classify_career_stage(active_years: int) -> str:
|
||||
return "unknown"
|
||||
|
||||
if active_years <= 4:
|
||||
return "Early Researcher"
|
||||
return "Early"
|
||||
|
||||
if active_years <= 10:
|
||||
return "Emerging Researcher"
|
||||
if active_years <= 9:
|
||||
return "Emerging"
|
||||
|
||||
if active_years <= 20:
|
||||
return "Established Researcher"
|
||||
if active_years <= 14:
|
||||
return "Established"
|
||||
|
||||
return "Senior Researcher"
|
||||
return "Senior"
|
||||
|
||||
|
||||
def _compute_career_metrics(publication_years: list[int]) -> CareerMetrics:
|
||||
@@ -433,15 +427,13 @@ def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> s
|
||||
def get_person_by_id(
|
||||
author_id: str, include: Optional[str] = None
|
||||
) -> CustomAuthorsListResponse:
|
||||
body = {
|
||||
"_source": include.split(",") if include else True,
|
||||
}
|
||||
source = include.split(",") if include else None
|
||||
|
||||
try:
|
||||
hit = elasticsearch.get(
|
||||
index="openalex-authors",
|
||||
body=body,
|
||||
doc_id=author_id,
|
||||
source=source,
|
||||
)
|
||||
except NotFoundError:
|
||||
raise HTTPException(
|
||||
@@ -451,7 +443,13 @@ def get_person_by_id(
|
||||
raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}")
|
||||
|
||||
author = util.get_persons_data(hit)
|
||||
start_time = time.time()
|
||||
career_metrics = get_career_metrics_for_author(author_id)
|
||||
elapsed_time = time.time() - start_time
|
||||
|
||||
logger.info(
|
||||
f"Career metrics calculation for author {author_id} took {elapsed_time:.2f} seconds"
|
||||
)
|
||||
|
||||
custom_author = CustomAuthor(
|
||||
**author.model_dump(),
|
||||
@@ -737,11 +735,22 @@ def advanced_search_persons(
|
||||
hits = response_dict.get("hits", {}).get("hits", [])
|
||||
total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
include_career_metrics = include is None or "career_metrics" in include
|
||||
results = []
|
||||
for hit in hits:
|
||||
raw_data = util.get_persons_data(hit)
|
||||
custom_author = _enrich_author_data(raw_data)
|
||||
if custom_author:
|
||||
if include_career_metrics:
|
||||
start_time = time.time()
|
||||
custom_author.career_metrics = get_career_metrics_for_author(
|
||||
custom_author.id
|
||||
)
|
||||
elapsed_time = time.time() - start_time
|
||||
logger.info(
|
||||
f"Career metrics calculation for author {custom_author.id} took "
|
||||
f"{elapsed_time:.2f} seconds"
|
||||
)
|
||||
results.append(custom_author)
|
||||
|
||||
return CustomAuthorsListResponse(
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
from functools import lru_cache
|
||||
import logging
|
||||
from typing import Annotated, Optional, Set
|
||||
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
This module defines the schema for the database
|
||||
used by the service using sql alchemy.
|
||||
"""
|
||||
from sqlalchemy import String
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
from sqlalchemy.orm import Mapped
|
||||
from sqlalchemy.orm import mapped_column
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
''' Base class for all data models. '''
|
||||
pass
|
||||
|
||||
class Item(Base):
|
||||
''' Data model to represent an item. '''
|
||||
__tablename__ = "item"
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(200))
|
||||
description: Mapped[str] = mapped_column(String(2000))
|
||||
def __repr__(self) -> str:
|
||||
return f"Item(id={self.id!r}, name={self.name!r})"
|
||||
@@ -1,13 +1,13 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
This module defines the security-related code.
|
||||
This module defines the security-related code.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
from typing import List
|
||||
from typing import Callable
|
||||
from typing import Literal
|
||||
from typing import Union
|
||||
from starlette.status import HTTP_403_FORBIDDEN
|
||||
from fastapi import Depends
|
||||
from fastapi.security import HTTPBearer
|
||||
@@ -15,63 +15,97 @@ from fastapi.security import HTTPAuthorizationCredentials
|
||||
from fastapi import HTTPException
|
||||
from pydantic import BaseModel
|
||||
from pydantic import Field
|
||||
from sqlalchemy.orm import Session
|
||||
import jwt
|
||||
import logging
|
||||
from . import config
|
||||
from . import database
|
||||
|
||||
|
||||
class Account(BaseModel):
|
||||
id: int = Field(description="The id of the account.")
|
||||
login: Optional[str] = Field(description="The optional login of the account.")
|
||||
organization: int = Field(description="The organization id of the account.")
|
||||
|
||||
|
||||
class Principal(BaseModel):
|
||||
account: Account = Field(description="The account of the principal.")
|
||||
delegate: Optional[Account] = Field(default=None, description="The optional delegate of the principal.")
|
||||
delegate: Optional[Account] = Field(
|
||||
default=None, description="The optional delegate of the principal."
|
||||
)
|
||||
roles: List[str] = Field(description="The roles of the principal.")
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
bearer = HTTPBearer(bearerFormat="JWT", scheme_name="bearer", description="JSON Web Token provided via bearer authorization.", auto_error=False)
|
||||
bearer = HTTPBearer(
|
||||
bearerFormat="JWT",
|
||||
scheme_name="bearer",
|
||||
description="JSON Web Token provided via bearer authorization.",
|
||||
auto_error=False,
|
||||
)
|
||||
|
||||
def principal(credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer), db: Session = Depends(database.get)) -> Optional[Principal]:
|
||||
|
||||
def principal(
|
||||
db: database.SessionDep,
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer),
|
||||
) -> Optional[Principal]:
|
||||
if config.settings.auth_disabled:
|
||||
account = Account(id=0, login="AUTH_DISABLED", organization=0)
|
||||
return Principal(account=account, delegate=None, roles=[ 'SUPER_ADMIN' ])
|
||||
return Principal(account=account, delegate=None, roles=["SUPER_ADMIN"])
|
||||
if credentials is None or credentials.credentials is None:
|
||||
return None
|
||||
return _extract_principal(credentials.credentials, config.settings.auth_secret, 'HS256')
|
||||
return _extract_principal(
|
||||
credentials.credentials, config.settings.auth_secret, "HS256"
|
||||
)
|
||||
|
||||
def _extract_principal(token: str, secret_key, algorithm: Literal['RS256', 'HS256'], token_types: List[Literal['ID', 'ACCESS', 'REFRESH']] = [ 'ACCESS' ]) -> Optional[Principal]:
|
||||
|
||||
def _extract_principal(
|
||||
token: str,
|
||||
secret_key,
|
||||
algorithm: Literal["RS256", "HS256"],
|
||||
token_types: List[Literal["ID", "ACCESS", "REFRESH"]] = ["ACCESS"],
|
||||
) -> Optional[Principal]:
|
||||
try:
|
||||
content = jwt.decode(token, secret_key, verify=True, issuer="my-app", algorithms=[ algorithm ], options={"require": [ "iss", "iat", "nbf", "exp", "inse"]})
|
||||
content = jwt.decode(
|
||||
token,
|
||||
secret_key,
|
||||
verify=True,
|
||||
issuer="my-app",
|
||||
algorithms=[algorithm],
|
||||
options={"require": ["iss", "iat", "nbf", "exp", "inse"]},
|
||||
)
|
||||
except jwt.exceptions.ExpiredSignatureError as e:
|
||||
logger.info(f'Received expired token, ignoring content ({e}).')
|
||||
logger.info(f"Received expired token, ignoring content ({e}).")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.info(f'Received invalid token content, ignoring content ({e}).')
|
||||
logger.info(f"Received invalid token content, ignoring content ({e}).")
|
||||
return None
|
||||
scope = content.get("inse")
|
||||
if scope is None:
|
||||
return None
|
||||
token_type = scope.get('t')
|
||||
token_type = scope.get("t")
|
||||
if token_type not in token_types:
|
||||
logger.info(f'Received invalid token type, ignoring content (Type was {token_type})')
|
||||
logger.info(
|
||||
f"Received invalid token type, ignoring content (Type was {token_type})"
|
||||
)
|
||||
return None
|
||||
a = scope.get('a', {})
|
||||
account = Account(id=a.get('i', 0), login=a.get('l'), organization=a.get('o', 0))
|
||||
a = scope.get("a", {})
|
||||
account = Account(id=a.get("i", 0), login=a.get("l"), organization=a.get("o", 0))
|
||||
delegate = None
|
||||
d = scope.get('d')
|
||||
d = scope.get("d")
|
||||
if d is not None:
|
||||
delegate = Account(id=d.get('i', 0), login=d.get('l'), organization=d.get('o', 0))
|
||||
return Principal(account=account, delegate=delegate, roles=scope.get('r', []))
|
||||
delegate = Account(
|
||||
id=d.get("i", 0), login=d.get("l"), organization=d.get("o", 0)
|
||||
)
|
||||
return Principal(account=account, delegate=delegate, roles=scope.get("r", []))
|
||||
|
||||
def roles_allowed(roles: List[str]|str) -> Callable[[Optional[Principal]], Principal]:
|
||||
|
||||
def roles_allowed(roles: List[str] | str) -> Callable[[Optional[Principal]], Principal]:
|
||||
if isinstance(roles, str):
|
||||
roles = [roles]
|
||||
if len(roles) < 1:
|
||||
raise ValueError("Must specify at least one role in roles_allowed.")
|
||||
|
||||
def verify_roles(principal: Optional[Principal] = Depends(principal)) -> Principal:
|
||||
if principal is None:
|
||||
logger.info("Rejecting call due to missing principal.")
|
||||
@@ -81,4 +115,5 @@ def roles_allowed(roles: List[str]|str) -> Callable[[Optional[Principal]], Princ
|
||||
return principal
|
||||
logger.info("Rejecting call due to missing roles.")
|
||||
raise HTTPException(status_code=HTTP_403_FORBIDDEN)
|
||||
|
||||
return verify_roles
|
||||
|
||||
@@ -6,28 +6,13 @@ service.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Annotated, List, Optional
|
||||
from fastapi import FastAPI
|
||||
from fastapi import Depends
|
||||
from fastapi import Path
|
||||
from typing import Annotated, List
|
||||
from fastapi import Query
|
||||
from fastapi import Body
|
||||
from fastapi import Response
|
||||
from fastapi.responses import RedirectResponse
|
||||
from starlette.status import HTTP_404_NOT_FOUND
|
||||
from starlette.status import HTTP_200_OK
|
||||
from sqlalchemy.orm import Session
|
||||
from inse.config import get_settings
|
||||
from fastapi import APIRouter
|
||||
|
||||
|
||||
from . import model
|
||||
from . import logic
|
||||
from . import schema
|
||||
from . import database
|
||||
from . import security
|
||||
from . import util
|
||||
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -42,126 +27,6 @@ router = APIRouter(
|
||||
responses={404: {"description": "Not found"}},
|
||||
)
|
||||
|
||||
# @app.get("/", include_in_schema=False)
|
||||
# async def show_api():
|
||||
# return RedirectResponse("api")
|
||||
|
||||
|
||||
### items
|
||||
|
||||
|
||||
@router.get(
|
||||
"/items",
|
||||
operation_id="getItems",
|
||||
response_model=model.ItemPage,
|
||||
summary="Returns a page of items.",
|
||||
tags=["Items"],
|
||||
)
|
||||
def get_items(
|
||||
page_offset: Annotated[
|
||||
int, Query(alias="pageOffset", description="The page offset.", ge=0)
|
||||
] = 0,
|
||||
page_size: Annotated[
|
||||
int, Query(alias="pageSize", description="The page size.", ge=0, le=1000)
|
||||
] = 100,
|
||||
db: Session = Depends(database.get),
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
):
|
||||
return logic.get_page(db, schema.Item, model.Item, page_offset, page_size)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/items/{id}",
|
||||
operation_id="getItem",
|
||||
response_model=model.Item,
|
||||
summary="Returns the item with the id.",
|
||||
responses={HTTP_404_NOT_FOUND: {"model": None}},
|
||||
tags=["Items"],
|
||||
)
|
||||
def get_item(
|
||||
id: Annotated[int, Path(description="The item id.", ge=0)],
|
||||
db: Session = Depends(database.get),
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
):
|
||||
return util.raise_not_found_if_none(logic.get_element(db, schema.Item, id))
|
||||
|
||||
|
||||
@router.post(
|
||||
"/items",
|
||||
operation_id="addItem",
|
||||
response_model=model.Item,
|
||||
summary="Adds a new item.",
|
||||
tags=["Items"],
|
||||
)
|
||||
def add_item(
|
||||
item: Annotated[model.ItemCreate, Body(description="The item to add.")],
|
||||
db: Session = Depends(database.get),
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
):
|
||||
i = schema.Item()
|
||||
i.name = item.name
|
||||
i.description = item.description
|
||||
try:
|
||||
return logic.insert_element(db, i)
|
||||
finally:
|
||||
db.commit()
|
||||
|
||||
|
||||
@router.put(
|
||||
"/items/{id}",
|
||||
operation_id="updateItem",
|
||||
response_model=model.Item,
|
||||
summary="Updates the item with the id.",
|
||||
responses={HTTP_404_NOT_FOUND: {"model": None}},
|
||||
tags=["Items"],
|
||||
)
|
||||
def update_item(
|
||||
id: Annotated[int, Path(description="The item id.", ge=0)],
|
||||
item: Annotated[model.ItemCreate, Body(description="The item data to update.")],
|
||||
db: Session = Depends(database.get),
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
):
|
||||
i = util.raise_not_found_if_none(logic.get_element(db, schema.Item, id))
|
||||
i.name = item.name
|
||||
i.description = item.description
|
||||
db.flush()
|
||||
db.refresh(i)
|
||||
try:
|
||||
return i
|
||||
finally:
|
||||
db.commit()
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/items/{id}",
|
||||
operation_id="deleteItem",
|
||||
summary="Deletes the item with the id.",
|
||||
response_model=None,
|
||||
responses={HTTP_404_NOT_FOUND: {"model": None}},
|
||||
tags=["Items"],
|
||||
)
|
||||
def delete_item(
|
||||
id: Annotated[int, Path(description="The item id.", ge=0)],
|
||||
db: Session = Depends(database.get),
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
):
|
||||
util.raise_not_found_if_none(logic.get_element(db, schema.Item, id))
|
||||
try:
|
||||
logic.delete_element(db, schema.Item, id)
|
||||
return Response(status_code=HTTP_200_OK)
|
||||
finally:
|
||||
db.commit()
|
||||
|
||||
|
||||
### topics
|
||||
# hierarchy cache (temporaray => should be called by a scheduled job, with new openalex data indexing)
|
||||
@@ -209,6 +74,7 @@ def count_topic_hierarchy(
|
||||
):
|
||||
return logic.count_topic_hierarchy(topic_names)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/topics/hierarchy",
|
||||
operation_id="getTopicHierarchy",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from enum import Enum
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class Tags(Enum):
|
||||
class Tags(StrEnum):
|
||||
PERSON = "Person"
|
||||
PERSON_NETWORK = "Person Network"
|
||||
INSTITUTIONS = "Institutions"
|
||||
@@ -9,3 +9,5 @@ class Tags(Enum):
|
||||
WORKS = "Works"
|
||||
NEWS = "News"
|
||||
PROJECTS = "Projects"
|
||||
AUTH = "Auth"
|
||||
ACCOUNT = "Account"
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"""
|
||||
Business logic for OpenAlex topics.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
@@ -156,7 +157,13 @@ def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
meta = normalized.get("meta")
|
||||
if isinstance(meta, dict):
|
||||
for field in ["count", "db_response_time_ms", "page", "per_page", "groups_count"]:
|
||||
for field in [
|
||||
"count",
|
||||
"db_response_time_ms",
|
||||
"page",
|
||||
"per_page",
|
||||
"groups_count",
|
||||
]:
|
||||
meta[field] = _int_or_none(meta.get(field))
|
||||
meta["next_cursor"] = _str_or_none(meta.get("next_cursor"))
|
||||
meta["cost_usd"] = _number_or_none(meta.get("cost_usd"))
|
||||
@@ -256,10 +263,21 @@ 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.62
|
||||
BOOST_LEXICAL = 1.0
|
||||
# higher values for semantic weights, because cosine similarity is between 0 and 1
|
||||
BOOST_DISPLAY_NAME_VECTOR = 30.0
|
||||
BOOST_DESCRIPTION_VECTOR = 15.0
|
||||
BOOST_KEYWORD_VECTORS = 25.0
|
||||
|
||||
|
||||
async def vector_search_topics(
|
||||
*,
|
||||
query: str,
|
||||
limit: int = 25,
|
||||
search_type: str = "hybrid",
|
||||
) -> TopicsListResponse:
|
||||
"""
|
||||
Perform a semantic similarity search on the topicvectors index.
|
||||
@@ -267,12 +285,12 @@ async def vector_search_topics(
|
||||
try:
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.util import get_model
|
||||
|
||||
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to load elasticsearch integration.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Failed to load elasticsearch integration: {exc}"
|
||||
detail=f"Failed to load elasticsearch integration: {exc}",
|
||||
)
|
||||
|
||||
# 1. Vectorize query
|
||||
@@ -283,96 +301,98 @@ async def vector_search_topics(
|
||||
logger.exception("Failed to encode query text.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Failed to encode query text: {exc}"
|
||||
detail=f"Failed to encode query text: {exc}",
|
||||
)
|
||||
|
||||
|
||||
# 2. Query Elasticsearch using standard Bool Should hybrid search
|
||||
|
||||
body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"multi_match": {
|
||||
"query": query,
|
||||
"fields": [
|
||||
"display_name^3",
|
||||
"keywords^2",
|
||||
"description^1"
|
||||
],
|
||||
"boost": 1.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62,
|
||||
"boost": 2.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "description_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "description_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max",
|
||||
"boost": 1.0
|
||||
}
|
||||
}
|
||||
]
|
||||
should_clauses = []
|
||||
|
||||
# Lexical multi_match search (only in hybrid mode)
|
||||
if search_type == "hybrid":
|
||||
should_clauses.append(
|
||||
{
|
||||
"multi_match": {
|
||||
"query": query,
|
||||
"fields": ["display_name^3", "keywords^2", "description^1"],
|
||||
"boost": BOOST_LEXICAL,
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
# Semantic KNN clauses
|
||||
should_clauses.extend(
|
||||
[
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"similarity": SIMILARITY_THRESHOLD,
|
||||
"boost": BOOST_DISPLAY_NAME_VECTOR,
|
||||
"k": 500,
|
||||
"num_candidates": 500,
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"similarity": SIMILARITY_THRESHOLD,
|
||||
"boost": BOOST_DESCRIPTION_VECTOR,
|
||||
"k": 500,
|
||||
"num_candidates": 500,
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"similarity": SIMILARITY_THRESHOLD,
|
||||
"k": 500,
|
||||
"num_candidates": 500,
|
||||
}
|
||||
},
|
||||
"score_mode": "max",
|
||||
"boost": BOOST_KEYWORD_VECTORS,
|
||||
}
|
||||
},
|
||||
]
|
||||
)
|
||||
|
||||
body = {
|
||||
"query": {"bool": {"should": should_clauses}},
|
||||
"_source": {
|
||||
"excludes": ["display_name_vector", "description_vectors", "description", "siblings"] # remove unrequired fields (description, sibling currently not needed)
|
||||
"excludes": [
|
||||
"display_name_vector",
|
||||
"description_vector",
|
||||
"keyword_vectors",
|
||||
"description",
|
||||
] # remove unrequired fields
|
||||
},
|
||||
"size": limit
|
||||
"size": limit,
|
||||
}
|
||||
|
||||
|
||||
try:
|
||||
raw_results = elasticsearch.search(
|
||||
index="topicvectors",
|
||||
body=body,
|
||||
cluster="nes"
|
||||
index="topicvectors", body=body, cluster="nes"
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Elasticsearch vector search failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Elasticsearch vector search failed: {exc}"
|
||||
detail=f"Elasticsearch vector search failed: {exc}",
|
||||
)
|
||||
|
||||
|
||||
# 3. Format result
|
||||
hits = raw_results.get("hits", {}).get("hits", [])
|
||||
|
||||
# Log scores to JSON for threshold analysis TODO: Remove after finetune
|
||||
try:
|
||||
from .score_logger import log_scores_to_json
|
||||
log_scores_to_json(hits, query)
|
||||
except Exception as exc:
|
||||
logger.warning(f"Could not log search scores: {exc}")
|
||||
|
||||
|
||||
total = len(hits)
|
||||
results = [hit.get("_source", {}) for hit in hits]
|
||||
|
||||
data = {
|
||||
"meta": {
|
||||
"count": total,
|
||||
"page": 1,
|
||||
"per_page": limit
|
||||
},
|
||||
"results": results
|
||||
}
|
||||
|
||||
|
||||
data = {"meta": {"count": total, "page": 1, "per_page": limit}, "results": results}
|
||||
|
||||
try:
|
||||
normalized_data = _normalize_topics_response(data)
|
||||
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
|
||||
@@ -382,4 +402,3 @@ async def vector_search_topics(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Vector search response could not be parsed.",
|
||||
) from exc
|
||||
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List
|
||||
|
||||
def log_scores_to_json(hits: List[Dict[str, Any]], query: str) -> None:
|
||||
"""
|
||||
Utility function to log the names and scores of all vector search hits to a JSON file.
|
||||
This helps in debugging and manually tweaking the similarity score thresholds.
|
||||
"""
|
||||
scores_data = []
|
||||
for hit in hits:
|
||||
source = hit.get("_source", {})
|
||||
topic_name = source.get("display_name") or source.get("name") or "Unknown"
|
||||
score = hit.get("_score", 0.0)
|
||||
scores_data.append({
|
||||
"topic_name": topic_name,
|
||||
"score": score
|
||||
})
|
||||
|
||||
|
||||
data_dir = Path("/data")
|
||||
|
||||
output_file = data_dir / "search_scores.json"
|
||||
|
||||
log_payload = {
|
||||
"query": query,
|
||||
"max_score": hits[0].get("_score", 0.0) if hits else 0.0,
|
||||
"results": scores_data
|
||||
}
|
||||
|
||||
try:
|
||||
with open(output_file, "w", encoding="utf-8") as f:
|
||||
json.dump(log_payload, f, indent=2, ensure_ascii=False)
|
||||
print(f"DEBUG: Saved search scores for query '{query}' to {output_file}")
|
||||
except Exception as exc:
|
||||
print(f"DEBUG: Failed to save search scores: {exc}")
|
||||
@@ -129,9 +129,14 @@ async def vector_search_topics(
|
||||
int,
|
||||
Query(description="Maximum number of topics to return.", ge=1, le=100),
|
||||
] = 25,
|
||||
search_type: Annotated[
|
||||
str,
|
||||
Query(alias="searchType", description="Search approach: 'hybrid' or 'semantic'."),
|
||||
] = "hybrid",
|
||||
):
|
||||
return await logic.vector_search_topics(
|
||||
query=query,
|
||||
limit=limit,
|
||||
search_type=search_type,
|
||||
)
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ def get_persons_data(hit:dict):
|
||||
return author
|
||||
|
||||
from sentence_transformers import SentenceTransformer
|
||||
from .config import settings
|
||||
# Sentence Transformer Model
|
||||
_model: SentenceTransformer | None = None
|
||||
|
||||
@@ -55,5 +56,6 @@ def get_model():
|
||||
if os.environ.get("SENTENCE_TRANSFORMERS_HOME") == "/models":
|
||||
os.environ["HF_HUB_OFFLINE"] = "1"
|
||||
|
||||
_model = SentenceTransformer("paraphrase-multilingual-mpnet-base-v2")
|
||||
model_name = settings.sentence_transformers_model_name
|
||||
_model = SentenceTransformer(model_name)
|
||||
return _model
|
||||
@@ -29,6 +29,26 @@ from .search_client import OpenAlexWorksSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TOPIC_DETAIL_SOURCE_FIELDS = [
|
||||
"id",
|
||||
"display_name",
|
||||
"description",
|
||||
"subfield",
|
||||
"field",
|
||||
"domain",
|
||||
]
|
||||
|
||||
TOPIC_HIERARCHY_DESCRIPTION_INDICES = {
|
||||
"subfield": "openalex-subfields",
|
||||
"field": "openalex-fields",
|
||||
"domain": "openalex-domains",
|
||||
}
|
||||
|
||||
TOPIC_HIERARCHY_DESCRIPTION_SOURCE_FIELDS = [
|
||||
"id",
|
||||
"description",
|
||||
]
|
||||
|
||||
|
||||
async def get_author_works(
|
||||
author_id: str,
|
||||
@@ -121,6 +141,7 @@ async def get_primary_topic_counts(
|
||||
name=name,
|
||||
count=item["count"],
|
||||
description=info.get("description"),
|
||||
**_topic_hierarchy_fields(info),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -208,7 +229,7 @@ def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||
response = elasticsearch.search(
|
||||
index="openalex-topics",
|
||||
query={"terms": {"id": topic_ids}},
|
||||
source=["id", "display_name", "description"],
|
||||
source=TOPIC_DETAIL_SOURCE_FIELDS,
|
||||
size=len(topic_ids),
|
||||
)
|
||||
except httpx.HTTPError:
|
||||
@@ -225,11 +246,94 @@ def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||
details[topic_id] = {
|
||||
"display_name": source.get("display_name"),
|
||||
"description": source.get("description"),
|
||||
"subfield": _extract_topic_hierarchy_item(source, "subfield"),
|
||||
"field": _extract_topic_hierarchy_item(source, "field"),
|
||||
"domain": _extract_topic_hierarchy_item(source, "domain"),
|
||||
}
|
||||
|
||||
_enrich_topic_hierarchy_descriptions(details)
|
||||
|
||||
return details
|
||||
|
||||
|
||||
def _extract_topic_hierarchy_item(source: dict, key: str) -> dict[str, str | None]:
|
||||
hierarchy_item = source.get(key)
|
||||
|
||||
if not isinstance(hierarchy_item, dict):
|
||||
return {"id": None, "display_name": None, "description": None}
|
||||
|
||||
return {
|
||||
"id": hierarchy_item.get("id"),
|
||||
"display_name": hierarchy_item.get("display_name"),
|
||||
"description": hierarchy_item.get("description"),
|
||||
}
|
||||
|
||||
|
||||
def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
for hierarchy_key, index in TOPIC_HIERARCHY_DESCRIPTION_INDICES.items():
|
||||
hierarchy_ids = {
|
||||
item.get(hierarchy_key, {}).get("id")
|
||||
for item in details.values()
|
||||
if item.get(hierarchy_key, {}).get("id")
|
||||
}
|
||||
|
||||
descriptions = _get_topic_hierarchy_descriptions(index, list(hierarchy_ids))
|
||||
|
||||
for item in details.values():
|
||||
hierarchy_item = item.get(hierarchy_key) or {}
|
||||
hierarchy_id = hierarchy_item.get("id")
|
||||
|
||||
if hierarchy_id and hierarchy_id in descriptions:
|
||||
hierarchy_item["description"] = descriptions[hierarchy_id]
|
||||
|
||||
|
||||
def _get_topic_hierarchy_descriptions(
|
||||
index: str,
|
||||
hierarchy_ids: list[str],
|
||||
) -> dict[str, str | None]:
|
||||
if not hierarchy_ids:
|
||||
return {}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
index=index,
|
||||
query={"terms": {"id": hierarchy_ids}},
|
||||
source=TOPIC_HIERARCHY_DESCRIPTION_SOURCE_FIELDS,
|
||||
size=len(hierarchy_ids),
|
||||
)
|
||||
except httpx.HTTPError:
|
||||
logger.exception("Could not load topic hierarchy details from %s.", index)
|
||||
return {}
|
||||
|
||||
descriptions = {}
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
source = hit.get("_source", {})
|
||||
hierarchy_id = source.get("id")
|
||||
|
||||
if hierarchy_id:
|
||||
descriptions[hierarchy_id] = source.get("description")
|
||||
|
||||
return descriptions
|
||||
|
||||
|
||||
def _topic_hierarchy_fields(topic_details: dict) -> dict[str, str | None]:
|
||||
subfield = topic_details.get("subfield") or {}
|
||||
field = topic_details.get("field") or {}
|
||||
domain = topic_details.get("domain") or {}
|
||||
|
||||
return {
|
||||
"subfield_id": subfield.get("id"),
|
||||
"subfield_name": subfield.get("display_name"),
|
||||
"subfield_description": subfield.get("description"),
|
||||
"field_id": field.get("id"),
|
||||
"field_name": field.get("display_name"),
|
||||
"field_description": field.get("description"),
|
||||
"domain_id": domain.get("id"),
|
||||
"domain_name": domain.get("display_name"),
|
||||
"domain_description": domain.get("description"),
|
||||
}
|
||||
|
||||
|
||||
def _limit_works_by_complete_years(
|
||||
work_results: list[Work],
|
||||
target_publications: int,
|
||||
@@ -445,6 +549,7 @@ async def _get_topics_by_time_by_author_from_work_pages(
|
||||
name=topic["name"],
|
||||
count=topic["count"],
|
||||
description=info.get("description"),
|
||||
**_topic_hierarchy_fields(info),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -462,6 +567,7 @@ async def _get_topics_by_time_by_author_from_work_pages(
|
||||
name=topic["name"],
|
||||
count=topic["count"],
|
||||
description=info.get("description"),
|
||||
**_topic_hierarchy_fields(info),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -768,6 +874,7 @@ def _build_topic_counts_from_buckets(
|
||||
name=display_name,
|
||||
count=count,
|
||||
description=info.get("description"),
|
||||
**_topic_hierarchy_fields(info),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -7,13 +7,11 @@ REST API for publication works.
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import Depends
|
||||
from fastapi import Path
|
||||
from fastapi import Query
|
||||
|
||||
from inse.tags import Tags
|
||||
|
||||
from .. import security
|
||||
from . import logic
|
||||
from inse.models.openalex.work_page import WorkPage
|
||||
from inse.models.openalex.work import Work
|
||||
@@ -56,9 +54,6 @@ async def get_author_works(
|
||||
list[str] | None,
|
||||
Query(description="Filter by OpenAlex topic id. Can be repeated."),
|
||||
] = None,
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
):
|
||||
return await logic.get_author_works(
|
||||
author_id,
|
||||
@@ -78,7 +73,6 @@ async def get_author_works(
|
||||
summary="Returns all works for an author.")
|
||||
async def get_all_author_works(
|
||||
author_id: Annotated[str, Path(description="The author id, for example A5023888391.")],
|
||||
principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])),
|
||||
):
|
||||
return await logic.get_all_author_works(author_id)
|
||||
|
||||
@@ -89,7 +83,6 @@ async def get_all_author_works(
|
||||
summary="Returns work counts per primary topic for an author.")
|
||||
async def get_primary_topic_counts(
|
||||
author_id: Annotated[str, Path(description="The author id, for example A5023888391.")],
|
||||
principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])),
|
||||
):
|
||||
return await logic.get_primary_topic_counts(author_id)
|
||||
|
||||
@@ -112,7 +105,6 @@ async def get_topics_by_time_by_author(
|
||||
bool,
|
||||
Query(description="If true, all publications are used for the timeline."),
|
||||
] = False,
|
||||
principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])),
|
||||
):
|
||||
return await logic.get_topics_by_time_by_author(
|
||||
author_id,
|
||||
@@ -132,8 +124,5 @@ async def get_work(
|
||||
work_id: Annotated[
|
||||
str, Path(description="The OpenAlex work id, for example W2741809807.")
|
||||
],
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
):
|
||||
return await logic.get_work(work_id)
|
||||
|
||||
Generated
+68
-68
@@ -2,8 +2,10 @@ version = 1
|
||||
revision = 3
|
||||
requires-python = ">=3.12"
|
||||
resolution-markers = [
|
||||
"sys_platform != 'darwin'",
|
||||
"sys_platform == 'darwin'",
|
||||
"python_full_version >= '3.14' and sys_platform != 'darwin'",
|
||||
"python_full_version < '3.14' and sys_platform != 'darwin'",
|
||||
"python_full_version >= '3.14' and sys_platform == 'darwin'",
|
||||
"python_full_version < '3.14' and sys_platform == 'darwin'",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -37,6 +39,49 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/da/42/e921fccf5015463e32a3cf6ee7f980a6ed0f395ceeaa45060b61d86486c2/anyio-4.13.0-py3-none-any.whl", hash = "sha256:08b310f9e24a9594186fd75b4f73f4a4152069e3853f1ed8bfbf58369f4ad708", size = 114353, upload-time = "2026-03-24T12:59:08.246Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "argon2-cffi"
|
||||
version = "25.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "argon2-cffi-bindings" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0e/89/ce5af8a7d472a67cc819d5d998aa8c82c5d860608c4db9f46f1162d7dab9/argon2_cffi-25.1.0.tar.gz", hash = "sha256:694ae5cc8a42f4c4e2bf2ca0e64e51e23a040c6a517a85074683d3959e1346c1", size = 45706, upload-time = "2025-06-03T06:55:32.073Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/4f/d3/a8b22fa575b297cd6e3e3b0155c7e25db170edf1c74783d6a31a2490b8d9/argon2_cffi-25.1.0-py3-none-any.whl", hash = "sha256:fdc8b074db390fccb6eb4a3604ae7231f219aa669a2652e0f20e16ba513d5741", size = 14657, upload-time = "2025-06-03T06:55:30.804Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "argon2-cffi-bindings"
|
||||
version = "25.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "cffi" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/5c/2d/db8af0df73c1cf454f71b2bbe5e356b8c1f8041c979f505b3d3186e520a9/argon2_cffi_bindings-25.1.0.tar.gz", hash = "sha256:b957f3e6ea4d55d820e40ff76f450952807013d361a65d7f28acc0acbf29229d", size = 1783441, upload-time = "2025-07-30T10:02:05.147Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/60/97/3c0a35f46e52108d4707c44b95cfe2afcafc50800b5450c197454569b776/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:3d3f05610594151994ca9ccb3c771115bdb4daef161976a266f0dd8aa9996b8f", size = 54393, upload-time = "2025-07-30T10:01:40.97Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9d/f4/98bbd6ee89febd4f212696f13c03ca302b8552e7dbf9c8efa11ea4a388c3/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:8b8efee945193e667a396cbc7b4fb7d357297d6234d30a489905d96caabde56b", size = 29328, upload-time = "2025-07-30T10:01:41.916Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/43/24/90a01c0ef12ac91a6be05969f29944643bc1e5e461155ae6559befa8f00b/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:3c6702abc36bf3ccba3f802b799505def420a1b7039862014a65db3205967f5a", size = 31269, upload-time = "2025-07-30T10:01:42.716Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d4/d3/942aa10782b2697eee7af5e12eeff5ebb325ccfb86dd8abda54174e377e4/argon2_cffi_bindings-25.1.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a1c70058c6ab1e352304ac7e3b52554daadacd8d453c1752e547c76e9c99ac44", size = 86558, upload-time = "2025-07-30T10:01:43.943Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0d/82/b484f702fec5536e71836fc2dbc8c5267b3f6e78d2d539b4eaa6f0db8bf8/argon2_cffi_bindings-25.1.0-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e2fd3bfbff3c5d74fef31a722f729bf93500910db650c925c2d6ef879a7e51cb", size = 92364, upload-time = "2025-07-30T10:01:44.887Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c9/c1/a606ff83b3f1735f3759ad0f2cd9e038a0ad11a3de3b6c673aa41c24bb7b/argon2_cffi_bindings-25.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c4f9665de60b1b0e99bcd6be4f17d90339698ce954cfd8d9cf4f91c995165a92", size = 85637, upload-time = "2025-07-30T10:01:46.225Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/44/b4/678503f12aceb0262f84fa201f6027ed77d71c5019ae03b399b97caa2f19/argon2_cffi_bindings-25.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ba92837e4a9aa6a508c8d2d7883ed5a8f6c308c89a4790e1e447a220deb79a85", size = 91934, upload-time = "2025-07-30T10:01:47.203Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f0/c7/f36bd08ef9bd9f0a9cff9428406651f5937ce27b6c5b07b92d41f91ae541/argon2_cffi_bindings-25.1.0-cp314-cp314t-win32.whl", hash = "sha256:84a461d4d84ae1295871329b346a97f68eade8c53b6ed9a7ca2d7467f3c8ff6f", size = 28158, upload-time = "2025-07-30T10:01:48.341Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b3/80/0106a7448abb24a2c467bf7d527fe5413b7fdfa4ad6d6a96a43a62ef3988/argon2_cffi_bindings-25.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b55aec3565b65f56455eebc9b9f34130440404f27fe21c3b375bf1ea4d8fbae6", size = 32597, upload-time = "2025-07-30T10:01:49.112Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/05/b8/d663c9caea07e9180b2cb662772865230715cbd573ba3b5e81793d580316/argon2_cffi_bindings-25.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:87c33a52407e4c41f3b70a9c2d3f6056d88b10dad7695be708c5021673f55623", size = 28231, upload-time = "2025-07-30T10:01:49.92Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1d/57/96b8b9f93166147826da5f90376e784a10582dd39a393c99bb62cfcf52f0/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:aecba1723ae35330a008418a91ea6cfcedf6d31e5fbaa056a166462ff066d500", size = 54121, upload-time = "2025-07-30T10:01:50.815Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0a/08/a9bebdb2e0e602dde230bdde8021b29f71f7841bd54801bcfd514acb5dcf/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:2630b6240b495dfab90aebe159ff784d08ea999aa4b0d17efa734055a07d2f44", size = 29177, upload-time = "2025-07-30T10:01:51.681Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b6/02/d297943bcacf05e4f2a94ab6f462831dc20158614e5d067c35d4e63b9acb/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:7aef0c91e2c0fbca6fc68e7555aa60ef7008a739cbe045541e438373bc54d2b0", size = 31090, upload-time = "2025-07-30T10:01:53.184Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c1/93/44365f3d75053e53893ec6d733e4a5e3147502663554b4d864587c7828a7/argon2_cffi_bindings-25.1.0-cp39-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1e021e87faa76ae0d413b619fe2b65ab9a037f24c60a1e6cc43457ae20de6dc6", size = 81246, upload-time = "2025-07-30T10:01:54.145Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/09/52/94108adfdd6e2ddf58be64f959a0b9c7d4ef2fa71086c38356d22dc501ea/argon2_cffi_bindings-25.1.0-cp39-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d3e924cfc503018a714f94a49a149fdc0b644eaead5d1f089330399134fa028a", size = 87126, upload-time = "2025-07-30T10:01:55.074Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/72/70/7a2993a12b0ffa2a9271259b79cc616e2389ed1a4d93842fac5a1f923ffd/argon2_cffi_bindings-25.1.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c87b72589133f0346a1cb8d5ecca4b933e3c9b64656c9d175270a000e73b288d", size = 80343, upload-time = "2025-07-30T10:01:56.007Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/78/9a/4e5157d893ffc712b74dbd868c7f62365618266982b64accab26bab01edc/argon2_cffi_bindings-25.1.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1db89609c06afa1a214a69a462ea741cf735b29a57530478c06eb81dd403de99", size = 86777, upload-time = "2025-07-30T10:01:56.943Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/74/cd/15777dfde1c29d96de7f18edf4cc94c385646852e7c7b0320aa91ccca583/argon2_cffi_bindings-25.1.0-cp39-abi3-win32.whl", hash = "sha256:473bcb5f82924b1becbb637b63303ec8d10e84c8d241119419897a26116515d2", size = 27180, upload-time = "2025-07-30T10:01:57.759Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e2/c6/a759ece8f1829d1f162261226fbfd2c6832b3ff7657384045286d2afa384/argon2_cffi_bindings-25.1.0-cp39-abi3-win_amd64.whl", hash = "sha256:a98cd7d17e9f7ce244c0803cad3c23a7d379c301ba618a5fa76a67d116618b98", size = 31715, upload-time = "2025-07-30T10:01:58.56Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/42/b9/f8d6fa329ab25128b7e98fd83a3cb34d9db5b059a9847eddb840a0af45dd/argon2_cffi_bindings-25.1.0-cp39-abi3-win_arm64.whl", hash = "sha256:b0fdbcf513833809c882823f98dc2f931cf659d9a1429616ac3adebb49f5db94", size = 27149, upload-time = "2025-07-30T10:01:59.329Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "certifi"
|
||||
version = "2026.5.20"
|
||||
@@ -178,36 +223,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b2/b7/545d2c10c1fc15e48653c91efde329a790f2eecfbbf2bd16003b5db2bab0/dotenv-0.9.9-py2.py3-none-any.whl", hash = "sha256:29cf74a087b31dafdb5a446b6d7e11cbce8ed2741540e2339c69fbef92c94ce9", size = 1892, upload-time = "2025-02-19T22:15:01.647Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "elastic-transport"
|
||||
version = "9.4.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "certifi" },
|
||||
{ name = "sniffio" },
|
||||
{ name = "urllib3" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0f/a8/dd1431b95daa54d4859c1d250362433df6df9cfaab7bfac3eafd410d019a/elastic_transport-9.4.1.tar.gz", hash = "sha256:d12c86ea73528690ebf63a488d9ae323292e6aa5ee55e1e29f14293472f4197f", size = 79170, upload-time = "2026-05-25T14:16:47.416Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/5c/f6/508c1e541b840b6eaf60a46a8994ba55affd07bf6a311cffc860781ae06a/elastic_transport-9.4.1-py3-none-any.whl", hash = "sha256:186a29e6c66ff269487e33f7b17176316e18b6061702c25eb0bb15681302e91d", size = 66229, upload-time = "2026-05-25T14:16:45.882Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "elasticsearch"
|
||||
version = "9.4.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "anyio" },
|
||||
{ name = "elastic-transport" },
|
||||
{ name = "python-dateutil" },
|
||||
{ name = "sniffio" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/e0/4b/9b753f0a8f56ae508dced2f7ac87bef7a27ce8f890e349e16812e9f7f4fa/elasticsearch-9.4.1.tar.gz", hash = "sha256:1d78fdfba97a903ec35a5eb5808a74e33392b7c620bd5f742d465a3a26c27d75", size = 908138, upload-time = "2026-05-26T16:28:40.132Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/cf/8e/2c93805e93e724a90156004a9212572ec86473974deede4605a33b8b169a/elasticsearch-9.4.1-py3-none-any.whl", hash = "sha256:71ab71c3d1b20fd88c2922fb82c3277cce7ea03c160686e7b9368b265c2b4cac", size = 993647, upload-time = "2026-05-26T16:28:36.556Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastapi"
|
||||
version = "0.115.14"
|
||||
@@ -799,18 +814,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/f0/d7/a812a0bd0f5160823e647524488cc9734f93782f2c273b8f77e8afc60a37/pytest-8.1.2-py3-none-any.whl", hash = "sha256:6c06dc309ff46a05721e6fd48e492a775ed8165d2ecdf57f156a80c7e95bb142", size = 337456, upload-time = "2024-04-26T18:05:15.452Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "python-dateutil"
|
||||
version = "2.9.0.post0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "six" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "python-dotenv"
|
||||
version = "1.2.2"
|
||||
@@ -1125,9 +1128,9 @@ name = "service"
|
||||
version = "0.1.0"
|
||||
source = { virtual = "." }
|
||||
dependencies = [
|
||||
{ name = "argon2-cffi" },
|
||||
{ name = "cryptography" },
|
||||
{ name = "dotenv" },
|
||||
{ name = "elasticsearch" },
|
||||
{ name = "fastapi" },
|
||||
{ name = "httpx" },
|
||||
{ name = "openai" },
|
||||
@@ -1138,7 +1141,7 @@ dependencies = [
|
||||
{ name = "python-multipart" },
|
||||
{ name = "pyyaml" },
|
||||
{ name = "sentence-transformers" },
|
||||
{ name = "sqlalchemy" },
|
||||
{ name = "sqlmodel" },
|
||||
{ name = "torch", version = "2.12.0", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "sys_platform == 'darwin'" },
|
||||
{ name = "torch", version = "2.12.0+cpu", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "sys_platform != 'darwin'" },
|
||||
{ name = "uvicorn" },
|
||||
@@ -1146,9 +1149,9 @@ dependencies = [
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "argon2-cffi", specifier = "~=25.1.0" },
|
||||
{ name = "cryptography", specifier = "~=42.0.0" },
|
||||
{ name = "dotenv", specifier = ">=0.9.9" },
|
||||
{ name = "elasticsearch", specifier = "~=9.4.0" },
|
||||
{ name = "fastapi", specifier = "~=0.115.0" },
|
||||
{ name = "httpx", specifier = "~=0.27.0" },
|
||||
{ name = "openai", specifier = "~=2.41.0" },
|
||||
@@ -1159,7 +1162,7 @@ requires-dist = [
|
||||
{ name = "python-multipart", specifier = "~=0.0.19" },
|
||||
{ name = "pyyaml", specifier = "~=6.0.1" },
|
||||
{ name = "sentence-transformers", specifier = "~=5.5.1" },
|
||||
{ name = "sqlalchemy", specifier = "~=2.0.0" },
|
||||
{ name = "sqlmodel", specifier = "~=0.0.33" },
|
||||
{ name = "torch", index = "https://download.pytorch.org/whl/cpu" },
|
||||
{ name = "uvicorn", specifier = "~=0.29.0" },
|
||||
]
|
||||
@@ -1182,15 +1185,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "six"
|
||||
version = "1.17.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sniffio"
|
||||
version = "1.3.1"
|
||||
@@ -1241,6 +1235,19 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/d0/10/f7220e9b784d295d241c86ed99aeb537f92afcd469a64861f2717e9bb077/sqlalchemy-2.0.50-py3-none-any.whl", hash = "sha256:92064363517a3ff8212b5a93b8c62876579d8dfd1ca5b561335f30152d884fa9", size = 1943861, upload-time = "2026-05-24T19:59:01.119Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sqlmodel"
|
||||
version = "0.0.33"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pydantic" },
|
||||
{ name = "sqlalchemy" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/c4/62/22c287122598e61d07d005eec0b4eb97e6bde9a1b051bcd66c2bca846ea8/sqlmodel-0.0.33.tar.gz", hash = "sha256:b473544ed5fc2097894d89033049e569e1f138363dd3ec2ed4b6932cc9f29f5f", size = 95578, upload-time = "2026-02-11T15:23:39.504Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/63/39/13891bae4658133b489a4d8b6a2f193d56110e392289560f312748e796dc/sqlmodel-0.0.33-py3-none-any.whl", hash = "sha256:9045bb4d97d2ba099c5a068ee9525af2d106972dda1ff8488e187ce50556bf73", size = 27444, upload-time = "2026-02-11T15:23:38.678Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "starlette"
|
||||
version = "0.46.2"
|
||||
@@ -1305,7 +1312,8 @@ name = "torch"
|
||||
version = "2.12.0"
|
||||
source = { registry = "https://download.pytorch.org/whl/cpu" }
|
||||
resolution-markers = [
|
||||
"sys_platform == 'darwin'",
|
||||
"python_full_version >= '3.14' and sys_platform == 'darwin'",
|
||||
"python_full_version < '3.14' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "filelock", marker = "sys_platform == 'darwin'" },
|
||||
@@ -1329,7 +1337,8 @@ name = "torch"
|
||||
version = "2.12.0+cpu"
|
||||
source = { registry = "https://download.pytorch.org/whl/cpu" }
|
||||
resolution-markers = [
|
||||
"sys_platform != 'darwin'",
|
||||
"python_full_version >= '3.14' and sys_platform != 'darwin'",
|
||||
"python_full_version < '3.14' and sys_platform != 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "filelock", marker = "sys_platform != 'darwin'" },
|
||||
@@ -1421,15 +1430,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "urllib3"
|
||||
version = "2.7.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uvicorn"
|
||||
version = "0.29.0"
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
"version": "0.0.0",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "ng serve",
|
||||
"start": "ng serve --proxy-config src/proxy.conf.json",
|
||||
"build": "ng build",
|
||||
"generate:api": "openapi-generator-cli generate --generator-key inse-service",
|
||||
"watch": "ng build --watch --configuration development",
|
||||
|
||||
@@ -4,12 +4,12 @@ README.md
|
||||
api.base.service.ts
|
||||
api.module.ts
|
||||
api/api.ts
|
||||
api/auth.service.ts
|
||||
api/companyConnections.service.ts
|
||||
api/funding.service.ts
|
||||
api/iNSEAccountService.service.ts
|
||||
api/iNSEService.service.ts
|
||||
api/institutions.service.ts
|
||||
api/items.service.ts
|
||||
api/news.service.ts
|
||||
api/patents.service.ts
|
||||
api/personNetwork.service.ts
|
||||
@@ -39,7 +39,11 @@ model/autocompleteResponse.ts
|
||||
model/autocompleteResponseMeta.ts
|
||||
model/autocompleteResponseResultsInner.ts
|
||||
model/award.ts
|
||||
model/bodyChangePassword.ts
|
||||
model/bodyCreateUser.ts
|
||||
model/bodyGetAccessToken.ts
|
||||
model/bodyLogin.ts
|
||||
model/bodyRequestOtk.ts
|
||||
model/bundProject.ts
|
||||
model/bundProjectDetails.ts
|
||||
model/bundProjectPage.ts
|
||||
@@ -81,9 +85,6 @@ model/institutionInformation.ts
|
||||
model/institutionNetworkNode.ts
|
||||
model/institutionPage.ts
|
||||
model/institutionsListResponse.ts
|
||||
model/item.ts
|
||||
model/itemCreate.ts
|
||||
model/itemPage.ts
|
||||
model/keywords.ts
|
||||
model/latitude.ts
|
||||
model/location.ts
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
export * from './auth.service';
|
||||
import { AuthService } from './auth.service';
|
||||
export * from './companyConnections.service';
|
||||
import { CompanyConnectionsService } from './companyConnections.service';
|
||||
export * from './funding.service';
|
||||
@@ -8,8 +10,6 @@ export * from './iNSEService.service';
|
||||
import { INSEServiceService } from './iNSEService.service';
|
||||
export * from './institutions.service';
|
||||
import { InstitutionsService } from './institutions.service';
|
||||
export * from './items.service';
|
||||
import { ItemsService } from './items.service';
|
||||
export * from './news.service';
|
||||
import { NewsService } from './news.service';
|
||||
export * from './patents.service';
|
||||
@@ -24,4 +24,4 @@ export * from './topics.service';
|
||||
import { TopicsService } from './topics.service';
|
||||
export * from './works.service';
|
||||
import { WorksService } from './works.service';
|
||||
export const APIS = [CompanyConnectionsService, FundingService, INSEAccountServiceService, INSEServiceService, InstitutionsService, ItemsService, NewsService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
|
||||
export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEAccountServiceService, INSEServiceService, InstitutionsService, NewsService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
/**
|
||||
* 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 { BodyChangePassword } from '../model/bodyChangePassword';
|
||||
// @ts-ignore
|
||||
import { BodyGetAccessToken } from '../model/bodyGetAccessToken';
|
||||
// @ts-ignore
|
||||
import { BodyLogin } from '../model/bodyLogin';
|
||||
// @ts-ignore
|
||||
import { BodyRequestOtk } from '../model/bodyRequestOtk';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthService extends BaseService {
|
||||
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Change Password
|
||||
* Change the user\'s password and invalidate existing tokens.
|
||||
* @endpoint post /api/auth/v2/change-password
|
||||
* @param bodyChangePassword
|
||||
* @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> {
|
||||
if (bodyChangePassword === null || bodyChangePassword === undefined) {
|
||||
throw new Error('Required parameter bodyChangePassword was null or undefined when calling changePassword.');
|
||||
}
|
||||
|
||||
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'
|
||||
]);
|
||||
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/change-password`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyChangePassword,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Access Token
|
||||
* Retrieve an access token for the authenticated user.
|
||||
* @endpoint post /api/auth/v2/access
|
||||
* @param bodyGetAccessToken
|
||||
* @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<{ [key: string]: string | null; }>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<{ [key: string]: string | null; }>>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<{ [key: string]: string | null; }>>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, 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'
|
||||
]);
|
||||
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/access`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<{ [key: string]: string | null; }>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyGetAccessToken,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Health Check
|
||||
* @endpoint get /api/auth/v2/health
|
||||
* @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 healthCheckApiAuthV2HealthGet(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public healthCheckApiAuthV2HealthGet(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public healthCheckApiAuthV2HealthGet(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public healthCheckApiAuthV2HealthGet(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/auth/v2/health`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Login with One-Time Key
|
||||
* Login using a one-time key (OTK) sent to the user\'s email.
|
||||
* @endpoint post /api/auth/v2/login
|
||||
* @param bodyLogin
|
||||
* @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 login(bodyLogin: BodyLogin, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public login(bodyLogin: BodyLogin, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public login(bodyLogin: BodyLogin, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public login(bodyLogin: BodyLogin, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (bodyLogin === null || bodyLogin === undefined) {
|
||||
throw new Error('Required parameter bodyLogin was null or undefined when calling login.');
|
||||
}
|
||||
|
||||
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/login`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyLogin,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout
|
||||
* Logout the authenticated user.
|
||||
* @endpoint post /api/auth/v2/logout
|
||||
* @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> {
|
||||
|
||||
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'
|
||||
]);
|
||||
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/auth/v2/logout`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh Access Token
|
||||
* Refresh the access token using a valid refresh token.
|
||||
* @endpoint post /api/auth/v2/refresh
|
||||
* @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<string>;
|
||||
public refreshAccessToken(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<string>>;
|
||||
public refreshAccessToken(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<string>>;
|
||||
public refreshAccessToken(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'
|
||||
]);
|
||||
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/auth/v2/refresh`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<string>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Request One-Time Key
|
||||
* Request a one-time key (OTK) for authentication using email and password.
|
||||
* @endpoint post /api/auth/v2/request-otk
|
||||
* @param bodyRequestOtk
|
||||
* @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: 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.');
|
||||
}
|
||||
|
||||
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-otk`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyRequestOtk,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -18,12 +18,6 @@ import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { Item } from '../model/item';
|
||||
// @ts-ignore
|
||||
import { ItemCreate } from '../model/itemCreate';
|
||||
// @ts-ignore
|
||||
import { ItemPage } from '../model/itemPage';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
@@ -41,74 +35,6 @@ export class INSEServiceService extends BaseService {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new item.
|
||||
* @endpoint post /api/inse-service/items
|
||||
* @param itemCreate
|
||||
* @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 addItem(itemCreate: ItemCreate, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Item>;
|
||||
public addItem(itemCreate: ItemCreate, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Item>>;
|
||||
public addItem(itemCreate: ItemCreate, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Item>>;
|
||||
public addItem(itemCreate: ItemCreate, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (itemCreate === null || itemCreate === undefined) {
|
||||
throw new Error('Required parameter itemCreate was null or undefined when calling addItem.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/items`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Item>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: itemCreate,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the topic hierarchy cache.
|
||||
* @endpoint get /api/inse-service/topics/cache
|
||||
@@ -233,185 +159,6 @@ export class INSEServiceService extends BaseService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the item with the id.
|
||||
* @endpoint delete /api/inse-service/items/{id}
|
||||
* @param id The item 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 deleteItem(id: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public deleteItem(id: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public deleteItem(id: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public deleteItem(id: number, 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 deleteItem.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
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/items/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: undefined})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('delete', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the item with the id.
|
||||
* @endpoint get /api/inse-service/items/{id}
|
||||
* @param id The item 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 getItem(id: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Item>;
|
||||
public getItem(id: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Item>>;
|
||||
public getItem(id: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Item>>;
|
||||
public getItem(id: number, 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 getItem.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
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/items/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: undefined})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Item>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a page of items.
|
||||
* @endpoint get /api/inse-service/items
|
||||
* @param pageOffset The page offset.
|
||||
* @param pageSize The page size.
|
||||
* @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 getItems(pageOffset?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<ItemPage>;
|
||||
public getItems(pageOffset?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<ItemPage>>;
|
||||
public getItems(pageOffset?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<ItemPage>>;
|
||||
public getItems(pageOffset?: number, pageSize?: number, 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>pageOffset, 'pageOffset');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>pageSize, 'pageSize');
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
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/items`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<ItemPage>('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
|
||||
@@ -463,76 +210,4 @@ export class INSEServiceService extends BaseService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the item with the id.
|
||||
* @endpoint put /api/inse-service/items/{id}
|
||||
* @param id The item id.
|
||||
* @param itemCreate
|
||||
* @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 updateItem(id: number, itemCreate: ItemCreate, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Item>;
|
||||
public updateItem(id: number, itemCreate: ItemCreate, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Item>>;
|
||||
public updateItem(id: number, itemCreate: ItemCreate, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Item>>;
|
||||
public updateItem(id: number, itemCreate: ItemCreate, 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 updateItem.');
|
||||
}
|
||||
if (itemCreate === null || itemCreate === undefined) {
|
||||
throw new Error('Required parameter itemCreate was null or undefined when calling updateItem.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/items/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: undefined})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Item>('put', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: itemCreate,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,363 +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.
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { Item } from '../model/item';
|
||||
// @ts-ignore
|
||||
import { ItemCreate } from '../model/itemCreate';
|
||||
// @ts-ignore
|
||||
import { ItemPage } from '../model/itemPage';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ItemsService extends BaseService {
|
||||
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new item.
|
||||
* @endpoint post /api/inse-service/items
|
||||
* @param itemCreate
|
||||
* @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 addItem(itemCreate: ItemCreate, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Item>;
|
||||
public addItem(itemCreate: ItemCreate, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Item>>;
|
||||
public addItem(itemCreate: ItemCreate, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Item>>;
|
||||
public addItem(itemCreate: ItemCreate, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (itemCreate === null || itemCreate === undefined) {
|
||||
throw new Error('Required parameter itemCreate was null or undefined when calling addItem.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/items`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Item>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: itemCreate,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the item with the id.
|
||||
* @endpoint delete /api/inse-service/items/{id}
|
||||
* @param id The item 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 deleteItem(id: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public deleteItem(id: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public deleteItem(id: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public deleteItem(id: number, 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 deleteItem.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
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/items/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: undefined})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('delete', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the item with the id.
|
||||
* @endpoint get /api/inse-service/items/{id}
|
||||
* @param id The item 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 getItem(id: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Item>;
|
||||
public getItem(id: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Item>>;
|
||||
public getItem(id: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Item>>;
|
||||
public getItem(id: number, 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 getItem.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
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/items/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: undefined})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Item>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a page of items.
|
||||
* @endpoint get /api/inse-service/items
|
||||
* @param pageOffset The page offset.
|
||||
* @param pageSize The page size.
|
||||
* @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 getItems(pageOffset?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<ItemPage>;
|
||||
public getItems(pageOffset?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<ItemPage>>;
|
||||
public getItems(pageOffset?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<ItemPage>>;
|
||||
public getItems(pageOffset?: number, pageSize?: number, 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>pageOffset, 'pageOffset');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>pageSize, 'pageSize');
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
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/items`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<ItemPage>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the item with the id.
|
||||
* @endpoint put /api/inse-service/items/{id}
|
||||
* @param id The item id.
|
||||
* @param itemCreate
|
||||
* @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 updateItem(id: number, itemCreate: ItemCreate, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Item>;
|
||||
public updateItem(id: number, itemCreate: ItemCreate, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Item>>;
|
||||
public updateItem(id: number, itemCreate: ItemCreate, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Item>>;
|
||||
public updateItem(id: number, itemCreate: ItemCreate, 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 updateItem.');
|
||||
}
|
||||
if (itemCreate === null || itemCreate === undefined) {
|
||||
throw new Error('Required parameter itemCreate was null or undefined when calling updateItem.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/items/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: undefined})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Item>('put', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: itemCreate,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -372,13 +372,14 @@ export class TopicsService extends BaseService {
|
||||
* @endpoint get /api/topics/vector-search
|
||||
* @param query Word or sentence to search by similarity.
|
||||
* @param limit Maximum number of topics to return.
|
||||
* @param searchType Search approach: \'hybrid\' or \'semantic\'.
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public vectorSearchTopics(query: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<TopicsListResponse>;
|
||||
public vectorSearchTopics(query: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<TopicsListResponse>>;
|
||||
public vectorSearchTopics(query: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<TopicsListResponse>>;
|
||||
public vectorSearchTopics(query: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public vectorSearchTopics(query: string, limit?: number, searchType?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<TopicsListResponse>;
|
||||
public vectorSearchTopics(query: string, limit?: number, searchType?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<TopicsListResponse>>;
|
||||
public vectorSearchTopics(query: string, limit?: number, searchType?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<TopicsListResponse>>;
|
||||
public vectorSearchTopics(query: string, limit?: number, searchType?: 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 vectorSearchTopics.');
|
||||
}
|
||||
@@ -388,6 +389,8 @@ export class TopicsService extends BaseService {
|
||||
<any>query, 'query');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>limit, 'limit');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>searchType, 'searchType');
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
|
||||
@@ -62,9 +62,6 @@ export class WorksService extends BaseService {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
@@ -163,9 +160,6 @@ export class WorksService extends BaseService {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
@@ -222,9 +216,6 @@ export class WorksService extends BaseService {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
@@ -291,9 +282,6 @@ export class WorksService extends BaseService {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
@@ -350,9 +338,6 @@ export class WorksService extends BaseService {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
|
||||
@@ -91,9 +91,9 @@ constructor({ accessToken, apiKeys, basePath, credentials, encodeParam, encoder,
|
||||
this.encodeParam = encodeParam ?? (param => this.defaultEncodeParam(param));
|
||||
this.credentials = credentials ?? {};
|
||||
|
||||
// init default bearer credential
|
||||
if (!this.credentials['bearer']) {
|
||||
this.credentials['bearer'] = () => {
|
||||
// init default HTTPBearer credential
|
||||
if (!this.credentials['HTTPBearer']) {
|
||||
this.credentials['HTTPBearer'] = () => {
|
||||
return typeof this.accessToken === 'function'
|
||||
? this.accessToken()
|
||||
: this.accessToken;
|
||||
|
||||
+5
-5
@@ -9,14 +9,14 @@
|
||||
*/
|
||||
|
||||
|
||||
export interface ItemCreate {
|
||||
export interface BodyChangePassword {
|
||||
/**
|
||||
* The name of the item.
|
||||
* Current password
|
||||
*/
|
||||
name: string;
|
||||
current_password: string;
|
||||
/**
|
||||
* The description of the item.
|
||||
* New password
|
||||
*/
|
||||
description: string;
|
||||
new_password: string;
|
||||
}
|
||||
|
||||
@@ -9,18 +9,14 @@
|
||||
*/
|
||||
|
||||
|
||||
export interface Item {
|
||||
export interface BodyGetAccessToken {
|
||||
/**
|
||||
* The id of the entity.
|
||||
* User\'s account ID
|
||||
*/
|
||||
id: number;
|
||||
real_account_id: string;
|
||||
/**
|
||||
* The name of the item.
|
||||
* Effective account ID for the access token
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* The description of the item.
|
||||
*/
|
||||
description: string;
|
||||
effective_account_id: 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 BodyLogin {
|
||||
/**
|
||||
* User\'s account ID
|
||||
*/
|
||||
account_id: string;
|
||||
/**
|
||||
* One-time code sent to user\'s email
|
||||
*/
|
||||
email_code: 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 BodyRequestOtk {
|
||||
/**
|
||||
* User\'s email address
|
||||
*/
|
||||
email: string;
|
||||
/**
|
||||
* User\'s password
|
||||
*/
|
||||
password: string;
|
||||
}
|
||||
|
||||
@@ -1,31 +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 { Item } from './item';
|
||||
|
||||
|
||||
export interface ItemPage {
|
||||
/**
|
||||
* The elements of the page.
|
||||
*/
|
||||
elements?: Array<Item>;
|
||||
/**
|
||||
* The page offset in elements.
|
||||
*/
|
||||
offset?: number;
|
||||
/**
|
||||
* The total number of elements.
|
||||
*/
|
||||
total?: number;
|
||||
/**
|
||||
* The page size in elements.
|
||||
*/
|
||||
size?: number;
|
||||
}
|
||||
|
||||
@@ -16,7 +16,11 @@ export * from './autocompleteResponse';
|
||||
export * from './autocompleteResponseMeta';
|
||||
export * from './autocompleteResponseResultsInner';
|
||||
export * from './award';
|
||||
export * from './bodyChangePassword';
|
||||
export * from './bodyCreateUser';
|
||||
export * from './bodyGetAccessToken';
|
||||
export * from './bodyLogin';
|
||||
export * from './bodyRequestOtk';
|
||||
export * from './bundProject';
|
||||
export * from './bundProjectDetails';
|
||||
export * from './bundProjectPage';
|
||||
@@ -58,9 +62,6 @@ export * from './institutionInformation';
|
||||
export * from './institutionNetworkNode';
|
||||
export * from './institutionPage';
|
||||
export * from './institutionsListResponse';
|
||||
export * from './item';
|
||||
export * from './itemCreate';
|
||||
export * from './itemPage';
|
||||
export * from './keywords';
|
||||
export * from './latitude';
|
||||
export * from './location';
|
||||
|
||||
@@ -20,5 +20,14 @@ export interface TopicCount {
|
||||
*/
|
||||
count?: number;
|
||||
description?: string | null;
|
||||
subfield_id?: string | null;
|
||||
subfield_name?: string | null;
|
||||
subfield_description?: string | null;
|
||||
field_id?: string | null;
|
||||
field_name?: string | null;
|
||||
field_description?: string | null;
|
||||
domain_id?: string | null;
|
||||
domain_name?: string | null;
|
||||
domain_description?: string | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ import { MatPaginatorIntl } from '@angular/material/paginator';
|
||||
import { PaginatorIntl } from './shared/utils/paginatorIntl';
|
||||
import { provideEchartsCore } from 'ngx-echarts';
|
||||
import { ErrorService } from './shared/services/error.service';
|
||||
import { provideApi } from './api/provide-api';
|
||||
|
||||
registerLocaleData(locale);
|
||||
|
||||
@@ -72,7 +73,10 @@ export const appConfig: ApplicationConfig = {
|
||||
}),
|
||||
),
|
||||
provideHttpClient(withInterceptors([authenticationInterceptor])),
|
||||
// provideApi('/inse-service'),
|
||||
provideApi({
|
||||
basePath: '/inse-webapp',
|
||||
withCredentials: true,
|
||||
}),
|
||||
provideAnimationsAsync(),
|
||||
provideEchartsCore({ echarts: () => import('echarts') }),
|
||||
],
|
||||
|
||||
@@ -90,6 +90,14 @@ export const routes: Routes = [
|
||||
loadComponent: () =>
|
||||
import('./modules/news/news.component').then((mod) => mod.NewsComponent),
|
||||
},
|
||||
{
|
||||
path: 'accounts',
|
||||
canActivate: [userGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/accounts/accounts.component').then(
|
||||
(mod) => mod.AccountsComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'news/:id',
|
||||
canActivate: [userGuard],
|
||||
@@ -190,7 +198,33 @@ export const routes: Routes = [
|
||||
collaborationNetwork: collaborationNetworkResolver,
|
||||
},
|
||||
runGuardsAndResolvers: (from, to) => {
|
||||
// No need to re-run for different table view or search term
|
||||
const network = from.data['collaborationNetwork'] as
|
||||
| {
|
||||
filter_information?: {
|
||||
min_possible_year?: number;
|
||||
max_possible_year?: number;
|
||||
};
|
||||
}
|
||||
| undefined;
|
||||
|
||||
const filterInformation = network?.filter_information;
|
||||
|
||||
const defaultQueryParams: Record<string, string> = {
|
||||
filter_by: 'works',
|
||||
start_year: filterInformation?.min_possible_year
|
||||
? String(filterInformation.min_possible_year)
|
||||
: '',
|
||||
end_year: filterInformation?.max_possible_year
|
||||
? String(filterInformation.max_possible_year)
|
||||
: '',
|
||||
min_contributors: '2',
|
||||
max_contributors: '10',
|
||||
min_collaborations: '1',
|
||||
max_collaborations: '100',
|
||||
institutions: '',
|
||||
topics: '',
|
||||
};
|
||||
|
||||
const keys = [
|
||||
'filter_by',
|
||||
'start_year',
|
||||
@@ -203,9 +237,22 @@ export const routes: Routes = [
|
||||
'topics',
|
||||
];
|
||||
|
||||
return keys.some(
|
||||
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
|
||||
);
|
||||
return keys.some((key) => {
|
||||
const fromRawValue = from.queryParamMap.get(key);
|
||||
const toRawValue = to.queryParamMap.get(key);
|
||||
|
||||
const fromValue =
|
||||
fromRawValue === null || fromRawValue === ''
|
||||
? defaultQueryParams[key]
|
||||
: fromRawValue;
|
||||
|
||||
const toValue =
|
||||
toRawValue === null || toRawValue === ''
|
||||
? defaultQueryParams[key]
|
||||
: toRawValue;
|
||||
|
||||
return fromValue !== toValue;
|
||||
});
|
||||
},
|
||||
},
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<h2 mat-dialog-title>
|
||||
{{ data.mode === 'create' ? 'Account erstellen' : 'Account bearbeiten' }}
|
||||
</h2>
|
||||
|
||||
<mat-dialog-content>
|
||||
<form class="account-form" [formGroup]="form" (ngSubmit)="submit()">
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>E-Mail</mat-label>
|
||||
<input matInput type="email" formControlName="email" />
|
||||
@if (form.controls.email.hasError('required')) {
|
||||
<mat-error>E-Mail ist erforderlich.</mat-error>
|
||||
} @else if (form.controls.email.hasError('email')) {
|
||||
<mat-error>Bitte gültige E-Mail eingeben.</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Name</mat-label>
|
||||
<input matInput formControlName="name" />
|
||||
@if (form.controls.name.hasError('required')) {
|
||||
<mat-error>Name ist erforderlich.</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Rolle</mat-label>
|
||||
<mat-select formControlName="role">
|
||||
@for (role of data.roles; track role) {
|
||||
<mat-option [value]="role">{{ role }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
|
||||
@if (data.canSelectOrganization) {
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Organisation</mat-label>
|
||||
<mat-select formControlName="organizationId">
|
||||
@for (organization of data.organizations; track organization.id) {
|
||||
<mat-option [value]="organization.id">
|
||||
{{ organization.name }}
|
||||
</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>
|
||||
{{
|
||||
data.mode === 'create'
|
||||
? 'Initiales Passwort'
|
||||
: 'Neues Passwort'
|
||||
}}
|
||||
</mat-label>
|
||||
<input matInput type="password" formControlName="password" />
|
||||
@if (form.controls.password.hasError('required')) {
|
||||
<mat-error>Passwort ist erforderlich.</mat-error>
|
||||
} @else if (form.controls.password.hasError('minlength')) {
|
||||
<mat-error>Mindestens 8 Zeichen.</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
</form>
|
||||
</mat-dialog-content>
|
||||
|
||||
<mat-dialog-actions align="end">
|
||||
<button mat-button type="button" (click)="close()">Abbrechen</button>
|
||||
<button mat-flat-button color="primary" type="button" (click)="submit()">
|
||||
<mat-icon>save</mat-icon>
|
||||
Speichern
|
||||
</button>
|
||||
</mat-dialog-actions>
|
||||
@@ -0,0 +1,22 @@
|
||||
.account-form {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px 14px;
|
||||
min-width: min(680px, calc(100vw - 64px));
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
.account-form mat-form-field {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
mat-dialog-actions {
|
||||
padding: 12px 24px 20px;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.account-form {
|
||||
grid-template-columns: 1fr;
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, inject } from '@angular/core';
|
||||
import {
|
||||
FormControl,
|
||||
FormGroup,
|
||||
ReactiveFormsModule,
|
||||
Validators,
|
||||
} from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import {
|
||||
MAT_DIALOG_DATA,
|
||||
MatDialogModule,
|
||||
MatDialogRef,
|
||||
} from '@angular/material/dialog';
|
||||
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,
|
||||
AccountProfile,
|
||||
AccountRole,
|
||||
CreateAccountPayload,
|
||||
OrganizationProfile,
|
||||
} from '../../shared/services/account-management.service';
|
||||
|
||||
export type AccountDialogMode = 'create' | 'edit';
|
||||
|
||||
export interface AccountDialogData {
|
||||
mode: AccountDialogMode;
|
||||
account?: AccountProfile;
|
||||
organizations: OrganizationProfile[];
|
||||
canSelectOrganization: boolean;
|
||||
roles: AccountRole[];
|
||||
}
|
||||
|
||||
export type AccountDialogResult =
|
||||
| { mode: 'create'; payload: CreateAccountPayload }
|
||||
| { mode: 'edit'; accountId: string; payload: AccountPayload };
|
||||
|
||||
@Component({
|
||||
selector: 'app-account-dialog',
|
||||
imports: [
|
||||
CommonModule,
|
||||
ReactiveFormsModule,
|
||||
MatButtonModule,
|
||||
MatDialogModule,
|
||||
MatFormFieldModule,
|
||||
MatIconModule,
|
||||
MatInputModule,
|
||||
MatSelectModule,
|
||||
],
|
||||
templateUrl: './account-dialog.component.html',
|
||||
styleUrl: './account-dialog.component.scss',
|
||||
standalone: true,
|
||||
})
|
||||
export class AccountDialogComponent {
|
||||
private readonly dialogRef = inject<
|
||||
MatDialogRef<AccountDialogComponent, AccountDialogResult | undefined>
|
||||
>(MatDialogRef);
|
||||
protected readonly data = inject<AccountDialogData>(MAT_DIALOG_DATA);
|
||||
|
||||
protected readonly form = new FormGroup({
|
||||
email: new FormControl<string>(this.data.account?.email ?? '', [
|
||||
Validators.required,
|
||||
Validators.email,
|
||||
]),
|
||||
name: new FormControl<string>(this.data.account?.name ?? '', [
|
||||
Validators.required,
|
||||
]),
|
||||
role: new FormControl<AccountRole>(this.data.account?.role ?? 'USER', [
|
||||
Validators.required,
|
||||
]),
|
||||
organizationId: new FormControl<string>(
|
||||
this.data.account?.organization_id ??
|
||||
(this.data.organizations.length === 1 ? this.data.organizations[0].id : ''),
|
||||
[Validators.required],
|
||||
),
|
||||
password: new FormControl<string>('', [
|
||||
...(this.data.mode === 'create' ? [Validators.required] : []),
|
||||
Validators.minLength(8),
|
||||
]),
|
||||
});
|
||||
|
||||
protected submit(): void {
|
||||
if (this.form.invalid) {
|
||||
this.form.markAllAsTouched();
|
||||
return;
|
||||
}
|
||||
|
||||
const value = this.form.getRawValue();
|
||||
|
||||
if (this.data.mode === 'create') {
|
||||
this.dialogRef.close({
|
||||
mode: 'create',
|
||||
payload: {
|
||||
email: value.email ?? '',
|
||||
name: value.name ?? '',
|
||||
role: value.role ?? 'USER',
|
||||
organization_id: value.organizationId ?? '',
|
||||
password: value.password ?? '',
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this.dialogRef.close({
|
||||
mode: 'edit',
|
||||
accountId: this.data.account!.id,
|
||||
payload: {
|
||||
email: value.email ?? '',
|
||||
name: value.name ?? '',
|
||||
role: value.role ?? 'USER',
|
||||
organization_id: value.organizationId ?? '',
|
||||
password: value.password || undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected close(): void {
|
||||
this.dialogRef.close(undefined);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
<section class="accounts-page">
|
||||
<header class="page-header">
|
||||
<div>
|
||||
<h1>Accounts</h1>
|
||||
<p>Account-Zugänge verwalten, Rollen setzen und Impersonation starten.</p>
|
||||
</div>
|
||||
<button mat-flat-button color="primary" type="button" (click)="startCreate()">
|
||||
<mat-icon>person_add</mat-icon>
|
||||
Neuer Account
|
||||
</button>
|
||||
</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.superadmin | async) {
|
||||
<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">
|
||||
<mat-icon>search</mat-icon>
|
||||
Suchen
|
||||
</button>
|
||||
<button mat-button type="button" (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>
|
||||
<th>Aktionen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (account of accounts; track account.id) {
|
||||
<tr [class.deleted]="account.deleted">
|
||||
<td>
|
||||
<button
|
||||
class="link-button"
|
||||
type="button"
|
||||
(click)="startEdit(account)">
|
||||
{{ account.name }}
|
||||
</button>
|
||||
</td>
|
||||
<td>{{ account.email }}</td>
|
||||
<td>{{ account.organization_name }}</td>
|
||||
<td><span class="role">{{ account.role }}</span></td>
|
||||
<td>
|
||||
<span class="status" [class.status--deleted]="account.deleted">
|
||||
{{ account.deleted ? 'deleted' : 'active' }}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<div class="row-actions">
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Bearbeiten"
|
||||
(click)="startEdit(account)">
|
||||
<mat-icon>edit</mat-icon>
|
||||
</button>
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Impersonate"
|
||||
[disabled]="!canImpersonate(account)"
|
||||
(click)="impersonate(account)">
|
||||
<mat-icon>switch_account</mat-icon>
|
||||
</button>
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Deaktivieren"
|
||||
[disabled]="account.is_current || account.deleted"
|
||||
(click)="deleteAccount(account)">
|
||||
<mat-icon>delete</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
} @empty {
|
||||
<tr>
|
||||
<td colspan="6" class="empty">Keine Accounts gefunden.</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="pagination">
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
[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"
|
||||
[disabled]="!canPageForward"
|
||||
(click)="loadAccounts(page + 1)">
|
||||
Weiter
|
||||
<mat-icon>chevron_right</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
@@ -0,0 +1,147 @@
|
||||
.accounts-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.page-header,
|
||||
.filters,
|
||||
.table-header,
|
||||
.pagination,
|
||||
.row-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.page-header p {
|
||||
color: #64748b;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.filters {
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.filters mat-form-field {
|
||||
width: min(320px, 100%);
|
||||
}
|
||||
|
||||
.filter-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-bottom: 22px;
|
||||
}
|
||||
|
||||
.table-panel {
|
||||
border: 1px solid #d7dde6;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.table-header {
|
||||
justify-content: space-between;
|
||||
padding: 16px;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.table-header span {
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.table-wrap {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
padding: 12px 16px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #edf1f7;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
th {
|
||||
color: #475569;
|
||||
font-weight: 700;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
tr.deleted {
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.link-button {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #1d4ed8;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.role,
|
||||
.status {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 24px;
|
||||
border-radius: 999px;
|
||||
padding: 2px 10px;
|
||||
background: #eef2ff;
|
||||
color: #3730a3;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.status {
|
||||
background: #dcfce7;
|
||||
color: #166534;
|
||||
}
|
||||
|
||||
.status--deleted {
|
||||
background: #fee2e2;
|
||||
color: #991b1b;
|
||||
}
|
||||
|
||||
.row-actions {
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.empty {
|
||||
color: #64748b;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.pagination {
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.accounts-page {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, OnInit, inject } from '@angular/core';
|
||||
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
||||
import { 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';
|
||||
|
||||
@Component({
|
||||
selector: 'app-accounts',
|
||||
imports: [
|
||||
CommonModule,
|
||||
ReactiveFormsModule,
|
||||
MatButtonModule,
|
||||
MatIconModule,
|
||||
MatFormFieldModule,
|
||||
MatInputModule,
|
||||
MatSelectModule,
|
||||
MatSnackBarModule,
|
||||
MatDialogModule,
|
||||
],
|
||||
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);
|
||||
|
||||
protected readonly roles: AccountRole[] = [
|
||||
'SUPER_ADMIN',
|
||||
'ADMIN',
|
||||
'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>(''),
|
||||
});
|
||||
|
||||
ngOnInit(): void {
|
||||
this.loadOrganizations();
|
||||
this.loadAccounts();
|
||||
}
|
||||
|
||||
protected loadAccounts(page = this.page): void {
|
||||
this.page = page;
|
||||
this.isLoading = true;
|
||||
this.accountService
|
||||
.listAccounts({
|
||||
page: this.page,
|
||||
pageSize: this.pageSize,
|
||||
search: this.filterForm.controls.search.value?.trim() || undefined,
|
||||
organizationId:
|
||||
this.filterForm.controls.organizationId.value || undefined,
|
||||
})
|
||||
.pipe(finalize(() => (this.isLoading = false)))
|
||||
.subscribe({
|
||||
next: (result) => {
|
||||
this.accounts = result.items;
|
||||
this.total = result.total;
|
||||
},
|
||||
error: () => {
|
||||
this.snackBar.open('Accounts konnten nicht geladen werden.', 'OK', {
|
||||
duration: 5000,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected loadOrganizations(): void {
|
||||
this.accountService.listOrganizations().subscribe({
|
||||
next: (organizations) => {
|
||||
this.organizations = organizations;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected applyFilters(): void {
|
||||
this.loadAccounts(0);
|
||||
}
|
||||
|
||||
protected resetFilters(): void {
|
||||
this.filterForm.reset({ search: '', organizationId: '' });
|
||||
this.loadAccounts(0);
|
||||
}
|
||||
|
||||
protected startCreate(): void {
|
||||
this.openAccountDialog({ mode: 'create' });
|
||||
}
|
||||
|
||||
protected startEdit(account: AccountProfile): void {
|
||||
this.openAccountDialog({ mode: 'edit', account });
|
||||
}
|
||||
|
||||
private saveDialogResult(result: AccountDialogResult): void {
|
||||
const request =
|
||||
result.mode === 'create'
|
||||
? this.accountService.createAccount(result.payload)
|
||||
: this.accountService.updateAccount(result.accountId, result.payload);
|
||||
|
||||
request.subscribe({
|
||||
next: () => {
|
||||
this.snackBar.open('Account wurde gespeichert.', 'OK', {
|
||||
duration: 3000,
|
||||
});
|
||||
this.loadAccounts(0);
|
||||
},
|
||||
error: (error) => {
|
||||
const message =
|
||||
error.status === 409
|
||||
? 'Diese E-Mail-Adresse wird bereits verwendet.'
|
||||
: 'Account konnte nicht gespeichert werden.';
|
||||
this.snackBar.open(message, 'OK', { duration: 5000 });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private openAccountDialog(data: {
|
||||
mode: 'create' | 'edit';
|
||||
account?: AccountProfile;
|
||||
}): void {
|
||||
import('./account-dialog.component').then(({ AccountDialogComponent }) => {
|
||||
const dialogRef = this.dialog.open<
|
||||
AccountDialogComponent,
|
||||
{
|
||||
mode: 'create' | 'edit';
|
||||
account?: AccountProfile;
|
||||
organizations: OrganizationProfile[];
|
||||
canSelectOrganization: boolean;
|
||||
roles: AccountRole[];
|
||||
},
|
||||
AccountDialogResult | undefined
|
||||
>(AccountDialogComponent, {
|
||||
width: '760px',
|
||||
maxWidth: 'calc(100vw - 32px)',
|
||||
data: {
|
||||
...data,
|
||||
organizations: this.organizations,
|
||||
canSelectOrganization: this.credentialService.superadmin.value,
|
||||
roles: this.roles,
|
||||
},
|
||||
});
|
||||
|
||||
dialogRef.afterClosed().subscribe((result) => {
|
||||
if (result) {
|
||||
this.saveDialogResult(result);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
protected deleteAccount(account: AccountProfile): void {
|
||||
if (account.is_current) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.accountService.deleteAccount(account.id).subscribe({
|
||||
next: () => {
|
||||
this.snackBar.open('Account wurde deaktiviert.', 'OK', {
|
||||
duration: 3000,
|
||||
});
|
||||
this.loadAccounts();
|
||||
},
|
||||
error: () => {
|
||||
this.snackBar.open('Account konnte nicht deaktiviert werden.', 'OK', {
|
||||
duration: 5000,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected impersonate(account: AccountProfile): 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;
|
||||
}
|
||||
|
||||
protected canImpersonate(account: AccountProfile): boolean {
|
||||
if (account.is_current || account.deleted) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.credentialService.superadmin.value) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
this.credentialService.universityadmin.value &&
|
||||
(account.role === 'MANAGER' || account.role === 'USER')
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,68 +1,154 @@
|
||||
<div class="container">
|
||||
<form class="form" [formGroup]="loginForm">
|
||||
<h3>Anmeldung</h3>
|
||||
<p class="field">
|
||||
Um auf den Dienst zuzugreifen, musst Du Deine Anmeldedaten eingeben.
|
||||
</p>
|
||||
|
||||
<mat-form-field class="field">
|
||||
<mat-label>Login</mat-label>
|
||||
<input id="dp-login" matInput formControlName="login" />
|
||||
@if (loginForm.controls.login.hasError('required')) {
|
||||
<mat-error>Fehler: <b>Login</b> erforderlich.</mat-error>
|
||||
} @else if (loginForm.controls.login.hasError('minlength')) {
|
||||
<mat-error>Fehler: <b>Login</b> ist unvollständig.</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field class="field">
|
||||
<mat-label>Passwort</mat-label>
|
||||
<input
|
||||
id="dp-password"
|
||||
matInput
|
||||
[type]="showPassword ? 'text' : 'password'"
|
||||
formControlName="password" />
|
||||
@if (showPassword) {
|
||||
<mat-icon matSuffix (click)="showPassword = false">visibility</mat-icon>
|
||||
} @else {
|
||||
<mat-icon matSuffix (click)="showPassword = true"
|
||||
>visibility_off</mat-icon
|
||||
>
|
||||
}
|
||||
@if (loginForm.controls.password.hasError('required')) {
|
||||
<mat-error>Fehler: <b>Passwort</b> erforderlich.</mat-error>
|
||||
} @else if (loginForm.controls.password.hasError('minlength')) {
|
||||
<mat-error>Fehler: <b>Passwort</b> ist unvollständig.</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
<button
|
||||
mat-raised-button
|
||||
class="button"
|
||||
(click)="login()"
|
||||
[disabled]="!loginForm.valid || (credentialService.validating | async)">
|
||||
Anmelden
|
||||
</button>
|
||||
|
||||
<div class="field" style="text-align: center; margin-top: -10px">
|
||||
<button mat-button type="button" routerLink="/register">
|
||||
Noch kein Konto? <b>Registrieren</b>
|
||||
</button>
|
||||
<section class="login-page">
|
||||
<div class="login-panel">
|
||||
<div class="brand-block">
|
||||
<span class="eyebrow">SmartGuide Account Portal</span>
|
||||
<h1>Login</h1>
|
||||
<p>
|
||||
Melde Dich mit Deiner Organisation an. Nach den Zugangsdaten erhältst Du
|
||||
einen einmaligen Code per E-Mail.
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
<p class="progress">
|
||||
@if (credentialService.validating | async) {
|
||||
<span><i>Anmeldung läuft,</i> bitte warte einen Moment.</span>
|
||||
|
||||
<div class="stepper" aria-label="Login-Fortschritt">
|
||||
<div class="step" [class.step--active]="currentStep === 'credentials'">
|
||||
<span>1</span>
|
||||
<strong>Zugangsdaten</strong>
|
||||
</div>
|
||||
<div class="step-line"></div>
|
||||
<div class="step" [class.step--active]="currentStep === 'otk'">
|
||||
<span>2</span>
|
||||
<strong>OTK-Code</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (currentStep === 'credentials') {
|
||||
<form
|
||||
class="login-form"
|
||||
[formGroup]="credentialsForm"
|
||||
(ngSubmit)="requestOtk()">
|
||||
<mat-form-field class="field" appearance="outline">
|
||||
<mat-label>E-Mail-Adresse</mat-label>
|
||||
<input
|
||||
id="login-email"
|
||||
matInput
|
||||
type="email"
|
||||
autocomplete="email"
|
||||
formControlName="email" />
|
||||
@if (credentialsForm.controls.email.hasError('required')) {
|
||||
<mat-error>E-Mail-Adresse ist erforderlich.</mat-error>
|
||||
} @else if (credentialsForm.controls.email.hasError('email')) {
|
||||
<mat-error>Bitte gib eine gültige E-Mail-Adresse ein.</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field class="field" appearance="outline">
|
||||
<mat-label>Passwort</mat-label>
|
||||
<input
|
||||
id="login-password"
|
||||
matInput
|
||||
[type]="showPassword ? 'text' : 'password'"
|
||||
autocomplete="current-password"
|
||||
formControlName="password" />
|
||||
<button
|
||||
mat-icon-button
|
||||
matSuffix
|
||||
type="button"
|
||||
[attr.aria-label]="showPassword ? 'Passwort verbergen' : 'Passwort anzeigen'"
|
||||
(click)="showPassword = !showPassword">
|
||||
<mat-icon>{{ showPassword ? 'visibility' : 'visibility_off' }}</mat-icon>
|
||||
</button>
|
||||
@if (credentialsForm.controls.password.hasError('required')) {
|
||||
<mat-error>Passwort ist erforderlich.</mat-error>
|
||||
} @else if (credentialsForm.controls.password.hasError('minlength')) {
|
||||
<mat-error>Passwort muss mindestens 8 Zeichen haben.</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<button
|
||||
mat-flat-button
|
||||
color="primary"
|
||||
class="submit-button"
|
||||
type="submit"
|
||||
[disabled]="credentialsForm.invalid || isSubmitting">
|
||||
@if (isSubmitting) {
|
||||
Code wird gesendet...
|
||||
} @else {
|
||||
Code per E-Mail senden
|
||||
}
|
||||
</button>
|
||||
|
||||
<div class="form-actions">
|
||||
<a routerLink="/login">Passwort vergessen?</a>
|
||||
<a routerLink="/register">Konto erstellen</a>
|
||||
</div>
|
||||
</form>
|
||||
} @else {
|
||||
@if (
|
||||
(credentialService.authenticated | async) &&
|
||||
!(credentialService.superadmin | async) &&
|
||||
!(credentialService.universityadmin | async)
|
||||
) {
|
||||
<span class="error"
|
||||
>Fehler: <b>{{ credentialService.login.value }}</b> ist nicht
|
||||
berechtigt.</span
|
||||
>
|
||||
}
|
||||
<form class="login-form" [formGroup]="otkForm" (ngSubmit)="login()">
|
||||
<div class="code-intro">
|
||||
<mat-icon>mark_email_unread</mat-icon>
|
||||
<div>
|
||||
<strong>Code eingeben</strong>
|
||||
<span>
|
||||
Wir haben den Code an
|
||||
{{ credentialsForm.controls.email.value || 'Deine E-Mail-Adresse' }}
|
||||
gesendet.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<mat-form-field class="field" appearance="outline">
|
||||
<mat-label>OTK-Code</mat-label>
|
||||
<input
|
||||
id="login-otk"
|
||||
matInput
|
||||
inputmode="text"
|
||||
autocomplete="one-time-code"
|
||||
formControlName="code" />
|
||||
@if (otkForm.controls.code.hasError('required')) {
|
||||
<mat-error>OTK-Code ist erforderlich.</mat-error>
|
||||
} @else if (otkForm.controls.code.hasError('pattern')) {
|
||||
<mat-error>Bitte gib den Code aus der E-Mail ein.</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<div
|
||||
class="expiry"
|
||||
[class.expiry--expired]="codeExpiresIn === 0"
|
||||
aria-live="polite">
|
||||
<mat-icon>timer</mat-icon>
|
||||
@if (codeExpiresIn > 0) {
|
||||
<span>Code läuft in {{ formatCountdown() }} ab.</span>
|
||||
} @else {
|
||||
<span>Code ist abgelaufen. Bitte neuen Code anfordern.</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
<button
|
||||
mat-flat-button
|
||||
color="primary"
|
||||
class="submit-button"
|
||||
type="submit"
|
||||
[disabled]="otkForm.invalid || isSubmitting || codeExpiresIn === 0">
|
||||
@if (isSubmitting) {
|
||||
Anmeldung wird geprüft...
|
||||
} @else {
|
||||
Anmelden
|
||||
}
|
||||
</button>
|
||||
|
||||
<div class="form-actions">
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
(click)="resendCode()"
|
||||
[disabled]="isSubmitting">
|
||||
Code erneut senden
|
||||
</button>
|
||||
<button mat-button type="button" (click)="editCredentials()">
|
||||
E-Mail ändern
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -1,54 +1,187 @@
|
||||
.container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
.login-page {
|
||||
display: grid;
|
||||
min-height: calc(100svh - 41px);
|
||||
place-items: center;
|
||||
padding: 48px 20px;
|
||||
background:
|
||||
radial-gradient(circle at top left, rgba(61, 124, 255, 0.12), transparent 34%),
|
||||
linear-gradient(160deg, #f7f9ff 0%, #ffffff 64%);
|
||||
}
|
||||
|
||||
.login-panel {
|
||||
width: min(100%, 480px);
|
||||
padding: 34px;
|
||||
background: var(--sg-surface);
|
||||
border: 1px solid var(--sg-border);
|
||||
border-radius: var(--sg-radius-sm);
|
||||
box-shadow: var(--sg-shadow-md);
|
||||
}
|
||||
|
||||
.brand-block {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
color: var(--sg-blue-highlight);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 32px;
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
.stepper {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr auto;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.step {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.step span {
|
||||
display: grid;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
place-items: center;
|
||||
border: 1px solid var(--sg-border-strong);
|
||||
border-radius: 50%;
|
||||
background: var(--sg-surface);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.step--active {
|
||||
color: var(--sg-text);
|
||||
}
|
||||
|
||||
.step--active span {
|
||||
background: var(--sg-primary);
|
||||
border-color: var(--sg-primary);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.step-line {
|
||||
height: 1px;
|
||||
background: var(--sg-border);
|
||||
}
|
||||
|
||||
.login-form {
|
||||
display: grid;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.field,
|
||||
.submit-button {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: linear-gradient(160deg, #f4f6fb 0%, #e8ecf7 100%);
|
||||
}
|
||||
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
background: white;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
box-shadow:
|
||||
0 2px 12px rgba(26, 58, 110, 0.1),
|
||||
0 1px 4px rgba(0, 0, 0, 0.06);
|
||||
gap: 20px;
|
||||
padding: 36px 32px 28px;
|
||||
}
|
||||
|
||||
.form h3 {
|
||||
margin: 0 0 4px;
|
||||
font-weight: 600;
|
||||
color: #1a3a6e;
|
||||
}
|
||||
|
||||
.button {
|
||||
.submit-button {
|
||||
min-height: 48px;
|
||||
min-width: 140px;
|
||||
border-radius: 8px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.02em;
|
||||
border-radius: var(--sg-radius-sm);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.field {
|
||||
width: 400px;
|
||||
.form-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
min-height: 40px;
|
||||
}
|
||||
|
||||
.progress {
|
||||
padding-top: 5px;
|
||||
width: 300px;
|
||||
height: 2em;
|
||||
text-align: center;
|
||||
font-size: small;
|
||||
color: #585f71;
|
||||
.form-actions a,
|
||||
.form-actions button {
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.error {
|
||||
.code-intro {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
gap: 14px;
|
||||
padding: 14px;
|
||||
background: var(--sg-surface-soft);
|
||||
border: 1px solid var(--sg-border);
|
||||
border-radius: var(--sg-radius-sm);
|
||||
}
|
||||
|
||||
.code-intro mat-icon {
|
||||
color: var(--sg-blue-highlight);
|
||||
}
|
||||
|
||||
.code-intro div {
|
||||
display: grid;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.code-intro span {
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 13px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.expiry {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--sg-success);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.expiry mat-icon {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.expiry--expired {
|
||||
color: #ba1a1a;
|
||||
}
|
||||
|
||||
@media (max-width: 560px) {
|
||||
.login-page {
|
||||
padding: 28px 14px;
|
||||
place-items: start center;
|
||||
}
|
||||
|
||||
.login-panel {
|
||||
padding: 24px 18px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 28px;
|
||||
}
|
||||
|
||||
.stepper {
|
||||
grid-template-columns: 1fr;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.step-line {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,9 +11,12 @@ import { MatInputModule } from '@angular/material/input';
|
||||
import { CredentialService } from '../../shared/services/credential.service';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Subscription } from 'rxjs';
|
||||
import { finalize, Subscription } from 'rxjs';
|
||||
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
||||
import { Router, RouterLink } from '@angular/router';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
|
||||
type LoginStep = 'credentials' | 'otk';
|
||||
|
||||
@Component({
|
||||
selector: 'app-app-login',
|
||||
@@ -32,20 +35,30 @@ import { Router, RouterLink } from '@angular/router';
|
||||
standalone: true,
|
||||
})
|
||||
export class AppLoginComponent implements OnInit, OnDestroy {
|
||||
loginForm = new FormGroup({
|
||||
login: new FormControl<string>('', [
|
||||
Validators.required,
|
||||
Validators.minLength(4),
|
||||
]),
|
||||
credentialsForm = new FormGroup({
|
||||
email: new FormControl<string>('', [Validators.required, Validators.email]),
|
||||
password: new FormControl<string>('', [
|
||||
Validators.required,
|
||||
Validators.minLength(4),
|
||||
Validators.minLength(8),
|
||||
]),
|
||||
});
|
||||
|
||||
otkForm = new FormGroup({
|
||||
code: new FormControl<string>('', [
|
||||
Validators.required,
|
||||
Validators.pattern(/^[0-9A-Za-z]{6,10}$/),
|
||||
]),
|
||||
});
|
||||
|
||||
currentStep: LoginStep = 'credentials';
|
||||
showPassword = false;
|
||||
isSubmitting = false;
|
||||
codeExpiresIn = 0;
|
||||
readonly codeLifetimeSeconds = 300;
|
||||
|
||||
subscription?: Subscription;
|
||||
private countdownInterval?: ReturnType<typeof setInterval>;
|
||||
private accountId?: string;
|
||||
|
||||
constructor(
|
||||
protected credentialService: CredentialService,
|
||||
@@ -57,14 +70,16 @@ export class AppLoginComponent implements OnInit, OnDestroy {
|
||||
this.subscription = this.credentialService.validating.subscribe(
|
||||
(validating) => {
|
||||
if (validating) {
|
||||
this.loginForm.disable();
|
||||
this.credentialsForm.disable();
|
||||
this.otkForm.disable();
|
||||
} else {
|
||||
this.loginForm.enable();
|
||||
this.credentialsForm.enable();
|
||||
this.otkForm.enable();
|
||||
this.checkEnter();
|
||||
}
|
||||
},
|
||||
);
|
||||
if (!this.credentialService.validating) {
|
||||
if (!this.credentialService.validating.value) {
|
||||
this.checkEnter();
|
||||
}
|
||||
}
|
||||
@@ -80,13 +95,161 @@ export class AppLoginComponent implements OnInit, OnDestroy {
|
||||
this.subscription.unsubscribe();
|
||||
this.subscription = undefined;
|
||||
}
|
||||
this.stopCountdown();
|
||||
}
|
||||
|
||||
requestOtk() {
|
||||
if (this.credentialsForm.invalid || this.isSubmitting) {
|
||||
this.credentialsForm.markAllAsTouched();
|
||||
return;
|
||||
}
|
||||
|
||||
this.isSubmitting = true;
|
||||
this.credentialsForm.disable();
|
||||
|
||||
const email = this.credentialsForm.controls.email.value ?? '';
|
||||
const password = this.credentialsForm.controls.password.value ?? '';
|
||||
|
||||
this.credentialService
|
||||
.requestOtk(email, password)
|
||||
.pipe(
|
||||
finalize(() => {
|
||||
this.isSubmitting = false;
|
||||
this.credentialsForm.enable();
|
||||
}),
|
||||
)
|
||||
.subscribe({
|
||||
next: (accountId) => {
|
||||
if (!accountId) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.accountId = accountId;
|
||||
this.currentStep = 'otk';
|
||||
this.otkForm.reset();
|
||||
this.startCountdown();
|
||||
this.snackBar.open(
|
||||
'OTK-Code wurde an die E-Mail-Adresse gesendet.',
|
||||
'OK',
|
||||
{
|
||||
duration: 4000,
|
||||
},
|
||||
);
|
||||
},
|
||||
error: (error: HttpErrorResponse) => {
|
||||
this.credentialService.logoutAcount();
|
||||
this.snackBar.open(this.getLoginErrorMessage(error), 'OK', {
|
||||
duration: 5000,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
resendCode() {
|
||||
if (this.isSubmitting) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.requestOtk();
|
||||
}
|
||||
|
||||
login() {
|
||||
let user = this.loginForm.controls.login.value;
|
||||
let pass = this.loginForm.controls.password.value;
|
||||
if (user && pass) {
|
||||
this.credentialService.loginAccount(user, pass);
|
||||
if (this.otkForm.invalid || this.isSubmitting) {
|
||||
this.otkForm.markAllAsTouched();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.codeExpiresIn <= 0) {
|
||||
this.snackBar.open(
|
||||
'Der Code ist abgelaufen. Bitte fordere einen neuen Code an.',
|
||||
'OK',
|
||||
{ duration: 5000 },
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.accountId) {
|
||||
this.snackBar.open(
|
||||
'Bitte fordere zuerst einen neuen Code an.',
|
||||
'OK',
|
||||
{ duration: 5000 },
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.isSubmitting = true;
|
||||
this.otkForm.disable();
|
||||
|
||||
const email = this.credentialsForm.controls.email.value ?? '';
|
||||
const code = this.otkForm.controls.code.value ?? '';
|
||||
|
||||
this.credentialService
|
||||
.loginWithOtk(this.accountId, email, code)
|
||||
.pipe(
|
||||
finalize(() => {
|
||||
this.isSubmitting = false;
|
||||
this.otkForm.enable();
|
||||
}),
|
||||
)
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.stopCountdown();
|
||||
this.router.navigate(['/dashboard']);
|
||||
},
|
||||
error: (error: HttpErrorResponse) => {
|
||||
this.credentialService.logoutAcount();
|
||||
this.snackBar.open(this.getLoginErrorMessage(error), 'OK', {
|
||||
duration: 5000,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
editCredentials() {
|
||||
this.currentStep = 'credentials';
|
||||
this.accountId = undefined;
|
||||
this.stopCountdown();
|
||||
this.otkForm.reset();
|
||||
}
|
||||
|
||||
formatCountdown(): string {
|
||||
const minutes = Math.floor(this.codeExpiresIn / 60);
|
||||
const seconds = this.codeExpiresIn % 60;
|
||||
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
private startCountdown(): void {
|
||||
this.stopCountdown();
|
||||
this.codeExpiresIn = this.codeLifetimeSeconds;
|
||||
this.countdownInterval = setInterval(() => {
|
||||
this.codeExpiresIn = Math.max(this.codeExpiresIn - 1, 0);
|
||||
|
||||
if (this.codeExpiresIn === 0) {
|
||||
this.stopCountdown(false);
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
private stopCountdown(reset = true): void {
|
||||
if (this.countdownInterval) {
|
||||
clearInterval(this.countdownInterval);
|
||||
this.countdownInterval = undefined;
|
||||
}
|
||||
|
||||
if (reset) {
|
||||
this.codeExpiresIn = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private getLoginErrorMessage(error: HttpErrorResponse): string {
|
||||
if (error.status === 401) {
|
||||
return 'E-Mail, Passwort oder OTK-Code ist ungültig.';
|
||||
}
|
||||
|
||||
if (error.status === 403) {
|
||||
return 'Dieses Konto ist nicht für die Anmeldung freigeschaltet.';
|
||||
}
|
||||
|
||||
return 'Die Anmeldung konnte nicht abgeschlossen werden. Bitte versuche es erneut.';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { Location } from '@angular/common';
|
||||
import { Component, input, OnInit, signal, inject } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
@@ -28,7 +27,6 @@ export class ErrorPageComponent implements OnInit {
|
||||
|
||||
isDetailsOpen = signal<boolean>(false);
|
||||
|
||||
private readonly location = inject(Location);
|
||||
private readonly errorService = inject(ErrorService);
|
||||
|
||||
ngOnInit() {
|
||||
@@ -53,6 +51,6 @@ export class ErrorPageComponent implements OnInit {
|
||||
}
|
||||
|
||||
goBack() {
|
||||
this.location.back();
|
||||
window.history.back();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,19 +4,10 @@
|
||||
<div class="funding-area">
|
||||
<mat-card appearance="outlined">
|
||||
<mat-card-content>
|
||||
<mat-form-field style="width: 100%">
|
||||
<mat-label>Suche nach Themen</mat-label>
|
||||
<input
|
||||
matInput
|
||||
type="search"
|
||||
[debounceTime]="300"
|
||||
[(debouncedValue)]="urlSearchTerm"
|
||||
(debouncedValueChange)="handleSearchTermChange($event)" />
|
||||
<mat-icon matPrefix>search</mat-icon>
|
||||
<button matIconButton matSuffix (click)="clearSearchTerm()">
|
||||
<mat-icon>clear</mat-icon>
|
||||
</button>
|
||||
</mat-form-field>
|
||||
<app-query-param-input
|
||||
label="Suche nach Themen"
|
||||
queryParamKey="search" />
|
||||
|
||||
<mat-tab-group
|
||||
[selectedIndex]="tabIndex()"
|
||||
(selectedTabChange)="selectedTabChange($event)">
|
||||
@@ -24,24 +15,20 @@
|
||||
<app-data-table
|
||||
[data]="euProjectData"
|
||||
[columns]="euProjectColumns"
|
||||
[activeSortKey]="urlSortKey()"
|
||||
[sortDirection]="urlSortDirection()"
|
||||
(sortChange)="handleSortChange($event)" />
|
||||
queryParamSortKey="sort_by"
|
||||
queryParamSortDirectionKey="sort_direction" />
|
||||
</mat-tab>
|
||||
<mat-tab label="Bund">
|
||||
<app-data-table
|
||||
[data]="bundProjectData"
|
||||
[columns]="bundProjectColumns"
|
||||
[activeSortKey]="urlSortKey()"
|
||||
[sortDirection]="urlSortDirection()"
|
||||
(sortChange)="handleSortChange($event)" />
|
||||
queryParamSortKey="sort_by"
|
||||
queryParamSortDirectionKey="sort_direction" />
|
||||
</mat-tab>
|
||||
</mat-tab-group>
|
||||
<mat-paginator
|
||||
[length]="this.pageTotal()"
|
||||
[pageSize]="this.pageSize()"
|
||||
[pageIndex]="this.pageIndex()"
|
||||
(page)="handlePageChange($event)" />
|
||||
<app-query-param-paginator
|
||||
[total]="pageTotal()"
|
||||
[pageSizeOptions]="[10, 20, 50]" />
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
<div class="funding-info-section">
|
||||
@@ -75,9 +62,7 @@
|
||||
undefined
|
||||
" />
|
||||
<app-person-network-info-card
|
||||
[description]="
|
||||
'Durchschnittliche jährliche Förderung durch die Europäische Union'
|
||||
"
|
||||
[description]="'Durchschnittliche jährliche Förderung durch die Europäische Union'"
|
||||
[value]="
|
||||
(euAverageAnnualFunding()
|
||||
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
effect,
|
||||
input,
|
||||
OnInit,
|
||||
signal,
|
||||
TemplateRef,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
@@ -19,7 +18,6 @@ import {
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatTabChangeEvent, MatTabsModule } from '@angular/material/tabs';
|
||||
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import {
|
||||
@@ -27,13 +25,13 @@ import {
|
||||
DataTableComponent,
|
||||
} from '../../shared/ui/data-table/data-table.component';
|
||||
import { CurrencyPipe, DatePipe } from '@angular/common';
|
||||
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
|
||||
import { Sort, SortDirection } from '@angular/material/sort';
|
||||
import { DebounceDirective } from '../../directives/debounce.directive';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { InstitutionProjectsFundingGraphComponent } from '../institution-projects-funding-graph/institution-projects-funding-graph.component';
|
||||
import { PersonNetworkInfoCardComponent } from '../person-network-info-card/person-network-info-card.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';
|
||||
|
||||
type BundProjectRow = {
|
||||
id: string;
|
||||
@@ -58,18 +56,18 @@ type EuProjectRow = {
|
||||
MatCardModule,
|
||||
MatFormFieldModule,
|
||||
MatTabsModule,
|
||||
MatPaginatorModule,
|
||||
FormsModule,
|
||||
MatInputModule,
|
||||
DataTableComponent,
|
||||
DatePipe,
|
||||
CurrencyPipe,
|
||||
DebounceDirective,
|
||||
MatIconModule,
|
||||
MatButtonModule,
|
||||
InstitutionProjectsFundingGraphComponent,
|
||||
PersonNetworkInfoCardComponent,
|
||||
RouterModule,
|
||||
QueryParamPaginatorComponent,
|
||||
QueryParamInputComponent,
|
||||
],
|
||||
templateUrl: './institution-projects.component.html',
|
||||
styleUrl: './institution-projects.component.scss',
|
||||
@@ -117,24 +115,10 @@ export class InstitutionProjectsComponent implements OnInit {
|
||||
return funding.annual_average_over_period ?? 0;
|
||||
});
|
||||
|
||||
urlSortKey = signal<string>('');
|
||||
urlSortDirection = signal<SortDirection>('');
|
||||
urlSearchTerm = signal<string>('');
|
||||
|
||||
constructor(
|
||||
private readonly activatedRoute: ActivatedRoute,
|
||||
private readonly router: Router,
|
||||
) {
|
||||
this.activatedRoute.queryParams
|
||||
.pipe(takeUntilDestroyed())
|
||||
.subscribe((params) => {
|
||||
this.urlSortKey.set(params['sort_by'] ?? '');
|
||||
this.urlSortDirection.set(
|
||||
(params['sort_direction'] as SortDirection) ?? '',
|
||||
);
|
||||
this.urlSearchTerm.set(params['search'] ?? '');
|
||||
});
|
||||
|
||||
effect(() => {
|
||||
const euPage = this.cordisEuProjectPage();
|
||||
if (euPage) {
|
||||
@@ -151,20 +135,6 @@ export class InstitutionProjectsComponent implements OnInit {
|
||||
: [];
|
||||
}
|
||||
});
|
||||
|
||||
effect(() => {
|
||||
const searchTerm = this.urlSearchTerm();
|
||||
if (searchTerm) {
|
||||
this.router.navigate([], {
|
||||
queryParams: { search: searchTerm, page: 0, size: 10 },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
effect(() => {
|
||||
console.log('Funding over time data:', this.bundProjectsFunding());
|
||||
});
|
||||
}
|
||||
|
||||
readonly queryParams = toSignal(this.activatedRoute.queryParamMap, {
|
||||
@@ -175,12 +145,6 @@ export class InstitutionProjectsComponent implements OnInit {
|
||||
return this.queryParams()?.get('project_tab') ?? 'eu';
|
||||
});
|
||||
|
||||
readonly page = computed(() => {
|
||||
const pageParam = this.queryParams()?.get('page');
|
||||
const page = pageParam ? Number.parseInt(pageParam, 10) : 0;
|
||||
return Number.isNaN(page) ? 0 : page;
|
||||
});
|
||||
|
||||
readonly selectedPage = computed(() => {
|
||||
if (this.displayedProjects() === 'eu') {
|
||||
return this.cordisEuProjectPage();
|
||||
@@ -193,14 +157,6 @@ export class InstitutionProjectsComponent implements OnInit {
|
||||
return this.selectedPage()?.total ?? 0;
|
||||
});
|
||||
|
||||
readonly pageSize = computed(() => {
|
||||
return this.selectedPage()?.size ?? 10;
|
||||
});
|
||||
|
||||
readonly pageIndex = computed(() => {
|
||||
return this.selectedPage()?.page ?? 0;
|
||||
});
|
||||
|
||||
ngOnInit(): void {
|
||||
this.euProjectColumns = [
|
||||
{
|
||||
@@ -319,32 +275,4 @@ export class InstitutionProjectsComponent implements OnInit {
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
handlePageChange(event: PageEvent): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: { page: event.pageIndex, size: event.pageSize },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
handleSortChange(event: Sort): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: { sort_by: event.active, sort_direction: event.direction },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
handleSearchTermChange(newTerm: string): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: { search: newTerm, page: 0, size: 10 },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
clearSearchTerm(): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: { search: null, page: 0, size: 10 },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,34 +4,19 @@
|
||||
<mat-divider />
|
||||
|
||||
<div class="search-and-sorting">
|
||||
<mat-form-field style="width: 100%">
|
||||
<mat-label>Suche nach Namen</mat-label>
|
||||
<input
|
||||
matInput
|
||||
type="search"
|
||||
[debounceTime]="300"
|
||||
[(debouncedValue)]="urlSearchTerm"
|
||||
(debouncedValueChange)="handleSearchTermChange($event)" />
|
||||
<mat-icon matPrefix>search</mat-icon>
|
||||
<button matIconButton matSuffix (click)="clearSearchTerm()">
|
||||
<mat-icon>clear</mat-icon>
|
||||
</button>
|
||||
</mat-form-field>
|
||||
<app-query-param-input
|
||||
[label]="'Suche nach Namen'"
|
||||
[debounceTime]="400"
|
||||
[queryParamKey]="'search'" />
|
||||
|
||||
<div class="sorting">
|
||||
<select (change)="handleSortFieldChange($event)" [value]="urlSortBy()">
|
||||
<option value="relevance">Relevanz</option>
|
||||
<option value="name">Name</option>
|
||||
<option value="works_count">Anzahl Publikationen</option>
|
||||
<option value="citations_count">Anzahl Zitationen</option>
|
||||
</select>
|
||||
<app-query-param-selector
|
||||
[options]="sortingOptions"
|
||||
[queryParamKey]="'sort_by'" />
|
||||
|
||||
<select
|
||||
(change)="handleSortOrderChange($event)"
|
||||
[value]="urlSortingOrder()">
|
||||
<option value="desc">Absteigend</option>
|
||||
<option value="asc">Aufsteigend</option>
|
||||
</select>
|
||||
<app-query-param-selector
|
||||
[options]="sortingDirectionOptions"
|
||||
[queryParamKey]="'sorting_order'" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -106,11 +91,7 @@
|
||||
|
||||
<mat-divider />
|
||||
|
||||
<mat-paginator
|
||||
[length]="institutionPageValue.total"
|
||||
[pageSize]="institutionPageValue.size"
|
||||
[pageSizeOptions]="[10, 20, 50]"
|
||||
[pageIndex]="institutionPageValue.page"
|
||||
(page)="handlePageChange($event)">
|
||||
</mat-paginator>
|
||||
<app-query-param-paginator
|
||||
[total]="institutionPageValue.total ?? 0"
|
||||
[pageSizeOptions]="[10, 20, 50]" />
|
||||
</div>
|
||||
|
||||
@@ -25,26 +25,10 @@
|
||||
.cards {
|
||||
display: grid;
|
||||
gap: 1.5rem;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
grid-template-columns: repeat(auto-fit, minmax(380px, 1fr));
|
||||
padding: 0 1rem;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.cards {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.cards {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
mat-paginator {
|
||||
background-color: var(--sg-background);
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 0.5rem;
|
||||
background-color: var(--sg-background);
|
||||
|
||||
@@ -1,26 +1,28 @@
|
||||
import { Component, effect, input, signal } from '@angular/core';
|
||||
import { Component, input } from '@angular/core';
|
||||
import { Institution, InstitutionPage } from '../../api';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { RouterModule } from '@angular/router';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { DebounceDirective } from '../../directives/debounce.directive';
|
||||
import { MatPaginator, PageEvent } from '@angular/material/paginator';
|
||||
import { MatDividerModule } from '@angular/material/divider';
|
||||
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
|
||||
import {
|
||||
QueryParamSelectorComponent,
|
||||
SelectorOption,
|
||||
} from '../../shared/ui/query-param-selector/query-param-selector.component';
|
||||
import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-institutions',
|
||||
imports: [
|
||||
MatButtonModule,
|
||||
MatCardModule,
|
||||
MatInputModule,
|
||||
MatIconModule,
|
||||
DebounceDirective,
|
||||
MatPaginator,
|
||||
MatDividerModule,
|
||||
RouterModule,
|
||||
QueryParamPaginatorComponent,
|
||||
QueryParamSelectorComponent,
|
||||
QueryParamInputComponent,
|
||||
],
|
||||
templateUrl: './institutions.component.html',
|
||||
styleUrl: './institutions.component.scss',
|
||||
@@ -28,74 +30,21 @@ import { MatDividerModule } from '@angular/material/divider';
|
||||
export class InstitutionsComponent {
|
||||
institutionPage = input.required<InstitutionPage>();
|
||||
|
||||
urlSearchTerm = signal<string>('');
|
||||
urlSortBy = signal<string>('relevance');
|
||||
urlSortingOrder = signal<string>('desc');
|
||||
|
||||
constructor(
|
||||
private readonly activatedRoute: ActivatedRoute,
|
||||
private readonly router: Router,
|
||||
) {
|
||||
this.activatedRoute.queryParams
|
||||
.pipe(takeUntilDestroyed())
|
||||
.subscribe((params) => {
|
||||
this.urlSearchTerm.set(params['search'] || '');
|
||||
this.urlSortBy.set(params['sort_by'] || 'relevance');
|
||||
this.urlSortingOrder.set(params['sorting_order'] || 'desc');
|
||||
});
|
||||
|
||||
effect(() => {
|
||||
const searchTerm = this.urlSearchTerm();
|
||||
this.router.navigate([], {
|
||||
queryParams: { search: searchTerm },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
handleSearchTermChange(newTerm: string): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: { search: newTerm },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
clearSearchTerm(): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: { search: null },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
handlePageChange(event: PageEvent): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: { page: event.pageIndex, size: event.pageSize },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
sortingOptions: SelectorOption[] = [
|
||||
{ value: 'relevance', display_name: 'Relevanz' },
|
||||
{ value: 'name', display_name: 'Name' },
|
||||
{ value: 'works_count', display_name: 'Anzahl Publikationen' },
|
||||
{ value: 'citations_count', display_name: 'Anzahl Zitationen' },
|
||||
];
|
||||
sortingDirectionOptions: SelectorOption[] = [
|
||||
{ value: 'asc', display_name: 'Aufsteigend' },
|
||||
{ value: 'desc', display_name: 'Absteigend' },
|
||||
];
|
||||
|
||||
extractInstitutionId(institution: Institution): string {
|
||||
return institution.id?.split('/').pop() ?? '';
|
||||
}
|
||||
|
||||
handleSortFieldChange(event: Event): void {
|
||||
const selectElement = event.target as HTMLSelectElement;
|
||||
const sortField = selectElement.value;
|
||||
this.router.navigate([], {
|
||||
queryParams: { sort_by: sortField },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
handleSortOrderChange(event: Event): void {
|
||||
const selectElement = event.target as HTMLSelectElement;
|
||||
const sortOrder = selectElement.value;
|
||||
this.router.navigate([], {
|
||||
queryParams: { sorting_order: sortOrder },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
getDisplayName(institution: Institution): string {
|
||||
const primary = institution.display_name?.trim();
|
||||
if (primary && primary.length > 0) return primary;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<article class="person-card">
|
||||
<a [routerLink]="['/person', person.id, 'overview']" class="card-header">
|
||||
<a [routerLink]="['/person', person().id, 'overview']" class="card-header">
|
||||
<!-- Initials Avatar or Profile Image fallback -->
|
||||
<div [skText]="loading" class="avatar">
|
||||
{{ getInitials(person.display_name) }}
|
||||
<div [skText]="loading()" class="avatar">
|
||||
{{ initials() }}
|
||||
</div>
|
||||
<div class="header-main">
|
||||
<div class="bookmark">
|
||||
@@ -11,41 +11,58 @@
|
||||
(click)="
|
||||
toggleBookmark(); $event.stopPropagation(); $event.preventDefault()
|
||||
"
|
||||
[class.bookmarked]="isBookmarked"
|
||||
[class.bookmarked]="isBookmarked()"
|
||||
aria-label="Bookmark person">
|
||||
<mat-icon>{{
|
||||
isBookmarked ? 'bookmark' : 'bookmark_border'
|
||||
isBookmarked() ? 'bookmark' : 'bookmark_border'
|
||||
}}</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
<h2
|
||||
[skText]="loading"
|
||||
[skText]="loading()"
|
||||
class="person-name"
|
||||
[title]="person.display_name ?? ''">
|
||||
{{ person.display_name ?? '' }}
|
||||
[title]="person().display_name ?? ''">
|
||||
{{ person().display_name ?? '' }}
|
||||
</h2>
|
||||
<p [skText]="loading" class="person-id">
|
||||
{{ getDistinguishingId(person) }}
|
||||
<p [skText]="loading()" class="person-id">
|
||||
{{ distinguishingId() }}
|
||||
</p>
|
||||
<p [skText]="loading" class="stats">
|
||||
{{ getStatsString() }}
|
||||
<p [skText]="loading()" class="stats">
|
||||
{{ statsString() }}
|
||||
</p>
|
||||
<p [skText]="loading" class="stats">
|
||||
{{ getHIndexString() }}
|
||||
<p [skText]="loading()" class="stats">
|
||||
{{ hIndexString() }}
|
||||
</p>
|
||||
@if (!loading()) {
|
||||
@if (careerStage(); as careerStage) {
|
||||
<div [skText]="loading()" class="career-stage-line">
|
||||
<span class="career-stage-label">Career Stage:</span>
|
||||
<span
|
||||
class="career-stage-chip"
|
||||
[matTooltip]="getCareerStageTooltip(careerStage)"
|
||||
matTooltipPosition="right"
|
||||
matTooltipClass="career-stage-tooltip"
|
||||
[matTooltipShowDelay]="250">
|
||||
{{ careerStage }}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</a>
|
||||
|
||||
<div class="card-body">
|
||||
@if (institution(person); as inst) {
|
||||
@if (institution(); as inst) {
|
||||
<div class="institution-row" style="margin-bottom: 8px">
|
||||
<span
|
||||
<button
|
||||
type="button"
|
||||
class="institution-tag"
|
||||
[matTooltip]="inst.display_name || ''"
|
||||
matTooltipPosition="above"
|
||||
(click)="
|
||||
institutionClick.emit(inst.display_name || '');
|
||||
$event.stopPropagation()
|
||||
"
|
||||
[title]="inst.display_name || ''">
|
||||
">
|
||||
<mat-icon
|
||||
style="
|
||||
font-size: 12px;
|
||||
@@ -57,12 +74,12 @@
|
||||
>apartment</mat-icon
|
||||
>
|
||||
<span
|
||||
[skText]="loading"
|
||||
[skText]="loading()"
|
||||
class="institution-name"
|
||||
style="vertical-align: middle"
|
||||
>{{ inst.display_name ?? '' }}</span
|
||||
>
|
||||
@if (inst.country_code && !loading) {
|
||||
@if (inst.country_code && !loading()) {
|
||||
<img
|
||||
alt=""
|
||||
class="flag-img"
|
||||
@@ -75,38 +92,41 @@
|
||||
>{{ inst.country_code.toUpperCase() }}</span
|
||||
>
|
||||
}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="topic-row">
|
||||
@for (topic of topics(person); track topic.id) {
|
||||
<span
|
||||
[skText]="loading"
|
||||
@for (topic of topics(); track topic.id) {
|
||||
<button
|
||||
type="button"
|
||||
[skText]="loading()"
|
||||
class="topic-tag"
|
||||
[class.active]="selectedTopics().has(topic.display_name || '')"
|
||||
[matTooltip]="getTopicTooltip(topic)"
|
||||
matTooltipPosition="above"
|
||||
(click)="
|
||||
topicClick.emit(topic.display_name || ''); $event.stopPropagation()
|
||||
"
|
||||
[title]="getTopicTooltip(topic)"
|
||||
>{{ topic.display_name }}</span
|
||||
>
|
||||
">
|
||||
{{ topic.display_name }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card-footer">
|
||||
<div class="action-buttons">
|
||||
<a [routerLink]="['/person', person.id, 'overview']" class="action-btn">
|
||||
<a [routerLink]="['/person', person().id, 'overview']" class="action-btn">
|
||||
<mat-icon>visibility</mat-icon>
|
||||
<span>Übersicht</span>
|
||||
</a>
|
||||
<a
|
||||
[routerLink]="['/person', person.id, 'publications']"
|
||||
[routerLink]="['/person', person().id, 'publications']"
|
||||
class="action-btn">
|
||||
<mat-icon>menu_book</mat-icon>
|
||||
<span>Publikationen</span>
|
||||
</a>
|
||||
<a [routerLink]="['/person', person.id, 'network']" class="action-btn">
|
||||
<a [routerLink]="['/person', person().id, 'network']" class="action-btn">
|
||||
<mat-icon>share</mat-icon>
|
||||
<span>Netzwerk</span>
|
||||
</a>
|
||||
|
||||
@@ -140,6 +140,9 @@
|
||||
transition: all 0.2s ease;
|
||||
max-width: 100%;
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
line-height: normal;
|
||||
font-family: inherit;
|
||||
|
||||
.institution-name {
|
||||
overflow: hidden;
|
||||
@@ -159,10 +162,15 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
background: var(--sg-primary);
|
||||
color: #fff;
|
||||
border-color: var(--sg-primary);
|
||||
outline: none;
|
||||
box-shadow:
|
||||
0 0 0 2px var(--sg-background),
|
||||
0 0 0 4px var(--sg-primary);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,6 +201,39 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.career-stage-line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-top: 6px;
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 10px;
|
||||
min-height: 18px;
|
||||
}
|
||||
|
||||
.career-stage-label {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.career-stage-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
padding: 2px 8px;
|
||||
border: 1px solid var(--sg-border);
|
||||
border-radius: 999px;
|
||||
background: var(--sg-surface-muted);
|
||||
color: var(--sg-primary);
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
line-height: 1.2;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.card-body {
|
||||
padding: 16px;
|
||||
flex-grow: 1;
|
||||
@@ -223,11 +264,36 @@
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
line-height: normal;
|
||||
font-family: inherit;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
||||
&:hover {
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
background: var(--sg-primary-soft);
|
||||
border-color: var(--sg-primary);
|
||||
color: var(--sg-primary);
|
||||
outline: none;
|
||||
box-shadow:
|
||||
0 0 0 2px var(--sg-background),
|
||||
0 0 0 4px var(--sg-primary);
|
||||
}
|
||||
|
||||
&.active {
|
||||
background: var(--sg-primary-soft);
|
||||
border-color: var(--sg-primary);
|
||||
color: var(--sg-primary);
|
||||
font-weight: 700;
|
||||
box-shadow: 0 0 0 1.5px var(--sg-primary);
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
box-shadow:
|
||||
0 0 0 2px var(--sg-background),
|
||||
0 0 0 4px var(--sg-primary);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,46 +1,51 @@
|
||||
import { Component, Input, Output, EventEmitter } from '@angular/core';
|
||||
import { Component, input, computed, output } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { CustomAuthor, DehydratedInstitution, WorkTopic } from '../../api';
|
||||
import { SkTextDirective } from '../../custom-directives/sk-text.directive';
|
||||
|
||||
@Component({
|
||||
selector: 'app-person-card',
|
||||
standalone: true,
|
||||
imports: [CommonModule, RouterLink, MatIconModule, SkTextDirective],
|
||||
imports: [
|
||||
CommonModule,
|
||||
RouterLink,
|
||||
MatIconModule,
|
||||
SkTextDirective,
|
||||
MatTooltipModule,
|
||||
],
|
||||
templateUrl: './person-card.component.html',
|
||||
styleUrl: './person-card.component.scss',
|
||||
})
|
||||
export class PersonCardComponent {
|
||||
@Input({ required: true }) person!: CustomAuthor;
|
||||
@Input() isBookmarked = false;
|
||||
@Input() loading = false;
|
||||
@Output() bookmarkToggle = new EventEmitter<CustomAuthor>();
|
||||
@Output() topicClick = new EventEmitter<string>();
|
||||
@Output() institutionClick = new EventEmitter<string>();
|
||||
person = input.required<CustomAuthor>();
|
||||
isBookmarked = input<boolean>(false);
|
||||
loading = input<boolean>(false);
|
||||
selectedTopics = input<Set<string>>(new Set<string>());
|
||||
|
||||
getInitials(name: string | null | undefined): string {
|
||||
bookmarkToggle = output<CustomAuthor>();
|
||||
topicClick = output<string>();
|
||||
institutionClick = output<string>();
|
||||
|
||||
initials = computed<string>(() => {
|
||||
const name = this.person().display_name;
|
||||
if (!name) return 'U';
|
||||
const cleanName = name.replace(/Prof\.|Dr\.|M\.Sc\./g, '').trim();
|
||||
const parts = cleanName.split(' ');
|
||||
const first = parts[0]?.[0] || '';
|
||||
const last = parts[parts.length - 1]?.[0] || '';
|
||||
return (first + last).toUpperCase();
|
||||
}
|
||||
});
|
||||
|
||||
getRatingClass(rating: string | null | undefined): string {
|
||||
const r = (rating || '').toLowerCase();
|
||||
if (r === 'sehr geeignet') return 'very-suitable';
|
||||
if (r === 'geeignet') return 'suitable';
|
||||
return 'possible';
|
||||
}
|
||||
|
||||
institution(person: CustomAuthor): DehydratedInstitution | undefined {
|
||||
if (person.last_known_institutions?.[0]) {
|
||||
return person.last_known_institutions[0];
|
||||
institution = computed<DehydratedInstitution | undefined>(() => {
|
||||
const p = this.person();
|
||||
if (p.last_known_institutions?.[0]) {
|
||||
return p.last_known_institutions[0];
|
||||
}
|
||||
|
||||
const affiliations = person.affiliations ?? [];
|
||||
const affiliations = p.affiliations ?? [];
|
||||
let newestInstitution: DehydratedInstitution | undefined =
|
||||
affiliations[0]?.institution ?? undefined;
|
||||
let newestYear = -1;
|
||||
@@ -55,12 +60,61 @@ export class PersonCardComponent {
|
||||
}
|
||||
|
||||
return newestInstitution;
|
||||
}
|
||||
});
|
||||
|
||||
topics(person: CustomAuthor): WorkTopic[] {
|
||||
return (person.topics ?? [])
|
||||
topics = computed<WorkTopic[]>(() => {
|
||||
return (this.person().topics ?? [])
|
||||
.filter((t): t is WorkTopic => !!t.display_name)
|
||||
.slice(0, 3);
|
||||
});
|
||||
|
||||
distinguishingId = computed<string>(() => {
|
||||
const p = this.person();
|
||||
if (p.orcid) {
|
||||
return p.orcid.replace('https://orcid.org/', '');
|
||||
}
|
||||
return '';
|
||||
});
|
||||
|
||||
statsString = computed<string>(() => {
|
||||
const works = this.person().works_count;
|
||||
const citations = this.person().cited_by_count;
|
||||
const hasWorks = works !== undefined && works !== null;
|
||||
const hasCitations = citations !== undefined && citations !== null;
|
||||
|
||||
if (hasWorks && hasCitations) {
|
||||
return `Publikationen: ${works} · Zitationen: ${citations}`;
|
||||
} else if (hasWorks) {
|
||||
return `Publikationen: ${works}`;
|
||||
} else if (hasCitations) {
|
||||
return `Zitationen: ${citations}`;
|
||||
}
|
||||
return '';
|
||||
});
|
||||
|
||||
hIndexString = computed<string>(() => {
|
||||
const hIndex = this.person().summary_stats?.h_index;
|
||||
if (hIndex !== undefined && hIndex !== null) {
|
||||
return `h_index: ${hIndex}`;
|
||||
}
|
||||
return '';
|
||||
});
|
||||
|
||||
careerStage = computed<string | null>(() => {
|
||||
const stage = this.person().career_metrics?.career_stage;
|
||||
|
||||
if (!stage || stage === 'unknown') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return stage;
|
||||
});
|
||||
|
||||
getRatingClass(rating: string | null | undefined): string {
|
||||
const r = (rating || '').toLowerCase();
|
||||
if (r === 'sehr geeignet') return 'very-suitable';
|
||||
if (r === 'geeignet') return 'suitable';
|
||||
return 'possible';
|
||||
}
|
||||
|
||||
getTopicTooltip(topic: WorkTopic): string {
|
||||
@@ -76,39 +130,24 @@ export class PersonCardComponent {
|
||||
return path;
|
||||
}
|
||||
|
||||
getDistinguishingId(person: CustomAuthor): string {
|
||||
if (!person) return '';
|
||||
if (person.orcid) {
|
||||
return person.orcid.replace('https://orcid.org/', '');
|
||||
}
|
||||
return '';
|
||||
}
|
||||
getCareerStageTooltip(careerStage: string): string {
|
||||
const activeYears = this.person().career_metrics?.active_years ?? '-';
|
||||
|
||||
getStatsString(): string {
|
||||
const works = this.person.works_count;
|
||||
const citations = this.person.cited_by_count;
|
||||
const hasWorks = works !== undefined && works !== null;
|
||||
const hasCitations = citations !== undefined && citations !== null;
|
||||
|
||||
if (hasWorks && hasCitations) {
|
||||
return `Publikationen: ${works} · Zitationen: ${citations}`;
|
||||
} else if (hasWorks) {
|
||||
return `Publikationen: ${works}`;
|
||||
} else if (hasCitations) {
|
||||
return `Zitationen: ${citations}`;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
getHIndexString(): string {
|
||||
const hIndex = this.person.summary_stats?.h_index;
|
||||
if (hIndex !== undefined && hIndex !== null) {
|
||||
return `h_index: ${hIndex}`;
|
||||
}
|
||||
return '';
|
||||
return [
|
||||
`Aktuell: ${careerStage.replace(' Researcher', '')}`,
|
||||
`Aktive Publikationsjahre: ${activeYears}`,
|
||||
'',
|
||||
'Einteilung:',
|
||||
'Early: 1-4 aktive Publikationsjahre',
|
||||
'Emerging: 5-9 aktive Publikationsjahre',
|
||||
'Established: 10-14 aktive Publikationsjahre',
|
||||
'Senior: ab 15 aktiven Publikationsjahren',
|
||||
'',
|
||||
'Diese Einschätzung basiert ausschließlich auf OpenAlex-Publikationsdaten und ist kein offizieller akademischer Status.',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
toggleBookmark(): void {
|
||||
this.bookmarkToggle.emit(this.person);
|
||||
this.bookmarkToggle.emit(this.person());
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -131,8 +131,8 @@ $text-muted: #64718f;
|
||||
right: 12px;
|
||||
z-index: 2;
|
||||
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
width: 51px;
|
||||
height: 51px;
|
||||
padding: 0;
|
||||
|
||||
background: transparent;
|
||||
|
||||
@@ -8,22 +8,78 @@
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
@if (visibleLegendGroups().length > 0) {
|
||||
<div class="interest-legend" aria-label="Aktuell sichtbare Themenbereiche">
|
||||
<mat-icon
|
||||
class="interest-legend-info"
|
||||
matTooltip="Fachgebiete geben die Farbfamilie vor, Themenbereiche bestimmen die konkrete Farbvariante."
|
||||
matTooltipPosition="above"
|
||||
aria-label="Informationen zur Farblegende">
|
||||
info_outline
|
||||
</mat-icon>
|
||||
|
||||
<div class="interest-legend-content">
|
||||
@for (group of visibleLegendGroups(); track group.id) {
|
||||
<span class="interest-legend-group">
|
||||
<span
|
||||
class="interest-legend-field"
|
||||
[matTooltip]="group.tooltip"
|
||||
[matTooltipDisabled]="!group.tooltip"
|
||||
matTooltipClass="topic-chip-tooltip"
|
||||
matTooltipPosition="above"
|
||||
>{{ group.name }}</span
|
||||
>
|
||||
<span class="interest-legend-items">
|
||||
@for (item of group.items; track item.id) {
|
||||
<span
|
||||
class="interest-legend-item"
|
||||
[matTooltip]="item.tooltip"
|
||||
[matTooltipDisabled]="!item.tooltip"
|
||||
matTooltipClass="topic-chip-tooltip"
|
||||
matTooltipPosition="above">
|
||||
<span
|
||||
class="interest-legend-dot"
|
||||
[style.background]="item.color"
|
||||
aria-hidden="true"></span>
|
||||
<span>{{ item.name }}</span>
|
||||
</span>
|
||||
}
|
||||
</span>
|
||||
</span>
|
||||
}
|
||||
|
||||
@if (hasHiddenLegendGroups()) {
|
||||
<button
|
||||
type="button"
|
||||
class="interest-legend-more"
|
||||
[attr.aria-expanded]="legendExpanded()"
|
||||
(click)="toggleLegend()">
|
||||
@if (legendExpanded()) {
|
||||
Weniger anzeigen
|
||||
} @else {
|
||||
+{{ hiddenLegendItemCount() }} weitere
|
||||
}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<div class="interest-tags">
|
||||
@if (tags().length > 0) {
|
||||
@for (tag of tags(); track tag.label; let i = $index) {
|
||||
<button
|
||||
type="button"
|
||||
class="topic-chip"
|
||||
[ngClass]="getColorClass(i)"
|
||||
[matTooltip]="tag.description"
|
||||
@for (tag of tags(); track tag.label) {
|
||||
<app-topic-chip
|
||||
[label]="tag.label"
|
||||
[count]="tag.count"
|
||||
[description]="tag.description"
|
||||
[subfieldName]="tag.subfieldName"
|
||||
[fieldName]="tag.fieldName"
|
||||
[domainName]="tag.domainName"
|
||||
[color]="tag.color"
|
||||
[disabled]="!tag.id"
|
||||
(click)="onTagClick(tag)">
|
||||
<span class="topic-name">{{ tag.label }}</span>
|
||||
<span class="topic-count">
|
||||
{{ tag.count }}
|
||||
<mat-icon class="count-icon">article</mat-icon>
|
||||
</span>
|
||||
</button>
|
||||
countIcon="article"
|
||||
descriptionTooltipTarget="button"
|
||||
(chipClick)="onTagClick(tag)">
|
||||
</app-topic-chip>
|
||||
}
|
||||
} @else {
|
||||
<span class="interest-empty">Keine Themen gefunden</span>
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 10px;
|
||||
margin: 0 0 18px;
|
||||
flex-wrap: wrap;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.interest-card h3 {
|
||||
@@ -29,98 +30,6 @@
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.topic-chip {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
justify-items: center;
|
||||
column-gap: 8px;
|
||||
box-sizing: border-box;
|
||||
min-height: 34px;
|
||||
padding: 6px 12px;
|
||||
border: 1px solid var(--topic-border);
|
||||
border-radius: 8px;
|
||||
background: var(--topic-bg);
|
||||
color: var(--topic-color);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
line-height: 1.25;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
transform 0.15s ease,
|
||||
box-shadow 0.15s ease;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 4px 10px rgba(15, 23, 42, 0.12);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
|
||||
.topic-name {
|
||||
min-width: 0;
|
||||
text-align: center;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.topic-count {
|
||||
display: inline-flex;
|
||||
flex: 0 0 auto;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 2px;
|
||||
min-width: 18px;
|
||||
height: 18px;
|
||||
padding: 0 5px;
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, 0.78);
|
||||
color: inherit;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.topic-count .count-icon {
|
||||
width: 13px;
|
||||
height: 13px;
|
||||
font-size: 13px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.purple {
|
||||
--topic-border: #d8cafe;
|
||||
--topic-bg: #f6f0ff;
|
||||
--topic-color: #7255d9;
|
||||
}
|
||||
|
||||
.blue {
|
||||
--topic-border: #bdd4ff;
|
||||
--topic-bg: #f0f6ff;
|
||||
--topic-color: #0b63ce;
|
||||
}
|
||||
|
||||
.green {
|
||||
--topic-border: #bdebcf;
|
||||
--topic-bg: #effaf3;
|
||||
--topic-color: #24834f;
|
||||
}
|
||||
|
||||
.orange {
|
||||
--topic-border: #ffd796;
|
||||
--topic-bg: #fff7e8;
|
||||
--topic-color: #c67500;
|
||||
}
|
||||
|
||||
.pink {
|
||||
--topic-border: #ffc7d7;
|
||||
--topic-bg: #fff1f5;
|
||||
--topic-color: #d12f61;
|
||||
}
|
||||
|
||||
.interest-footnote {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -136,6 +45,127 @@
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.interest-legend {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 9px;
|
||||
width: fit-content;
|
||||
max-width: 100%;
|
||||
margin: 0 0 16px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid #dbe5f6;
|
||||
border-radius: 8px;
|
||||
background: #ffffff;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.interest-legend-content,
|
||||
.interest-legend-group,
|
||||
.interest-legend-items,
|
||||
.interest-legend-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.interest-legend-info {
|
||||
flex: 0 0 auto;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
color: #7d8aa8;
|
||||
font-size: 14px;
|
||||
line-height: 14px;
|
||||
}
|
||||
|
||||
.interest-legend-content {
|
||||
gap: 7px;
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.interest-legend-group {
|
||||
gap: 6px;
|
||||
flex: 0 1 auto;
|
||||
flex-wrap: wrap;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
min-height: 24px;
|
||||
padding: 3px 7px;
|
||||
border: 1px solid #dbe5f6;
|
||||
border-radius: 999px;
|
||||
background: #fbfdff;
|
||||
}
|
||||
|
||||
.interest-legend-field {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
color: #07163d;
|
||||
font-size: 10px;
|
||||
font-weight: 800;
|
||||
line-height: 1.2;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.interest-legend-items {
|
||||
flex: 0 1 auto;
|
||||
gap: 4px 7px;
|
||||
min-width: 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.interest-legend-item {
|
||||
gap: 4px;
|
||||
flex: 0 0 auto;
|
||||
min-width: 0;
|
||||
color: #53617e;
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
line-height: 1.2;
|
||||
white-space: nowrap;
|
||||
cursor: help;
|
||||
|
||||
span:last-child {
|
||||
overflow: visible;
|
||||
text-overflow: clip;
|
||||
}
|
||||
}
|
||||
|
||||
.interest-legend-dot {
|
||||
flex: 0 0 auto;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.85);
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.2);
|
||||
}
|
||||
|
||||
.interest-legend-more {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex: 0 0 auto;
|
||||
min-height: 24px;
|
||||
padding: 0 2px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--accent, #0057ff);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--accent, #0057ff);
|
||||
outline-offset: 2px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.interest-tags .interest-empty {
|
||||
padding: 9px 16px;
|
||||
border: 1px solid #e2e8f0;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
|
||||
import { PersonInterestingComponent } from './person-interesting.component';
|
||||
|
||||
@@ -9,6 +10,7 @@ describe('PersonInterestingComponent', () => {
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [PersonInterestingComponent],
|
||||
providers: [provideRouter([])],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(PersonInterestingComponent);
|
||||
|
||||
@@ -1,28 +1,77 @@
|
||||
import { Component, input, computed, output } from '@angular/core';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import {
|
||||
Component,
|
||||
DestroyRef,
|
||||
OnInit,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
output,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
|
||||
import { TopicCount } from '../../api';
|
||||
import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component';
|
||||
import { topicHierarchyColor } from '../../shared/utils/topic-colors';
|
||||
|
||||
interface InterestTag {
|
||||
id: string;
|
||||
label: string;
|
||||
count: number;
|
||||
description: string;
|
||||
color: string;
|
||||
subfieldId: string;
|
||||
subfieldName: string;
|
||||
subfieldDescription: string;
|
||||
fieldId: string;
|
||||
fieldName: string;
|
||||
fieldDescription: string;
|
||||
domainId: string;
|
||||
domainName: string;
|
||||
domainDescription: string;
|
||||
}
|
||||
|
||||
interface InterestLegendGroup {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
domainName: string;
|
||||
domainDescription: string;
|
||||
tooltip: string;
|
||||
items: InterestLegendItem[];
|
||||
}
|
||||
|
||||
interface InterestLegendItem {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
color: string;
|
||||
tooltip: string;
|
||||
}
|
||||
|
||||
const MAX_TAGS = 5;
|
||||
const colors = ['purple', 'blue', 'green', 'orange', 'pink'];
|
||||
const MAX_LEGEND_GROUPS = 3;
|
||||
|
||||
@Component({
|
||||
selector: 'app-person-interesting',
|
||||
imports: [CommonModule, MatTooltipModule, MatIconModule],
|
||||
imports: [CommonModule, MatIconModule, MatTooltipModule, TopicChipComponent],
|
||||
templateUrl: './person-interesting.component.html',
|
||||
styleUrl: './person-interesting.component.scss',
|
||||
})
|
||||
export class PersonInterestingComponent {
|
||||
export class PersonInterestingComponent implements OnInit {
|
||||
private static readonly legendExpandedQueryParam =
|
||||
'interesting_legend_expanded';
|
||||
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
private readonly router = inject(Router);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
readonly topics = input<TopicCount[] | null>(null);
|
||||
readonly legendExpanded = signal(false);
|
||||
|
||||
readonly tagClick = output<{ id: string; name: string }>();
|
||||
|
||||
@@ -39,18 +88,192 @@ export class PersonInterestingComponent {
|
||||
label,
|
||||
count: topic.count ?? 0,
|
||||
description: (topic.description ?? '').trim(),
|
||||
color: topicHierarchyColor(topic),
|
||||
subfieldId: topic.subfield_id ?? '',
|
||||
subfieldName: (topic.subfield_name ?? '').trim(),
|
||||
subfieldDescription: (topic.subfield_description ?? '').trim(),
|
||||
fieldId: topic.field_id ?? '',
|
||||
fieldName: (topic.field_name ?? '').trim(),
|
||||
fieldDescription: (topic.field_description ?? '').trim(),
|
||||
domainId: topic.domain_id ?? '',
|
||||
domainName: (topic.domain_name ?? '').trim(),
|
||||
domainDescription: (topic.domain_description ?? '').trim(),
|
||||
});
|
||||
}
|
||||
|
||||
return tags.sort((a, b) => b.count - a.count).slice(0, MAX_TAGS);
|
||||
});
|
||||
|
||||
getColorClass(index: number): string {
|
||||
return colors[index % colors.length];
|
||||
readonly legendGroups = computed<InterestLegendGroup[]>(() => {
|
||||
const groups = new Map<string, InterestLegendGroup>();
|
||||
|
||||
for (const tag of this.tags()) {
|
||||
if (!tag.subfieldName) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fieldName = tag.fieldName || 'Ohne Field';
|
||||
const fieldId = tag.fieldId || fieldName.toLowerCase();
|
||||
const subfieldId = tag.subfieldId || tag.subfieldName.toLowerCase();
|
||||
|
||||
if (!groups.has(fieldId)) {
|
||||
groups.set(fieldId, {
|
||||
id: fieldId,
|
||||
name: fieldName,
|
||||
description: tag.fieldDescription,
|
||||
domainName: tag.domainName,
|
||||
domainDescription: tag.domainDescription,
|
||||
tooltip: this.buildLegendTooltip([
|
||||
{
|
||||
label: 'Fachgebiet',
|
||||
value: fieldName,
|
||||
description: tag.fieldDescription,
|
||||
},
|
||||
{
|
||||
label: 'Wissenschaftsbereich',
|
||||
value: tag.domainName,
|
||||
description: tag.domainDescription,
|
||||
},
|
||||
]),
|
||||
items: [],
|
||||
});
|
||||
}
|
||||
|
||||
const group = groups.get(fieldId);
|
||||
|
||||
if (!group || group.items.some((item) => item.id === subfieldId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
group.items.push({
|
||||
id: subfieldId,
|
||||
name: tag.subfieldName,
|
||||
description: tag.subfieldDescription,
|
||||
color: tag.color,
|
||||
tooltip: this.buildLegendTooltip([
|
||||
{
|
||||
label: 'Themenbereich',
|
||||
value: tag.subfieldName,
|
||||
description: tag.subfieldDescription,
|
||||
},
|
||||
{
|
||||
label: 'Fachgebiet',
|
||||
value: fieldName,
|
||||
description: tag.fieldDescription,
|
||||
},
|
||||
{
|
||||
label: 'Wissenschaftsbereich',
|
||||
value: tag.domainName,
|
||||
description: tag.domainDescription,
|
||||
},
|
||||
]),
|
||||
});
|
||||
}
|
||||
|
||||
return [...groups.values()]
|
||||
.map((group) => ({
|
||||
...group,
|
||||
items: group.items.sort((left, right) =>
|
||||
left.name.localeCompare(right.name),
|
||||
),
|
||||
}))
|
||||
.sort((left, right) => left.name.localeCompare(right.name));
|
||||
});
|
||||
|
||||
readonly visibleLegendGroups = computed<InterestLegendGroup[]>(() => {
|
||||
const groups = this.legendGroups();
|
||||
return this.legendExpanded() ? groups : groups.slice(0, MAX_LEGEND_GROUPS);
|
||||
});
|
||||
|
||||
readonly hasHiddenLegendGroups = computed<boolean>(
|
||||
() => this.legendGroups().length > MAX_LEGEND_GROUPS,
|
||||
);
|
||||
|
||||
readonly hiddenLegendItemCount = computed<number>(() =>
|
||||
this.legendGroups()
|
||||
.slice(MAX_LEGEND_GROUPS)
|
||||
.reduce((count, group) => count + group.items.length, 0),
|
||||
);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.route.queryParamMap
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe((queryParams) => {
|
||||
this.legendExpanded.set(
|
||||
this.parseBooleanQueryParam(
|
||||
queryParams.get(
|
||||
PersonInterestingComponent.legendExpandedQueryParam,
|
||||
),
|
||||
false,
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
onTagClick(tag: InterestTag): void {
|
||||
if (!tag.id) return;
|
||||
this.tagClick.emit({ id: tag.id, name: tag.label });
|
||||
}
|
||||
|
||||
toggleLegend(): void {
|
||||
const expanded = !this.legendExpanded();
|
||||
this.legendExpanded.set(expanded);
|
||||
|
||||
void this.router.navigate([], {
|
||||
relativeTo: this.route,
|
||||
queryParams: {
|
||||
[PersonInterestingComponent.legendExpandedQueryParam]: expanded
|
||||
? 'true'
|
||||
: null,
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true,
|
||||
});
|
||||
}
|
||||
|
||||
private parseBooleanQueryParam(
|
||||
value: string | null,
|
||||
fallback: boolean,
|
||||
): boolean {
|
||||
if (value === null) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
if (value === 'true' || value === '1') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (value === 'false' || value === '0') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
private buildLegendTooltip(
|
||||
entries: Array<{ label: string; value: string; description: string }>,
|
||||
): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.value && !entry.description) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (lines.length > 0) {
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (entry.value) {
|
||||
lines.push(`${entry.label}: ${entry.value}`);
|
||||
}
|
||||
|
||||
if (entry.description) {
|
||||
lines.push('');
|
||||
lines.push(`Beschreibung: ${entry.description}`);
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,8 @@
|
||||
<button
|
||||
mat-icon-button
|
||||
(click)="clearSearch()"
|
||||
matTooltip="Suche zurücksetzen">
|
||||
matTooltip="Suche zurücksetzen"
|
||||
aria-label="Suche zurücksetzen">
|
||||
<mat-icon>close</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
@@ -42,7 +43,10 @@
|
||||
</button>
|
||||
</span>
|
||||
}
|
||||
<button class="clear-all-btn" (click)="clearAllFilters()">
|
||||
<button
|
||||
class="clear-all-btn"
|
||||
(click)="clearAllFilters()"
|
||||
aria-label="Alle Filter zurücksetzen">
|
||||
Filter zurücksetzen
|
||||
</button>
|
||||
</div>
|
||||
@@ -56,14 +60,18 @@
|
||||
<div class="sort-selector">
|
||||
<span class="sort-label">Sortierung:</span>
|
||||
<div class="select-wrapper">
|
||||
<select [formControl]="sortValueControl">
|
||||
<select
|
||||
[formControl]="sortValueControl"
|
||||
aria-label="Sortierkriterium">
|
||||
<option [ngValue]="null">Beste Treffer (Relevanz)</option>
|
||||
<option value="works_count">Publikationen</option>
|
||||
<option value="cited_by_count">Zitierungen</option>
|
||||
<option value="summary_stats.h_index">h_index</option>
|
||||
</select>
|
||||
|
||||
<select [formControl]="sortOrderControl">
|
||||
<select
|
||||
[formControl]="sortOrderControl"
|
||||
aria-label="Sortierreihenfolge">
|
||||
<option value="desc">Absteigend</option>
|
||||
<option value="asc">Aufsteigend</option>
|
||||
</select>
|
||||
@@ -87,6 +95,7 @@
|
||||
[loading]="loading"
|
||||
[person]="person"
|
||||
[isBookmarked]="isBookmarked(person)"
|
||||
[selectedTopics]="selectedTopics()"
|
||||
(bookmarkToggle)="toggleBookmark($event)"
|
||||
(topicClick)="onCardTopicClick($event)"
|
||||
(institutionClick)="onCardInstitutionClick($event)">
|
||||
@@ -132,19 +141,23 @@
|
||||
<input
|
||||
type="text"
|
||||
[formControl]="topicSearchControl"
|
||||
aria-label="Thema suchen"
|
||||
placeholder="Thema suchen..." />
|
||||
@if (topicSearchControl.value) {
|
||||
<button
|
||||
class="clear-topic-search"
|
||||
(click)="topicSearchControl.setValue('')">
|
||||
(click)="topicSearchControl.setValue('')"
|
||||
aria-label="Themensuche zurücksetzen">
|
||||
<mat-icon>close</mat-icon>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
|
||||
<app-topic-hierarchy
|
||||
[selectedTopics]="selectedTopics"
|
||||
[selectedTopics]="selectedTopics()"
|
||||
[searchQuery]="topicSearchControl.value"
|
||||
[searchType]="topicSearchType()"
|
||||
(searchTypeChange)="onTopicSearchTypeChange($event)"
|
||||
(selectionChange)="onTopicSelectionChange($event)">
|
||||
</app-topic-hierarchy>
|
||||
</div>
|
||||
@@ -158,6 +171,7 @@
|
||||
type="text"
|
||||
[formControl]="institutionControl"
|
||||
[matAutocomplete]="auto"
|
||||
aria-label="Institution suchen"
|
||||
placeholder="Institution suchen..."
|
||||
(keyup.enter)="applySidebarFilters()" />
|
||||
<mat-autocomplete
|
||||
@@ -183,7 +197,8 @@
|
||||
@if (institutionControl.value) {
|
||||
<button
|
||||
class="clear-topic-search"
|
||||
(click)="clearInstitutionFilter()">
|
||||
(click)="clearInstitutionFilter()"
|
||||
aria-label="Institution zurücksetzen">
|
||||
<mat-icon>close</mat-icon>
|
||||
</button>
|
||||
}
|
||||
@@ -198,7 +213,8 @@
|
||||
">
|
||||
<mat-checkbox
|
||||
[formControl]="yearFilterEnabledControl"
|
||||
(change)="applySidebarFilters()">
|
||||
(change)="applySidebarFilters()"
|
||||
aria-label="Zusammenarbeit nach Jahr filtern">
|
||||
<span
|
||||
style="font-size: 12px; font-weight: 500; color: var(--sg-text)"
|
||||
>Zusammenarbeit nach Jahr filtern</span
|
||||
@@ -217,7 +233,8 @@
|
||||
<mat-radio-group
|
||||
[formControl]="filterModeControl"
|
||||
(change)="applySidebarFilters()"
|
||||
style="display: flex; gap: 16px">
|
||||
style="display: flex; gap: 16px"
|
||||
aria-label="Modus für Jahresfilter">
|
||||
<mat-radio-button value="in"
|
||||
><span style="font-size: 12px; color: var(--sg-text)"
|
||||
>Genau in</span
|
||||
@@ -240,6 +257,7 @@
|
||||
[formControl]="filterYearControl"
|
||||
(change)="applySidebarFilters()"
|
||||
(keyup.enter)="applySidebarFilters()"
|
||||
aria-label="Jahr"
|
||||
placeholder="Z. B. 2025" />
|
||||
@if (filterYearControl.hasError('min')) {
|
||||
<mat-error>Jahr muss ≥ 1900 sein</mat-error>
|
||||
@@ -255,7 +273,10 @@
|
||||
|
||||
<!-- Sidebar Footer Action showing matches count -->
|
||||
<div class="sidebar-footer">
|
||||
<button class="submit-btn" (click)="applySidebarFilters()">
|
||||
<button
|
||||
class="submit-btn"
|
||||
(click)="applySidebarFilters()"
|
||||
aria-label="Gefundene Personen anzeigen">
|
||||
<span [skText]="loading"
|
||||
>{{ total | number: '1.0-0' }} Personen anzeigen</span
|
||||
>
|
||||
|
||||
@@ -13,18 +13,64 @@
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.results-column {
|
||||
// Shared flex layouts
|
||||
.page-header,
|
||||
.sidebar-header,
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.page-header,
|
||||
.toolbar {
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.sidebar-header,
|
||||
.toolbar {
|
||||
border-bottom: 1px solid var(--sg-border);
|
||||
padding-bottom: 12px;
|
||||
}
|
||||
|
||||
.selection-summary,
|
||||
.active-filters-row,
|
||||
.chips-container,
|
||||
.sort-selector,
|
||||
.topic-search-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.filter-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
// Shared column & sidebar column layouts
|
||||
.results-column,
|
||||
.empty-state,
|
||||
.filters-sidebar,
|
||||
.filter-section {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
// Shared containers styling
|
||||
.selection-summary,
|
||||
.active-filters-row,
|
||||
.filters-sidebar {
|
||||
background: var(--sg-surface);
|
||||
border: 1px solid var(--sg-border);
|
||||
border-radius: var(--sg-radius-sm);
|
||||
}
|
||||
|
||||
// Individual styles
|
||||
.results-column {
|
||||
gap: 20px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
|
||||
h1 {
|
||||
@@ -42,13 +88,8 @@
|
||||
}
|
||||
|
||||
.selection-summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 8px 12px;
|
||||
background: var(--sg-surface);
|
||||
border: 1px solid var(--sg-border);
|
||||
border-radius: var(--sg-radius-sm);
|
||||
|
||||
strong {
|
||||
display: block;
|
||||
@@ -65,13 +106,8 @@
|
||||
}
|
||||
|
||||
.active-filters-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
background: var(--sg-surface);
|
||||
padding: 8px 16px;
|
||||
border: 1px solid var(--sg-border);
|
||||
border-radius: var(--sg-radius-sm);
|
||||
flex-wrap: wrap;
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -82,15 +118,11 @@
|
||||
}
|
||||
|
||||
.chips-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.filter-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 2px 8px;
|
||||
background: var(--sg-surface-soft);
|
||||
@@ -99,53 +131,53 @@
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--sg-text);
|
||||
|
||||
button {
|
||||
border: none;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
color: var(--sg-text-soft);
|
||||
|
||||
&:hover {
|
||||
color: var(--sg-text);
|
||||
}
|
||||
|
||||
mat-icon {
|
||||
font-size: 12px;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Shared button resets
|
||||
.filter-chip button,
|
||||
.clear-topic-search,
|
||||
.clear-all-btn {
|
||||
border: none;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.filter-chip button,
|
||||
.clear-topic-search {
|
||||
padding: 0;
|
||||
display: flex;
|
||||
color: var(--sg-text-soft);
|
||||
|
||||
&:hover {
|
||||
color: var(--sg-text);
|
||||
}
|
||||
}
|
||||
|
||||
.filter-chip button mat-icon {
|
||||
font-size: 12px;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
}
|
||||
|
||||
.clear-topic-search mat-icon {
|
||||
font-size: 14px;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}
|
||||
|
||||
.clear-all-btn {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--sg-warning);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
border-bottom: 1px solid var(--sg-border);
|
||||
padding-bottom: 12px;
|
||||
}
|
||||
|
||||
.result-count {
|
||||
font-size: 13px;
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
.sort-selector {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 13px;
|
||||
color: var(--sg-text-muted);
|
||||
@@ -159,6 +191,14 @@
|
||||
color: var(--sg-text);
|
||||
outline: none;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
border-color 0.15s,
|
||||
box-shadow 0.15s;
|
||||
|
||||
&:focus-visible {
|
||||
border-color: var(--sg-primary);
|
||||
box-shadow: 0 0 0 2px var(--sg-primary-soft);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,8 +209,6 @@
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 48px 16px;
|
||||
background: var(--sg-surface);
|
||||
@@ -204,24 +242,14 @@ mat-paginator {
|
||||
}
|
||||
|
||||
.filters-sidebar {
|
||||
background: var(--sg-surface);
|
||||
border: 1px solid var(--sg-border);
|
||||
border-radius: var(--sg-radius-sm);
|
||||
padding: 16px;
|
||||
box-shadow: var(--sg-shadow-sm);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
position: sticky;
|
||||
top: 16px;
|
||||
}
|
||||
|
||||
.sidebar-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding-bottom: 12px;
|
||||
border-bottom: 1px solid var(--sg-border);
|
||||
|
||||
mat-icon {
|
||||
color: var(--sg-primary);
|
||||
@@ -238,8 +266,6 @@ mat-paginator {
|
||||
}
|
||||
|
||||
.filter-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
@@ -252,13 +278,18 @@ mat-paginator {
|
||||
}
|
||||
|
||||
.topic-search-wrapper {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background: var(--sg-surface-soft);
|
||||
border: 1px solid var(--sg-border);
|
||||
border-radius: var(--sg-radius-sm);
|
||||
padding: 4px 8px;
|
||||
transition:
|
||||
border-color 0.15s,
|
||||
box-shadow 0.15s;
|
||||
|
||||
&:focus-within {
|
||||
border-color: var(--sg-primary);
|
||||
box-shadow: 0 0 0 2px var(--sg-primary-soft);
|
||||
}
|
||||
|
||||
mat-icon {
|
||||
font-size: 16px;
|
||||
@@ -276,20 +307,6 @@ mat-paginator {
|
||||
flex-grow: 1;
|
||||
margin-left: 6px;
|
||||
}
|
||||
|
||||
.clear-topic-search {
|
||||
border: none;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
color: var(--sg-text-soft);
|
||||
|
||||
mat-icon {
|
||||
font-size: 14px;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.sidebar-footer {
|
||||
@@ -307,12 +324,21 @@ mat-paginator {
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
transition:
|
||||
background 0.15s,
|
||||
box-shadow 0.15s;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: var(--sg-primary-strong);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: none;
|
||||
box-shadow:
|
||||
0 0 0 2px var(--sg-background),
|
||||
0 0 0 4px var(--sg-primary);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
|
||||
@@ -78,8 +78,9 @@ export class PersonListComponent {
|
||||
defaultOrderValue = 'desc';
|
||||
|
||||
// Selected filter states
|
||||
selectedTopics = new Set<string>();
|
||||
searchValue = signal<string | null>(null);
|
||||
readonly selectedTopics = signal<Set<string>>(new Set<string>());
|
||||
readonly searchValue = signal<string | null>(null);
|
||||
readonly topicSearchType = signal<'hybrid' | 'semantic'>('hybrid');
|
||||
|
||||
// Applied filter states (reflecting actual URL query params)
|
||||
appliedInstitutionName = '';
|
||||
@@ -144,11 +145,14 @@ export class PersonListComponent {
|
||||
const filterYear = params['filterYear']
|
||||
? Number.parseInt(params['filterYear'], 10)
|
||||
: new Date().getFullYear() - 1;
|
||||
const topicSearch = params['topicSearch'] || '';
|
||||
const topicSearchType =
|
||||
params['topicSearchType'] === 'semantic' ? 'semantic' : 'hybrid';
|
||||
|
||||
const topics = this.parseQueryParamArray(params['topic']);
|
||||
|
||||
// restore values from query params
|
||||
this.selectedTopics = new Set(topics);
|
||||
this.selectedTopics.set(new Set(topics));
|
||||
this.currentPage = page;
|
||||
this.paginationService.selection = pageSize;
|
||||
|
||||
@@ -177,6 +181,10 @@ export class PersonListComponent {
|
||||
if (this.filterYearControl.value !== filterYear) {
|
||||
this.filterYearControl.setValue(filterYear);
|
||||
}
|
||||
if (this.topicSearchControl.value !== topicSearch) {
|
||||
this.topicSearchControl.setValue(topicSearch, { emitEvent: false });
|
||||
}
|
||||
this.topicSearchType.set(topicSearchType);
|
||||
|
||||
// Update applied filter states
|
||||
this.appliedInstitutionName = institutionName;
|
||||
@@ -214,6 +222,22 @@ export class PersonListComponent {
|
||||
.subscribe(() => {
|
||||
this.applySidebarFilters();
|
||||
});
|
||||
|
||||
this.topicSearchControl.valueChanges
|
||||
.pipe(
|
||||
debounceTime(300),
|
||||
distinctUntilChanged(),
|
||||
takeUntilDestroyed(this.destroyRef),
|
||||
)
|
||||
.subscribe((val) => {
|
||||
this.router.navigate([], {
|
||||
queryParams: {
|
||||
topicSearch: val || null,
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private updateSortOrderState(value: any) {
|
||||
@@ -237,7 +261,7 @@ export class PersonListComponent {
|
||||
|
||||
// Filter selection checks
|
||||
isTopicSelected(topic: string): boolean {
|
||||
return this.selectedTopics.has(topic);
|
||||
return this.selectedTopics().has(topic);
|
||||
}
|
||||
|
||||
isRelevanceSelected(): boolean {
|
||||
@@ -245,11 +269,15 @@ export class PersonListComponent {
|
||||
}
|
||||
|
||||
toggleTopic(topic: string): void {
|
||||
if (this.selectedTopics.has(topic)) {
|
||||
this.selectedTopics.delete(topic);
|
||||
} else {
|
||||
this.selectedTopics.add(topic);
|
||||
}
|
||||
this.selectedTopics.update((set) => {
|
||||
const next = new Set(set);
|
||||
if (next.has(topic)) {
|
||||
next.delete(topic);
|
||||
} else {
|
||||
next.add(topic);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
this.applySidebarFilters();
|
||||
}
|
||||
|
||||
@@ -260,7 +288,7 @@ export class PersonListComponent {
|
||||
label: string;
|
||||
}> {
|
||||
const list: Array<{ category: string; value: string; label: string }> = [];
|
||||
this.selectedTopics.forEach((t) => {
|
||||
this.selectedTopics().forEach((t) => {
|
||||
list.push({ category: 'topic', value: t, label: `Thema: ${t}` });
|
||||
});
|
||||
if (this.appliedInstitutionName) {
|
||||
@@ -280,7 +308,11 @@ export class PersonListComponent {
|
||||
|
||||
removeFilter(filter: { category: string; value: string }): void {
|
||||
if (filter.category === 'topic') {
|
||||
this.selectedTopics.delete(filter.value);
|
||||
this.selectedTopics.update((set) => {
|
||||
const next = new Set(set);
|
||||
next.delete(filter.value);
|
||||
return next;
|
||||
});
|
||||
} else if (filter.category === 'institutionName') {
|
||||
this.institutionControl.setValue('', { emitEvent: false });
|
||||
this.updateYearFilterState('');
|
||||
@@ -293,7 +325,7 @@ export class PersonListComponent {
|
||||
}
|
||||
|
||||
clearAllFilters(): void {
|
||||
this.selectedTopics.clear();
|
||||
this.selectedTopics.set(new Set<string>());
|
||||
this.institutionControl.setValue('', { emitEvent: false });
|
||||
this.updateYearFilterState('');
|
||||
this.institutionOptions.set([]);
|
||||
@@ -309,9 +341,12 @@ export class PersonListComponent {
|
||||
}
|
||||
this.router.navigate([], {
|
||||
queryParams: {
|
||||
topic: this.selectedTopics.size
|
||||
? Array.from(this.selectedTopics)
|
||||
topic: this.selectedTopics().size
|
||||
? Array.from(this.selectedTopics())
|
||||
: null,
|
||||
topicSearch: this.topicSearchControl.value || null,
|
||||
topicSearchType:
|
||||
this.topicSearchType() === 'semantic' ? 'semantic' : null,
|
||||
institutionName: this.institutionControl.value || null,
|
||||
sortBy: this.sortValueControl.value || null,
|
||||
sortOrder: this.sortOrderControl.value || null,
|
||||
@@ -363,12 +398,17 @@ export class PersonListComponent {
|
||||
}
|
||||
|
||||
onTopicSelectionChange(newSelection: Set<string>): void {
|
||||
this.selectedTopics = newSelection;
|
||||
this.selectedTopics.set(newSelection);
|
||||
this.applySidebarFilters();
|
||||
}
|
||||
|
||||
onTopicSearchTypeChange(type: 'hybrid' | 'semantic'): void {
|
||||
this.topicSearchType.set(type);
|
||||
this.applySidebarFilters();
|
||||
}
|
||||
|
||||
onCardTopicClick(topic: string): void {
|
||||
this.topicSearchControl.setValue(topic);
|
||||
this.toggleTopic(topic);
|
||||
}
|
||||
|
||||
onCardInstitutionClick(institutionName: string): void {
|
||||
|
||||
@@ -299,7 +299,7 @@ export class PersonNetworkComponent implements OnInit {
|
||||
console.log('Form value when opening dialog:', this.filterForm.value);
|
||||
const dialogRef = this.dialog.open(PersonNetworkFilterDialogComponent, {
|
||||
data: {
|
||||
collaborationNetwork: this.collaborationNetwork,
|
||||
collaborationNetwork: this.collaborationNetwork(),
|
||||
filterBy: this.filterForm.get('filterBy')?.value || 'works',
|
||||
startYear: this.filterForm.get('startYear')?.value,
|
||||
|
||||
@@ -407,22 +407,34 @@ export class PersonNetworkComponent implements OnInit {
|
||||
];
|
||||
|
||||
this.filterForm.valueChanges.pipe(debounceTime(300)).subscribe((value) => {
|
||||
console.log('Form value changed:', value);
|
||||
const queryParams = {
|
||||
table: value.displayedTable ?? 'collaborators',
|
||||
search_term: value.searchTerm ?? '',
|
||||
filter_by: value.filterBy ?? 'works',
|
||||
start_year: value.startYear ?? '',
|
||||
end_year: value.endYear ?? '',
|
||||
min_contributors: value.minContributors ?? 2,
|
||||
max_contributors: value.maxContributors ?? 10,
|
||||
min_collaborations: value.minCollaborations ?? 1,
|
||||
max_collaborations: value.maxCollaborations ?? 100,
|
||||
institutions: value.institutions?.join(',') ?? '',
|
||||
topics: value.topics?.join(',') ?? '',
|
||||
};
|
||||
|
||||
const currentQueryParams = this.activatedRoute.snapshot.queryParams;
|
||||
|
||||
const hasChanged = Object.entries(queryParams).some(([key, value]) => {
|
||||
return String(currentQueryParams[key] ?? '') !== String(value ?? '');
|
||||
});
|
||||
|
||||
if (!hasChanged) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.router.navigate([], {
|
||||
relativeTo: this.activatedRoute,
|
||||
queryParams: {
|
||||
table: value.displayedTable,
|
||||
search_term: value.searchTerm,
|
||||
filter_by: value.filterBy,
|
||||
start_year: value.startYear,
|
||||
end_year: value.endYear,
|
||||
min_contributors: value.minContributors,
|
||||
max_contributors: value.maxContributors,
|
||||
min_collaborations: value.minCollaborations,
|
||||
max_collaborations: value.maxCollaborations,
|
||||
institutions: value.institutions?.join(','),
|
||||
topics: value.topics?.join(','),
|
||||
},
|
||||
queryParams,
|
||||
replaceUrl: true,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
+144
-80
@@ -7,22 +7,87 @@
|
||||
<span>(basierend auf Publikationen)</span>
|
||||
</p>
|
||||
|
||||
<button
|
||||
*ngIf="
|
||||
showEarlierYearsControl &&
|
||||
timelineViewMode === 'compact' &&
|
||||
!loading &&
|
||||
!loadFailed
|
||||
"
|
||||
type="button"
|
||||
class="load-more-action-button"
|
||||
[disabled]="loadingEarlierYears"
|
||||
(click)="requestEarlierYears()">
|
||||
<span class="load-more-content">
|
||||
<mat-spinner *ngIf="loadingEarlierYears" diameter="16"></mat-spinner>
|
||||
<span>{{ earlierYearsLabel }}</span>
|
||||
</span>
|
||||
</button>
|
||||
<div
|
||||
*ngIf="subfieldLegendGroups.length > 0"
|
||||
class="subfield-legend"
|
||||
[class.expanded]="subfieldLegendExpanded"
|
||||
aria-label="Aktuell sichtbare Themenbereiche">
|
||||
<div class="subfield-legend-header">
|
||||
<div class="subfield-legend-title">
|
||||
<span>Farben nach Themenbereich</span>
|
||||
<mat-icon
|
||||
class="subfield-legend-info"
|
||||
matTooltip="Fachgebiete geben die Farbfamilie vor, Themenbereiche bestimmen die konkrete Farbvariante."
|
||||
matTooltipPosition="above"
|
||||
aria-label="Informationen zur Farblegende">
|
||||
info_outline
|
||||
</mat-icon>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="subfield-legend-visibility-toggle"
|
||||
[attr.aria-expanded]="subfieldLegendVisible"
|
||||
(click)="toggleSubfieldLegendVisibility()">
|
||||
<span>
|
||||
{{
|
||||
subfieldLegendVisible
|
||||
? 'Legende ausblenden'
|
||||
: 'Legende einblenden'
|
||||
}}
|
||||
</span>
|
||||
<mat-icon aria-hidden="true">
|
||||
{{ subfieldLegendVisible ? 'expand_less' : 'expand_more' }}
|
||||
</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div *ngIf="subfieldLegendVisible" class="subfield-legend-content">
|
||||
<div
|
||||
*ngFor="
|
||||
let group of subfieldLegendGroups;
|
||||
trackBy: trackByLegendGroup
|
||||
"
|
||||
class="subfield-legend-group">
|
||||
<span
|
||||
class="subfield-legend-field"
|
||||
[matTooltip]="group.tooltip"
|
||||
[matTooltipDisabled]="!group.tooltip"
|
||||
matTooltipClass="topic-chip-tooltip"
|
||||
matTooltipPosition="above"
|
||||
>{{ group.name }}</span
|
||||
>
|
||||
|
||||
<span class="subfield-legend-items">
|
||||
<span
|
||||
*ngFor="let item of group.items; trackBy: trackByLegendItem"
|
||||
class="subfield-legend-item"
|
||||
[matTooltip]="item.tooltip"
|
||||
[matTooltipDisabled]="!item.tooltip"
|
||||
matTooltipClass="topic-chip-tooltip"
|
||||
matTooltipPosition="above">
|
||||
<span
|
||||
class="subfield-legend-dot"
|
||||
[style.background]="item.color"
|
||||
aria-hidden="true"></span>
|
||||
<span>{{ item.name }}</span>
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
*ngIf="showSubfieldLegendToggle"
|
||||
type="button"
|
||||
class="subfield-legend-more-toggle"
|
||||
(click)="toggleSubfieldLegend()">
|
||||
{{
|
||||
subfieldLegendExpanded
|
||||
? 'Weniger anzeigen'
|
||||
: '+' + hiddenSubfieldLegendItemCount + ' weitere'
|
||||
}}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<span
|
||||
*ngIf="
|
||||
@@ -157,13 +222,11 @@
|
||||
</div>
|
||||
|
||||
<div
|
||||
*ngFor="
|
||||
let item of timelineItems;
|
||||
let index = index;
|
||||
trackBy: trackByYear
|
||||
"
|
||||
*ngFor="let item of timelineItems; trackBy: trackByYear"
|
||||
class="timeline-point"
|
||||
[ngClass]="getColorClass(index)">
|
||||
[style.--timeline-color]="
|
||||
getTopicColor(getMainTopicItem(item))
|
||||
">
|
||||
<button
|
||||
type="button"
|
||||
class="year-button"
|
||||
@@ -218,9 +281,10 @@
|
||||
type="button"
|
||||
class="main-topic-button"
|
||||
[disabled]="!getMainTopicItem(item)?.id"
|
||||
[matTooltip]="getTopicDescription(getMainTopicItem(item))"
|
||||
[matTooltip]="getTopicTooltip(getMainTopicItem(item))"
|
||||
matTooltipClass="topic-chip-tooltip"
|
||||
[matTooltipDisabled]="
|
||||
!hasTopicDescription(getMainTopicItem(item))
|
||||
!hasTopicTooltip(getMainTopicItem(item))
|
||||
"
|
||||
(click)="
|
||||
selectTopic(getMainTopicItem(item), [item.year])
|
||||
@@ -248,28 +312,23 @@
|
||||
getDisplayedTopics(item).length > 0;
|
||||
else noTopicsForYear
|
||||
">
|
||||
<button
|
||||
type="button"
|
||||
<app-topic-chip
|
||||
*ngFor="
|
||||
let topic of getDisplayedTopics(item);
|
||||
trackBy: trackByTopic
|
||||
"
|
||||
class="topic-chip"
|
||||
[ngClass]="getColorClass(index)"
|
||||
class="timeline-topic-chip"
|
||||
[label]="topic.name"
|
||||
[count]="topic.count"
|
||||
[description]="getTopicDescription(topic)"
|
||||
[subfieldName]="topic.subfield_name"
|
||||
[fieldName]="topic.field_name"
|
||||
[domainName]="topic.domain_name"
|
||||
[countTooltip]="getYearTopicCountTooltip(topic, item)"
|
||||
[color]="getTopicColor(topic)"
|
||||
[disabled]="!topic.id"
|
||||
(click)="selectTopic(topic, [item.year])">
|
||||
<span
|
||||
class="topic-name"
|
||||
[matTooltip]="getTopicDescription(topic)"
|
||||
[matTooltipDisabled]="!hasTopicDescription(topic)">
|
||||
{{ topic.name }}
|
||||
</span>
|
||||
<span
|
||||
class="topic-count"
|
||||
[matTooltip]="getYearTopicCountTooltip(topic, item)">
|
||||
{{ topic.count }}
|
||||
</span>
|
||||
</button>
|
||||
(chipClick)="selectTopic(topic, [item.year])">
|
||||
</app-topic-chip>
|
||||
</ng-container>
|
||||
|
||||
<ng-template #noTopicsForYear>
|
||||
@@ -283,15 +342,26 @@
|
||||
</ng-container>
|
||||
|
||||
<ng-template #compactTimeline>
|
||||
<div *ngIf="showEarlierYearsControl" class="compact-load-more-row">
|
||||
<button
|
||||
type="button"
|
||||
class="load-more-action-button"
|
||||
[disabled]="loadingEarlierYears"
|
||||
(click)="requestEarlierYears()">
|
||||
<span class="load-more-content">
|
||||
<mat-spinner
|
||||
*ngIf="loadingEarlierYears"
|
||||
diameter="16"></mat-spinner>
|
||||
<span>{{ earlierYearsLabel }}</span>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="compact-phase-list">
|
||||
<article
|
||||
*ngFor="
|
||||
let phase of compactPhases;
|
||||
let index = index;
|
||||
trackBy: trackByPhase
|
||||
"
|
||||
*ngFor="let phase of compactPhases; trackBy: trackByPhase"
|
||||
class="phase-card"
|
||||
[ngClass]="getColorClass(index)">
|
||||
[style.--timeline-color]="getTopicColor(phase.primaryTopic)">
|
||||
<div class="phase-card-header">
|
||||
<span class="phase-marker"></span>
|
||||
|
||||
@@ -328,9 +398,10 @@
|
||||
type="button"
|
||||
class="main-topic-button"
|
||||
[disabled]="!phase.primaryTopic.id"
|
||||
[matTooltip]="getTopicDescription(phase.primaryTopic)"
|
||||
[matTooltip]="getTopicTooltip(phase.primaryTopic)"
|
||||
matTooltipClass="topic-chip-tooltip"
|
||||
[matTooltipDisabled]="
|
||||
!hasTopicDescription(phase.primaryTopic)
|
||||
!hasTopicTooltip(phase.primaryTopic)
|
||||
"
|
||||
(click)="
|
||||
selectTopic(phase.primaryTopic, getPhaseYears(phase))
|
||||
@@ -344,25 +415,20 @@
|
||||
<div class="phase-topics">
|
||||
<ng-container
|
||||
*ngIf="phase.topics.length > 0; else noPhaseTopics">
|
||||
<button
|
||||
type="button"
|
||||
<app-topic-chip
|
||||
*ngFor="let topic of phase.topics; trackBy: trackByTopic"
|
||||
class="topic-chip"
|
||||
[ngClass]="getColorClass(index)"
|
||||
class="phase-topic-chip"
|
||||
[label]="topic.name"
|
||||
[count]="topic.count"
|
||||
[description]="getTopicDescription(topic)"
|
||||
[subfieldName]="topic.subfield_name"
|
||||
[fieldName]="topic.field_name"
|
||||
[domainName]="topic.domain_name"
|
||||
[countTooltip]="getPhaseTopicCountTooltip(topic, phase)"
|
||||
[color]="getTopicColor(topic)"
|
||||
[disabled]="!topic.id"
|
||||
(click)="selectTopic(topic, getPhaseYears(phase))">
|
||||
<span
|
||||
class="topic-name"
|
||||
[matTooltip]="getTopicDescription(topic)"
|
||||
[matTooltipDisabled]="!hasTopicDescription(topic)">
|
||||
{{ topic.name }}
|
||||
</span>
|
||||
<span
|
||||
class="topic-count"
|
||||
[matTooltip]="getPhaseTopicCountTooltip(topic, phase)">
|
||||
{{ topic.count }}
|
||||
</span>
|
||||
</button>
|
||||
(chipClick)="selectTopic(topic, getPhaseYears(phase))">
|
||||
</app-topic-chip>
|
||||
</ng-container>
|
||||
|
||||
<ng-template #noPhaseTopics>
|
||||
@@ -420,8 +486,7 @@
|
||||
).length > 0;
|
||||
else noPhaseYearTopics
|
||||
">
|
||||
<button
|
||||
type="button"
|
||||
<app-topic-chip
|
||||
*ngFor="
|
||||
let topic of getDisplayedTopicsForPrimaryTopic(
|
||||
year,
|
||||
@@ -429,19 +494,18 @@
|
||||
);
|
||||
trackBy: trackByTopic
|
||||
"
|
||||
class="mini-topic-chip"
|
||||
size="mini"
|
||||
[label]="topic.name"
|
||||
[count]="topic.count"
|
||||
[description]="getTopicDescription(topic)"
|
||||
[subfieldName]="topic.subfield_name"
|
||||
[fieldName]="topic.field_name"
|
||||
[domainName]="topic.domain_name"
|
||||
[countTooltip]="getYearTopicCountTooltip(topic, year)"
|
||||
[color]="getTopicColor(topic)"
|
||||
[disabled]="!topic.id"
|
||||
(click)="selectTopic(topic, [year.year])">
|
||||
<span
|
||||
[matTooltip]="getTopicDescription(topic)"
|
||||
[matTooltipDisabled]="!hasTopicDescription(topic)">
|
||||
{{ topic.name }}
|
||||
</span>
|
||||
<strong
|
||||
[matTooltip]="getYearTopicCountTooltip(topic, year)">
|
||||
{{ topic.count }}
|
||||
</strong>
|
||||
</button>
|
||||
(chipClick)="selectTopic(topic, [year.year])">
|
||||
</app-topic-chip>
|
||||
</ng-container>
|
||||
|
||||
<ng-template #noPhaseYearTopics>
|
||||
|
||||
+141
-134
@@ -11,9 +11,6 @@
|
||||
|
||||
button {
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
button:not(:where(.topic-chip, .mini-topic-chip)) {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
@@ -67,6 +64,131 @@
|
||||
}
|
||||
}
|
||||
|
||||
.subfield-legend {
|
||||
width: min(760px, 100%);
|
||||
box-sizing: border-box;
|
||||
margin-top: 16px;
|
||||
padding: 13px 16px;
|
||||
border: 1px solid #dbe5f6;
|
||||
border-radius: 8px;
|
||||
background: #ffffff;
|
||||
}
|
||||
|
||||
.subfield-legend-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.subfield-legend-title,
|
||||
.subfield-legend-visibility-toggle,
|
||||
.subfield-legend-content,
|
||||
.subfield-legend-group,
|
||||
.subfield-legend-items,
|
||||
.subfield-legend-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.subfield-legend-title {
|
||||
gap: 5px;
|
||||
color: #07163d;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.subfield-legend-info {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
color: #7d8aa8;
|
||||
font-size: 14px;
|
||||
line-height: 14px;
|
||||
}
|
||||
|
||||
.subfield-legend-visibility-toggle {
|
||||
flex: 0 0 auto;
|
||||
gap: 4px;
|
||||
color: var(--accent);
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
|
||||
mat-icon {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
font-size: 14px;
|
||||
line-height: 14px;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
text-decoration: none;
|
||||
}
|
||||
}
|
||||
|
||||
.subfield-legend-content {
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 17px;
|
||||
}
|
||||
|
||||
.subfield-legend-group {
|
||||
gap: 9px;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
min-height: 28px;
|
||||
padding: 5px 9px;
|
||||
border: 1px solid #dbe5f6;
|
||||
border-radius: 999px;
|
||||
background: #fbfdff;
|
||||
}
|
||||
|
||||
.subfield-legend-field {
|
||||
flex: 0 0 auto;
|
||||
color: #07163d;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
line-height: 1.2;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.subfield-legend-items {
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 11px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.subfield-legend-item {
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
color: #53617e;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.subfield-legend-dot {
|
||||
flex: 0 0 auto;
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.85);
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.2);
|
||||
}
|
||||
|
||||
.subfield-legend-more-toggle {
|
||||
flex: 0 0 auto;
|
||||
color: var(--accent);
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
|
||||
&:hover {
|
||||
text-decoration: none;
|
||||
}
|
||||
}
|
||||
|
||||
.view-toggle {
|
||||
justify-self: center;
|
||||
display: flex;
|
||||
@@ -291,12 +413,12 @@
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 13px;
|
||||
height: 13px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border: 3px solid #ffffff;
|
||||
border-radius: 50%;
|
||||
background: var(--timeline-color);
|
||||
box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.16);
|
||||
box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.24);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -366,60 +488,9 @@
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.topic-chip {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
justify-items: center;
|
||||
column-gap: 8px;
|
||||
app-topic-chip.timeline-topic-chip {
|
||||
width: 100%;
|
||||
max-width: 210px;
|
||||
box-sizing: border-box;
|
||||
min-height: 34px;
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--topic-border);
|
||||
border-radius: 8px;
|
||||
background: var(--topic-bg);
|
||||
color: var(--topic-color);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
line-height: 1.25;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
transform 0.15s ease,
|
||||
box-shadow 0.15s ease;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 4px 10px rgba(15, 23, 42, 0.12);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
|
||||
.topic-name,
|
||||
.mini-topic-chip span {
|
||||
min-width: 0;
|
||||
text-align: center;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.topic-count {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 18px;
|
||||
height: 18px;
|
||||
padding: 0 5px;
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, 0.78);
|
||||
color: inherit;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.no-topics {
|
||||
@@ -427,6 +498,11 @@
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.compact-load-more-row {
|
||||
display: flex;
|
||||
margin: 6px 0 28px;
|
||||
}
|
||||
|
||||
.compact-phase-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
@@ -453,13 +529,13 @@
|
||||
}
|
||||
|
||||
.phase-marker {
|
||||
width: 11px;
|
||||
height: 11px;
|
||||
margin-top: 5px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
margin-top: 3px;
|
||||
border: 3px solid #ffffff;
|
||||
border-radius: 50%;
|
||||
background: var(--timeline-color);
|
||||
box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.14);
|
||||
box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.22);
|
||||
}
|
||||
|
||||
.phase-title-block {
|
||||
@@ -505,7 +581,7 @@
|
||||
gap: 7px;
|
||||
margin-top: 14px;
|
||||
|
||||
.topic-chip {
|
||||
app-topic-chip.phase-topic-chip {
|
||||
flex: 0 0 calc((100% - 7px) / 2);
|
||||
width: calc((100% - 7px) / 2);
|
||||
max-width: none;
|
||||
@@ -574,75 +650,6 @@
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.mini-topic-chip {
|
||||
display: inline-grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
column-gap: 5px;
|
||||
max-width: 100%;
|
||||
padding: 4px 7px;
|
||||
border: 0;
|
||||
border-radius: 7px;
|
||||
background: #f2f6ff;
|
||||
color: #40506f;
|
||||
font-family: inherit;
|
||||
font-size: 11px;
|
||||
line-height: 1.25;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
color: var(--accent);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
strong {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
color: var(--accent);
|
||||
font-size: 10px;
|
||||
}
|
||||
}
|
||||
|
||||
.purple {
|
||||
--timeline-color: #7255d9;
|
||||
--topic-border: #d8cafe;
|
||||
--topic-bg: #f6f0ff;
|
||||
--topic-color: #7255d9;
|
||||
}
|
||||
|
||||
.blue {
|
||||
--timeline-color: #2678e8;
|
||||
--topic-border: #bdd4ff;
|
||||
--topic-bg: #f0f6ff;
|
||||
--topic-color: #0b63ce;
|
||||
}
|
||||
|
||||
.green {
|
||||
--timeline-color: #39a96b;
|
||||
--topic-border: #bdebcf;
|
||||
--topic-bg: #effaf3;
|
||||
--topic-color: #24834f;
|
||||
}
|
||||
|
||||
.orange {
|
||||
--timeline-color: #f59e0b;
|
||||
--topic-border: #ffd796;
|
||||
--topic-bg: #fff7e8;
|
||||
--topic-color: #c67500;
|
||||
}
|
||||
|
||||
.pink {
|
||||
--timeline-color: #e0527c;
|
||||
--topic-border: #ffc7d7;
|
||||
--topic-bg: #fff1f5;
|
||||
--topic-color: #d12f61;
|
||||
}
|
||||
|
||||
.timeline-note {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
@@ -655,8 +662,8 @@
|
||||
}
|
||||
|
||||
.note-dot {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border: 3px solid #dce5f5;
|
||||
border-radius: 50%;
|
||||
background: #52627f;
|
||||
|
||||
+347
-6
@@ -1,4 +1,5 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import {
|
||||
@@ -12,12 +13,24 @@ import {
|
||||
SimpleChanges,
|
||||
ViewChild,
|
||||
} from '@angular/core';
|
||||
import { TopicChipComponent } from '../../../../shared/ui/topic-chip/topic-chip.component';
|
||||
import { topicHierarchyColor } from '../../../../shared/utils/topic-colors';
|
||||
import { buildTopicHierarchyTooltip } from '../../../../shared/utils/topic-tooltip';
|
||||
|
||||
export interface TopicTimelineTopic {
|
||||
id?: string;
|
||||
name: string;
|
||||
count: number;
|
||||
description?: string;
|
||||
subfield_id?: string;
|
||||
subfield_name?: string;
|
||||
subfield_description?: string;
|
||||
field_id?: string;
|
||||
field_name?: string;
|
||||
field_description?: string;
|
||||
domain_id?: string;
|
||||
domain_name?: string;
|
||||
domain_description?: string;
|
||||
}
|
||||
|
||||
export interface TopicTimelineElement {
|
||||
@@ -65,10 +78,34 @@ interface TimelineScrollAnchor {
|
||||
scrollLeft: number;
|
||||
}
|
||||
|
||||
interface TopicSubfieldLegendItem {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
color: string;
|
||||
tooltip: string;
|
||||
}
|
||||
|
||||
interface TopicFieldLegendGroup {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
domainName: string;
|
||||
domainDescription: string;
|
||||
tooltip: string;
|
||||
items: TopicSubfieldLegendItem[];
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-research-timeline',
|
||||
standalone: true,
|
||||
imports: [CommonModule, MatProgressSpinnerModule, MatTooltipModule],
|
||||
imports: [
|
||||
CommonModule,
|
||||
MatIconModule,
|
||||
MatProgressSpinnerModule,
|
||||
MatTooltipModule,
|
||||
TopicChipComponent,
|
||||
],
|
||||
templateUrl: './research-timeline.component.html',
|
||||
styleUrl: './research-timeline.component.scss',
|
||||
})
|
||||
@@ -84,12 +121,16 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
@Input() viewMode: TimelineViewMode = 'years';
|
||||
@Input() startYear: number | undefined;
|
||||
@Input() endYear: number | undefined;
|
||||
@Input() subfieldLegendVisible = true;
|
||||
@Input() subfieldLegendExpanded = false;
|
||||
|
||||
@Output() viewModeChange = new EventEmitter<TimelineViewMode>();
|
||||
@Output() yearRangeChange = new EventEmitter<TimelineYearRange>();
|
||||
@Output() topicSelect = new EventEmitter<TimelineTopicSelection>();
|
||||
@Output() yearSelect = new EventEmitter<number[]>();
|
||||
@Output() loadEarlierYears = new EventEmitter<void>();
|
||||
@Output() subfieldLegendVisibleChange = new EventEmitter<boolean>();
|
||||
@Output() subfieldLegendExpandedChange = new EventEmitter<boolean>();
|
||||
|
||||
timelineViewMode: TimelineViewMode = 'years';
|
||||
|
||||
@@ -98,10 +139,10 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
selectedStartYear = 0;
|
||||
selectedEndYear = 0;
|
||||
|
||||
private readonly colors = ['purple', 'blue', 'green', 'orange', 'pink'];
|
||||
private readonly columnWidth = 240;
|
||||
private readonly displayedTopicLimit = 3;
|
||||
private readonly displayedPhaseTopicLimit = 4;
|
||||
private readonly collapsedSubfieldLegendGroupLimit = 3;
|
||||
private readonly scrollRestoreThreshold = 24;
|
||||
private readonly expandedPhaseIds = new Set<string>();
|
||||
|
||||
@@ -157,6 +198,32 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
return this.buildCompactPhases(this.timelineItems);
|
||||
}
|
||||
|
||||
get subfieldLegendGroups(): TopicFieldLegendGroup[] {
|
||||
const groups = this.allSubfieldLegendGroups;
|
||||
|
||||
if (this.subfieldLegendExpanded) {
|
||||
return groups;
|
||||
}
|
||||
|
||||
return groups.slice(0, this.collapsedSubfieldLegendGroupLimit);
|
||||
}
|
||||
|
||||
get hiddenSubfieldLegendItemCount(): number {
|
||||
if (this.subfieldLegendExpanded) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return this.allSubfieldLegendGroups
|
||||
.slice(this.collapsedSubfieldLegendGroupLimit)
|
||||
.reduce((count, group) => count + group.items.length, 0);
|
||||
}
|
||||
|
||||
get showSubfieldLegendToggle(): boolean {
|
||||
return (
|
||||
this.subfieldLegendExpanded || this.hiddenSubfieldLegendItemCount > 0
|
||||
);
|
||||
}
|
||||
|
||||
get hasYearRange(): boolean {
|
||||
return this.minYear > 0 && this.maxYear > 0 && this.minYear < this.maxYear;
|
||||
}
|
||||
@@ -335,8 +402,45 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
return (topic?.description ?? '').trim();
|
||||
}
|
||||
|
||||
hasTopicDescription(topic: TopicTimelineTopic | undefined): boolean {
|
||||
return this.getTopicDescription(topic).length > 0;
|
||||
getTopicTooltip(topic: TopicTimelineTopic | undefined): string {
|
||||
return buildTopicHierarchyTooltip({
|
||||
topicName: topic?.name,
|
||||
description: topic?.description,
|
||||
subfieldName: topic?.subfield_name,
|
||||
fieldName: topic?.field_name,
|
||||
domainName: topic?.domain_name,
|
||||
});
|
||||
}
|
||||
|
||||
hasTopicTooltip(topic: TopicTimelineTopic | undefined): boolean {
|
||||
return this.getTopicTooltip(topic).length > 0;
|
||||
}
|
||||
|
||||
buildLegendTooltip(
|
||||
entries: Array<{ label: string; value: string; description: string }>,
|
||||
): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.value && !entry.description) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (lines.length > 0) {
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (entry.value) {
|
||||
lines.push(`${entry.label}: ${entry.value}`);
|
||||
}
|
||||
|
||||
if (entry.description) {
|
||||
lines.push('');
|
||||
lines.push(`Beschreibung: ${entry.description}`);
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
getYearTopicCountTooltip(
|
||||
@@ -369,8 +473,26 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
return this.expandedPhaseIds.has(phase.id);
|
||||
}
|
||||
|
||||
getColorClass(index: number): string {
|
||||
return this.colors[index % this.colors.length];
|
||||
getTopicColor(topic: TopicTimelineTopic | undefined): string {
|
||||
return topicHierarchyColor(topic);
|
||||
}
|
||||
|
||||
toggleSubfieldLegend(): void {
|
||||
this.subfieldLegendExpanded = !this.subfieldLegendExpanded;
|
||||
this.subfieldLegendExpandedChange.emit(this.subfieldLegendExpanded);
|
||||
}
|
||||
|
||||
toggleSubfieldLegendVisibility(): void {
|
||||
this.subfieldLegendVisible = !this.subfieldLegendVisible;
|
||||
this.subfieldLegendVisibleChange.emit(this.subfieldLegendVisible);
|
||||
}
|
||||
|
||||
trackByLegendGroup(_: number, group: TopicFieldLegendGroup): string {
|
||||
return group.id;
|
||||
}
|
||||
|
||||
trackByLegendItem(_: number, item: TopicSubfieldLegendItem): string {
|
||||
return item.id;
|
||||
}
|
||||
|
||||
trackByYear(_: number, item: TopicTimelineElement): number {
|
||||
@@ -519,6 +641,117 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
);
|
||||
}
|
||||
|
||||
private get allSubfieldLegendGroups(): TopicFieldLegendGroup[] {
|
||||
if (
|
||||
this.loading ||
|
||||
this.loadFailed ||
|
||||
this.timelineViewMode === 'wordcloud'
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const groups = new Map<string, TopicFieldLegendGroup>();
|
||||
|
||||
for (const topic of this.visibleLegendTopics) {
|
||||
const subfieldName = topic.subfield_name?.trim();
|
||||
|
||||
if (!subfieldName) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fieldName = topic.field_name?.trim() || 'Ohne Field';
|
||||
const fieldKey = topic.field_id ?? this.normalizeTopicName(fieldName);
|
||||
const subfieldKey =
|
||||
topic.subfield_id ?? this.normalizeTopicName(subfieldName);
|
||||
|
||||
if (!groups.has(fieldKey)) {
|
||||
groups.set(fieldKey, {
|
||||
id: fieldKey,
|
||||
name: fieldName,
|
||||
description: topic.field_description?.trim() ?? '',
|
||||
domainName: topic.domain_name?.trim() ?? '',
|
||||
domainDescription: topic.domain_description?.trim() ?? '',
|
||||
tooltip: this.buildLegendTooltip([
|
||||
{
|
||||
label: 'Fachgebiet',
|
||||
value: fieldName,
|
||||
description: topic.field_description?.trim() ?? '',
|
||||
},
|
||||
{
|
||||
label: 'Wissenschaftsbereich',
|
||||
value: topic.domain_name?.trim() ?? '',
|
||||
description: topic.domain_description?.trim() ?? '',
|
||||
},
|
||||
]),
|
||||
items: [],
|
||||
});
|
||||
}
|
||||
|
||||
const group = groups.get(fieldKey);
|
||||
|
||||
if (!group || group.items.some((item) => item.id === subfieldKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
group.items.push({
|
||||
id: subfieldKey,
|
||||
name: subfieldName,
|
||||
description: topic.subfield_description?.trim() ?? '',
|
||||
color: this.getTopicColor(topic),
|
||||
tooltip: this.buildLegendTooltip([
|
||||
{
|
||||
label: 'Themenbereich',
|
||||
value: subfieldName,
|
||||
description: topic.subfield_description?.trim() ?? '',
|
||||
},
|
||||
{
|
||||
label: 'Fachgebiet',
|
||||
value: fieldName,
|
||||
description: topic.field_description?.trim() ?? '',
|
||||
},
|
||||
{
|
||||
label: 'Wissenschaftsbereich',
|
||||
value: topic.domain_name?.trim() ?? '',
|
||||
description: topic.domain_description?.trim() ?? '',
|
||||
},
|
||||
]),
|
||||
});
|
||||
}
|
||||
|
||||
return [...groups.values()]
|
||||
.map((group) => ({
|
||||
...group,
|
||||
items: group.items.sort((left, right) =>
|
||||
left.name.localeCompare(right.name),
|
||||
),
|
||||
}))
|
||||
.sort((left, right) => left.name.localeCompare(right.name));
|
||||
}
|
||||
|
||||
private get visibleLegendTopics(): TopicTimelineTopic[] {
|
||||
if (this.timelineViewMode === 'compact') {
|
||||
return this.compactPhases.flatMap((phase) => [
|
||||
phase.primaryTopic,
|
||||
...phase.topics,
|
||||
...(this.isPhaseExpanded(phase)
|
||||
? phase.years.flatMap((year) =>
|
||||
this.getDisplayedTopicsForPrimaryTopic(
|
||||
year,
|
||||
phase.primaryTopicName,
|
||||
),
|
||||
)
|
||||
: []),
|
||||
]);
|
||||
}
|
||||
|
||||
return this.timelineItems
|
||||
.flatMap((item) => [
|
||||
this.getMainTopicItem(item),
|
||||
...this.getDisplayedTopics(item),
|
||||
])
|
||||
.filter((topic): topic is TopicTimelineTopic => Boolean(topic));
|
||||
}
|
||||
|
||||
private initializeYearBounds(): void {
|
||||
const years = this.sortedElements
|
||||
.map((item) => item.year)
|
||||
@@ -646,6 +879,15 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
let count = 0;
|
||||
let id = primaryTopic.id;
|
||||
let description = primaryTopic.description;
|
||||
let subfieldId = primaryTopic.subfield_id;
|
||||
let subfieldName = primaryTopic.subfield_name;
|
||||
let subfieldDescription = primaryTopic.subfield_description;
|
||||
let fieldId = primaryTopic.field_id;
|
||||
let fieldName = primaryTopic.field_name;
|
||||
let fieldDescription = primaryTopic.field_description;
|
||||
let domainId = primaryTopic.domain_id;
|
||||
let domainName = primaryTopic.domain_name;
|
||||
let domainDescription = primaryTopic.domain_description;
|
||||
|
||||
for (const year of years) {
|
||||
for (const topic of year.primary_topics ?? []) {
|
||||
@@ -662,6 +904,42 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
if (!description && topic.description) {
|
||||
description = topic.description;
|
||||
}
|
||||
|
||||
if (!subfieldId && topic.subfield_id) {
|
||||
subfieldId = topic.subfield_id;
|
||||
}
|
||||
|
||||
if (!subfieldName && topic.subfield_name) {
|
||||
subfieldName = topic.subfield_name;
|
||||
}
|
||||
|
||||
if (!subfieldDescription && topic.subfield_description) {
|
||||
subfieldDescription = topic.subfield_description;
|
||||
}
|
||||
|
||||
if (!fieldId && topic.field_id) {
|
||||
fieldId = topic.field_id;
|
||||
}
|
||||
|
||||
if (!fieldName && topic.field_name) {
|
||||
fieldName = topic.field_name;
|
||||
}
|
||||
|
||||
if (!fieldDescription && topic.field_description) {
|
||||
fieldDescription = topic.field_description;
|
||||
}
|
||||
|
||||
if (!domainId && topic.domain_id) {
|
||||
domainId = topic.domain_id;
|
||||
}
|
||||
|
||||
if (!domainName && topic.domain_name) {
|
||||
domainName = topic.domain_name;
|
||||
}
|
||||
|
||||
if (!domainDescription && topic.domain_description) {
|
||||
domainDescription = topic.domain_description;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -670,6 +948,15 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
name: primaryTopicName,
|
||||
count: count > 0 ? count : primaryTopic.count,
|
||||
description,
|
||||
subfield_id: subfieldId,
|
||||
subfield_name: subfieldName,
|
||||
subfield_description: subfieldDescription,
|
||||
field_id: fieldId,
|
||||
field_name: fieldName,
|
||||
field_description: fieldDescription,
|
||||
domain_id: domainId,
|
||||
domain_name: domainName,
|
||||
domain_description: domainDescription,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -681,6 +968,15 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
const originalNames = new Map<string, string>();
|
||||
const ids = new Map<string, string>();
|
||||
const descriptions = new Map<string, string>();
|
||||
const subfieldIds = new Map<string, string>();
|
||||
const subfieldNames = new Map<string, string>();
|
||||
const subfieldDescriptions = new Map<string, string>();
|
||||
const fieldIds = new Map<string, string>();
|
||||
const fieldNames = new Map<string, string>();
|
||||
const fieldDescriptions = new Map<string, string>();
|
||||
const domainIds = new Map<string, string>();
|
||||
const domainNames = new Map<string, string>();
|
||||
const domainDescriptions = new Map<string, string>();
|
||||
|
||||
for (const year of years) {
|
||||
for (const topic of year.topics ?? []) {
|
||||
@@ -700,6 +996,42 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
descriptions.set(normalizedName, topic.description);
|
||||
}
|
||||
|
||||
if (topic.subfield_id) {
|
||||
subfieldIds.set(normalizedName, topic.subfield_id);
|
||||
}
|
||||
|
||||
if (topic.subfield_name) {
|
||||
subfieldNames.set(normalizedName, topic.subfield_name);
|
||||
}
|
||||
|
||||
if (topic.subfield_description) {
|
||||
subfieldDescriptions.set(normalizedName, topic.subfield_description);
|
||||
}
|
||||
|
||||
if (topic.field_id) {
|
||||
fieldIds.set(normalizedName, topic.field_id);
|
||||
}
|
||||
|
||||
if (topic.field_name) {
|
||||
fieldNames.set(normalizedName, topic.field_name);
|
||||
}
|
||||
|
||||
if (topic.field_description) {
|
||||
fieldDescriptions.set(normalizedName, topic.field_description);
|
||||
}
|
||||
|
||||
if (topic.domain_id) {
|
||||
domainIds.set(normalizedName, topic.domain_id);
|
||||
}
|
||||
|
||||
if (topic.domain_name) {
|
||||
domainNames.set(normalizedName, topic.domain_name);
|
||||
}
|
||||
|
||||
if (topic.domain_description) {
|
||||
domainDescriptions.set(normalizedName, topic.domain_description);
|
||||
}
|
||||
|
||||
counts.set(
|
||||
normalizedName,
|
||||
(counts.get(normalizedName) ?? 0) + topic.count,
|
||||
@@ -713,6 +1045,15 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
name: originalNames.get(normalizedName) ?? normalizedName,
|
||||
count,
|
||||
description: descriptions.get(normalizedName),
|
||||
subfield_id: subfieldIds.get(normalizedName),
|
||||
subfield_name: subfieldNames.get(normalizedName),
|
||||
subfield_description: subfieldDescriptions.get(normalizedName),
|
||||
field_id: fieldIds.get(normalizedName),
|
||||
field_name: fieldNames.get(normalizedName),
|
||||
field_description: fieldDescriptions.get(normalizedName),
|
||||
domain_id: domainIds.get(normalizedName),
|
||||
domain_name: domainNames.get(normalizedName),
|
||||
domain_description: domainDescriptions.get(normalizedName),
|
||||
}))
|
||||
.sort((left, right) => {
|
||||
if (right.count !== left.count) {
|
||||
|
||||
@@ -9,8 +9,12 @@
|
||||
[viewMode]="timelineViewMode"
|
||||
[startYear]="timelineStartYear"
|
||||
[endYear]="timelineEndYear"
|
||||
[subfieldLegendVisible]="timelineLegendVisible"
|
||||
[subfieldLegendExpanded]="timelineLegendExpanded"
|
||||
(viewModeChange)="onTimelineViewModeChange($event)"
|
||||
(yearRangeChange)="onTimelineYearRangeChange($event)"
|
||||
(subfieldLegendVisibleChange)="onTimelineLegendVisibleChange($event)"
|
||||
(subfieldLegendExpandedChange)="onTimelineLegendExpandedChange($event)"
|
||||
(topicSelect)="onTimelineTopicSelect($event)"
|
||||
(yearSelect)="onTimelineYearSelect($event)"
|
||||
(loadEarlierYears)="onTimelineLoadEarlierYears()">
|
||||
|
||||
@@ -28,6 +28,10 @@ export class PersonOverviewComponent implements OnInit {
|
||||
private static readonly timelineViewQueryParam = 'timeline_view';
|
||||
private static readonly timelineStartYearQueryParam = 'timeline_start_year';
|
||||
private static readonly timelineEndYearQueryParam = 'timeline_end_year';
|
||||
private static readonly timelineLegendVisibleQueryParam =
|
||||
'timeline_legend_visible';
|
||||
private static readonly timelineLegendExpandedQueryParam =
|
||||
'timeline_legend_expanded';
|
||||
private static readonly timelineTopicCountLimit = 4;
|
||||
private static readonly initialTimelineTargetPublications = 250;
|
||||
|
||||
@@ -49,6 +53,8 @@ export class PersonOverviewComponent implements OnInit {
|
||||
timelineViewMode: TimelineViewMode = 'years';
|
||||
timelineStartYear: number | undefined;
|
||||
timelineEndYear: number | undefined;
|
||||
timelineLegendVisible = true;
|
||||
timelineLegendExpanded = false;
|
||||
|
||||
wordCloudOptions: EChartsOption | null = null;
|
||||
loadingWordCloud = false;
|
||||
@@ -84,6 +90,18 @@ export class PersonOverviewComponent implements OnInit {
|
||||
this.timelineEndYear = this.parseOptionalYear(
|
||||
queryParams.get(PersonOverviewComponent.timelineEndYearQueryParam),
|
||||
);
|
||||
this.timelineLegendVisible = this.parseBooleanQueryParam(
|
||||
queryParams.get(
|
||||
PersonOverviewComponent.timelineLegendVisibleQueryParam,
|
||||
),
|
||||
true,
|
||||
);
|
||||
this.timelineLegendExpanded = this.parseBooleanQueryParam(
|
||||
queryParams.get(
|
||||
PersonOverviewComponent.timelineLegendExpandedQueryParam,
|
||||
),
|
||||
false,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -112,6 +130,32 @@ export class PersonOverviewComponent implements OnInit {
|
||||
);
|
||||
}
|
||||
|
||||
onTimelineLegendVisibleChange(visible: boolean): void {
|
||||
this.timelineLegendVisible = visible;
|
||||
|
||||
this.updateTimelineQueryParams(
|
||||
{
|
||||
[PersonOverviewComponent.timelineLegendVisibleQueryParam]: visible
|
||||
? null
|
||||
: 'false',
|
||||
},
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
onTimelineLegendExpandedChange(expanded: boolean): void {
|
||||
this.timelineLegendExpanded = expanded;
|
||||
|
||||
this.updateTimelineQueryParams(
|
||||
{
|
||||
[PersonOverviewComponent.timelineLegendExpandedQueryParam]: expanded
|
||||
? 'true'
|
||||
: null,
|
||||
},
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
onTimelineTopicSelect(selection: TimelineTopicSelection): void {
|
||||
if (!selection.topic.id) {
|
||||
return;
|
||||
@@ -436,6 +480,15 @@ export class PersonOverviewComponent implements OnInit {
|
||||
name: topic.name,
|
||||
count: topic.count ?? 0,
|
||||
description: topic.description ?? undefined,
|
||||
subfield_id: topic.subfield_id ?? undefined,
|
||||
subfield_name: topic.subfield_name ?? undefined,
|
||||
subfield_description: topic.subfield_description ?? undefined,
|
||||
field_id: topic.field_id ?? undefined,
|
||||
field_name: topic.field_name ?? undefined,
|
||||
field_description: topic.field_description ?? undefined,
|
||||
domain_id: topic.domain_id ?? undefined,
|
||||
domain_name: topic.domain_name ?? undefined,
|
||||
domain_description: topic.domain_description ?? undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -493,8 +546,27 @@ export class PersonOverviewComponent implements OnInit {
|
||||
return year;
|
||||
}
|
||||
|
||||
private parseBooleanQueryParam(
|
||||
value: string | null,
|
||||
fallback: boolean,
|
||||
): boolean {
|
||||
if (value === null) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
if (value === 'true' || value === '1') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (value === 'false' || value === '0') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
private updateTimelineQueryParams(
|
||||
queryParams: Record<string, string | number>,
|
||||
queryParams: Record<string, string | number | null>,
|
||||
replaceUrl: boolean,
|
||||
): void {
|
||||
void this.router.navigate([], {
|
||||
|
||||
@@ -5,40 +5,27 @@
|
||||
</div>
|
||||
<mat-card appearance="outlined">
|
||||
<mat-card-content>
|
||||
<mat-form-field style="width: 100%">
|
||||
<mat-label>Suche nach Titel</mat-label>
|
||||
<input
|
||||
matInput
|
||||
type="search"
|
||||
[debounceTime]="300"
|
||||
[(debouncedValue)]="urlSearchTerm"
|
||||
(debouncedValueChange)="handleSearchTermChange($event)" />
|
||||
<mat-icon matPrefix>search</mat-icon>
|
||||
<button matIconButton matSuffix (click)="clearSearchTerm()">
|
||||
<mat-icon>clear</mat-icon>
|
||||
</button>
|
||||
</mat-form-field>
|
||||
<app-query-param-input label="Suche nach Titel" queryParamKey="search" />
|
||||
<mat-tab-group>
|
||||
<mat-tab label="DFG">
|
||||
<app-data-table
|
||||
[columns]="dfgProjectColumns"
|
||||
[data]="dfgProjectData"
|
||||
[detailTemplate]="dfgProjectDetailRowTmp"
|
||||
[activeSortKey]="urlSortKey()"
|
||||
[sortDirection]="urlSortDirection()"
|
||||
(sortChange)="handleSortChange($event)" />
|
||||
queryParamSortKey="sort_by"
|
||||
queryParamSortDirectionKey="sort_direction" />
|
||||
</mat-tab>
|
||||
<mat-tab label="EU">
|
||||
<app-data-table
|
||||
[columns]="personCordisEuProjectColumns"
|
||||
[data]="personCordisEuProjectData" />
|
||||
[data]="personCordisEuProjectData"
|
||||
queryParamSortKey="sort_by"
|
||||
queryParamSortDirectionKey="sort_direction" />
|
||||
</mat-tab>
|
||||
</mat-tab-group>
|
||||
<mat-paginator
|
||||
[length]="this.pageTotal()"
|
||||
[pageSize]="this.pageSize()"
|
||||
[pageIndex]="this.pageIndex()"
|
||||
(page)="handlePageChange($event)" />
|
||||
<app-query-param-paginator
|
||||
[total]="this.pageTotal()"
|
||||
[pageSizeOptions]="[10]" />
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
effect,
|
||||
input,
|
||||
OnInit,
|
||||
signal,
|
||||
TemplateRef,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
@@ -24,12 +23,10 @@ import { MatCardModule } from '@angular/material/card';
|
||||
import { MatTabsModule } from '@angular/material/tabs';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { DebounceDirective } from '../../directives/debounce.directive';
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
|
||||
import { Sort, SortDirection } from '@angular/material/sort';
|
||||
import { Router, RouterModule } from '@angular/router';
|
||||
import { CurrencyPipe, DatePipe } from '@angular/common';
|
||||
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
|
||||
import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-person-projects',
|
||||
@@ -41,11 +38,11 @@ import { CurrencyPipe, DatePipe } from '@angular/common';
|
||||
MatTabsModule,
|
||||
MatFormFieldModule,
|
||||
MatInputModule,
|
||||
DebounceDirective,
|
||||
MatPaginatorModule,
|
||||
RouterModule,
|
||||
DatePipe,
|
||||
CurrencyPipe,
|
||||
QueryParamPaginatorComponent,
|
||||
QueryParamInputComponent,
|
||||
],
|
||||
templateUrl: './person-projects.component.html',
|
||||
styleUrl: './person-projects.component.scss',
|
||||
@@ -82,55 +79,19 @@ export class PersonProjectsComponent implements OnInit {
|
||||
'euProjectsActionsTmp',
|
||||
);
|
||||
|
||||
urlSearchTerm = signal<string>('');
|
||||
urlSortKey = signal<string>('');
|
||||
urlSortDirection = signal<SortDirection>('');
|
||||
|
||||
readonly pageTotal = computed(() => {
|
||||
return this.dfgProjectPage()?.total ?? 0;
|
||||
});
|
||||
|
||||
readonly pageSize = computed(() => {
|
||||
return this.dfgProjectPage()?.size ?? 10;
|
||||
});
|
||||
|
||||
readonly pageIndex = computed(() => {
|
||||
return this.dfgProjectPage()?.page ?? 0;
|
||||
});
|
||||
|
||||
constructor(
|
||||
private readonly router: Router,
|
||||
private readonly activatedRoute: ActivatedRoute,
|
||||
) {
|
||||
this.activatedRoute.queryParamMap
|
||||
.pipe(takeUntilDestroyed())
|
||||
.subscribe((params) => {
|
||||
this.urlSearchTerm.set(params.get('search') || '');
|
||||
});
|
||||
|
||||
constructor(private readonly router: Router) {
|
||||
effect(() => {
|
||||
this.dfgProjectData = this.dfgProjectPage().elements || [];
|
||||
});
|
||||
|
||||
effect(() => {
|
||||
console.log(
|
||||
'Updating personCordisEuProjectData with',
|
||||
this.personCordisEuProjectPage(),
|
||||
);
|
||||
|
||||
this.personCordisEuProjectData =
|
||||
this.personCordisEuProjectPage().elements || [];
|
||||
});
|
||||
|
||||
effect(() => {
|
||||
const searchTerm = this.urlSearchTerm();
|
||||
if (searchTerm) {
|
||||
this.router.navigate([], {
|
||||
queryParams: { search: searchTerm, page: 0, size: this.pageSize() },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -196,32 +157,4 @@ export class PersonProjectsComponent implements OnInit {
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
handleSearchTermChange(newTerm: string): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: { search: newTerm },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
clearSearchTerm(): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: { search: null },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
handlePageChange(event: PageEvent): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: { page: event.pageIndex, size: event.pageSize },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
handleSortChange(event: Sort): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: { sort_by: event.active, sort_direction: event.direction },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,19 @@
|
||||
}
|
||||
</span>
|
||||
}
|
||||
@if (displayCareerStage()) {
|
||||
<div class="career-stage-line">
|
||||
<span class="career-stage-label">Career Stage:</span>
|
||||
<span
|
||||
class="career-stage-chip"
|
||||
[matTooltip]="careerStageTooltip()"
|
||||
matTooltipPosition="right"
|
||||
matTooltipClass="career-stage-tooltip"
|
||||
[matTooltipShowDelay]="250">
|
||||
{{ displayCareerStage() }}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<div class="profile-contact">
|
||||
<div>
|
||||
|
||||
@@ -85,6 +85,33 @@
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.career-stage-line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.career-stage-label {
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
.career-stage-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 24px;
|
||||
padding: 2px 10px;
|
||||
border: 1px solid var(--sg-border);
|
||||
border-radius: 999px;
|
||||
background: var(--sg-surface-muted);
|
||||
color: var(--sg-primary);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
line-height: 1.2;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.profile-contact {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatProgressSpinner } from '@angular/material/progress-spinner';
|
||||
import { MatTabsModule } from '@angular/material/tabs';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import {
|
||||
ActivatedRoute,
|
||||
ResolveEnd,
|
||||
@@ -19,7 +20,7 @@ import {
|
||||
import { of, switchMap, finalize, map, catchError } from 'rxjs';
|
||||
|
||||
import { PersonInterestingComponent } from '../person-interesting/person-interesting.component';
|
||||
import { PersonsService, WorksService } from '../../api';
|
||||
import { WorksService } from '../../api';
|
||||
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
||||
import { PersonBioResolved } from '../../resolvers/person-bio.resolver';
|
||||
|
||||
@@ -28,6 +29,7 @@ import { PersonBioResolved } from '../../resolvers/person-bio.resolver';
|
||||
imports: [
|
||||
MatIconModule,
|
||||
MatTabsModule,
|
||||
MatTooltipModule,
|
||||
PersonInterestingComponent,
|
||||
RouterOutlet,
|
||||
RouterModule,
|
||||
@@ -41,7 +43,6 @@ export class PersonComponent {
|
||||
private readonly router = inject(Router);
|
||||
private readonly activatedRoute = inject(ActivatedRoute);
|
||||
|
||||
private readonly personsApi = inject(PersonsService);
|
||||
private readonly worksApi = inject(WorksService);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
@@ -62,9 +63,9 @@ export class PersonComponent {
|
||||
const event = this.routerEvents();
|
||||
|
||||
if (
|
||||
!(event instanceof RouterEvent) || // not a router event
|
||||
!this.isResolverEvent(event) || // not a resolver event
|
||||
!this.isNetworkRouterEvent(event) // not navigating to network route
|
||||
!(event instanceof RouterEvent) ||
|
||||
!this.isResolverEvent(event) ||
|
||||
!this.isNetworkRouterEvent(event)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -84,7 +85,6 @@ export class PersonComponent {
|
||||
return event.url.startsWith(`/person/${this.authorId()}/network`);
|
||||
}
|
||||
|
||||
// loading states
|
||||
readonly isPersonLoading = signal(false);
|
||||
readonly isBioLoading = signal(false);
|
||||
|
||||
@@ -111,6 +111,7 @@ export class PersonComponent {
|
||||
),
|
||||
{ initialValue: null },
|
||||
);
|
||||
|
||||
readonly displayName = computed(
|
||||
() => this.person()?.display_name ?? 'Unbekannte Person',
|
||||
);
|
||||
@@ -147,6 +148,36 @@ export class PersonComponent {
|
||||
readonly h_index = computed(
|
||||
() => this.person()?.summary_stats?.h_index ?? null,
|
||||
);
|
||||
readonly displayCareerStage = computed(() => {
|
||||
const stage = this.person()?.career_metrics?.career_stage;
|
||||
|
||||
if (!stage || stage === 'unknown') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return stage;
|
||||
});
|
||||
readonly careerStageTooltip = computed(() => {
|
||||
const stage = this.displayCareerStage();
|
||||
if (!stage) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const activeYears = this.person()?.career_metrics?.active_years ?? '-';
|
||||
|
||||
return [
|
||||
`Aktuell: ${stage.replace(' Researcher', '')}`,
|
||||
`Aktive Publikationsjahre: ${activeYears}`,
|
||||
'',
|
||||
'Einteilung:',
|
||||
'Early: 1\u20134 aktive Publikationsjahre',
|
||||
'Emerging: 5\u20139 aktive Publikationsjahre',
|
||||
'Established: 10\u201314 aktive Publikationsjahre',
|
||||
'Senior: ab 15 aktiven Publikationsjahren',
|
||||
'',
|
||||
'Diese Einschätzung basiert ausschließlich auf OpenAlex-Publikationsdaten und ist kein offizieller akademischer Status.',
|
||||
].join('\n');
|
||||
});
|
||||
readonly orcid = computed(() => {
|
||||
const rawOrcid = this.getId('orcid');
|
||||
if (!rawOrcid) {
|
||||
@@ -173,6 +204,7 @@ export class PersonComponent {
|
||||
),
|
||||
{ initialValue: [] },
|
||||
);
|
||||
|
||||
links = [
|
||||
{ label: 'Übersicht', path: 'overview', disabled: false },
|
||||
{
|
||||
|
||||
@@ -4,19 +4,11 @@
|
||||
<mat-divider />
|
||||
|
||||
<div style="padding: 0 1rem">
|
||||
<mat-form-field style="width: 100%">
|
||||
<mat-label>Suche nach Namen</mat-label>
|
||||
<input
|
||||
matInput
|
||||
type="search"
|
||||
[debounceTime]="300"
|
||||
[(debouncedValue)]="urlSearchTerm"
|
||||
(debouncedValueChange)="handleSearchTermChange($event)" />
|
||||
<mat-icon matPrefix>search</mat-icon>
|
||||
<button matIconButton matSuffix (click)="clearSearchTerm()">
|
||||
<mat-icon>clear</mat-icon>
|
||||
</button>
|
||||
</mat-form-field>
|
||||
<app-query-param-input
|
||||
label="Suche nach Namen"
|
||||
[debounceTime]="400"
|
||||
queryParamKey="search">
|
||||
</app-query-param-input>
|
||||
|
||||
<div
|
||||
style="
|
||||
@@ -34,16 +26,13 @@
|
||||
</mat-chip-listbox>
|
||||
|
||||
<div class="sorting">
|
||||
<select (change)="handleSortFieldChange($event)" [value]="urlSortBy()">
|
||||
<option value="title">Name</option>
|
||||
</select>
|
||||
<app-query-param-selector
|
||||
[options]="sortingOptions"
|
||||
queryParamKey="sort_by" />
|
||||
|
||||
<select
|
||||
(change)="handleSortOrderChange($event)"
|
||||
[value]="urlSortingOrder()">
|
||||
<option value="desc">Absteigend</option>
|
||||
<option value="asc">Aufsteigend</option>
|
||||
</select>
|
||||
<app-query-param-selector
|
||||
[options]="sortingDirectionOptions"
|
||||
queryParamKey="sorting_order" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -102,11 +91,7 @@
|
||||
|
||||
<mat-divider />
|
||||
|
||||
<mat-paginator
|
||||
[length]="fundingProjectPageValue.total"
|
||||
[pageSize]="fundingProjectPageValue.size"
|
||||
[pageSizeOptions]="[10, 20, 50]"
|
||||
[pageIndex]="fundingProjectPageValue.page"
|
||||
(page)="handlePageChange($event)">
|
||||
</mat-paginator>
|
||||
<app-query-param-paginator
|
||||
[total]="fundingProjectPageValue.total || 0"
|
||||
[pageSizeOptions]="[10, 25, 50]" />
|
||||
</div>
|
||||
|
||||
@@ -25,22 +25,10 @@
|
||||
.cards {
|
||||
display: grid;
|
||||
gap: 1.5rem;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
grid-template-columns: repeat(auto-fit, minmax(380px, 1fr));
|
||||
padding: 0 1rem;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.cards {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.cards {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
mat-paginator {
|
||||
background-color: var(--sg-background);
|
||||
}
|
||||
|
||||
@@ -1,33 +1,34 @@
|
||||
import { Component, effect, input, signal } from '@angular/core';
|
||||
import { Component, input, signal } from '@angular/core';
|
||||
import { FundingProject, FundingProjectPage, ProjectType } from '../../api';
|
||||
import { MatDividerModule } from '@angular/material/divider';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { DebounceDirective } from '../../directives/debounce.directive';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
import { MatPaginator, PageEvent } from '@angular/material/paginator';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { DatePipe, UpperCasePipe } from '@angular/common';
|
||||
import { MatChipListboxChange, MatChipsModule } from '@angular/material/chips';
|
||||
import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component';
|
||||
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
|
||||
import {
|
||||
QueryParamSelectorComponent,
|
||||
SelectorOption,
|
||||
} from '../../shared/ui/query-param-selector/query-param-selector.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-projects',
|
||||
imports: [
|
||||
MatDividerModule,
|
||||
MatFormFieldModule,
|
||||
DebounceDirective,
|
||||
MatIconModule,
|
||||
MatCardModule,
|
||||
RouterModule,
|
||||
MatPaginator,
|
||||
MatInputModule,
|
||||
MatButtonModule,
|
||||
UpperCasePipe,
|
||||
DatePipe,
|
||||
MatChipsModule,
|
||||
QueryParamInputComponent,
|
||||
QueryParamPaginatorComponent,
|
||||
QueryParamSelectorComponent,
|
||||
],
|
||||
templateUrl: './projects.component.html',
|
||||
styleUrl: './projects.component.scss',
|
||||
@@ -35,11 +36,14 @@ import { MatChipListboxChange, MatChipsModule } from '@angular/material/chips';
|
||||
export class ProjectsComponent {
|
||||
fundingProjectPage = input.required<FundingProjectPage>();
|
||||
|
||||
urlSearchTerm = signal<string>('');
|
||||
urlSortBy = signal<string>('relevance');
|
||||
urlSortingOrder = signal<string>('desc');
|
||||
urlChips = signal<ProjectType[]>(['eu', 'bund', 'dfg']);
|
||||
|
||||
sortingOptions: SelectorOption[] = [{ value: 'title', display_name: 'Name' }];
|
||||
sortingDirectionOptions: SelectorOption[] = [
|
||||
{ value: 'asc', display_name: 'Aufsteigend' },
|
||||
{ value: 'desc', display_name: 'Absteigend' },
|
||||
];
|
||||
|
||||
constructor(
|
||||
private readonly activatedRoute: ActivatedRoute,
|
||||
private readonly router: Router,
|
||||
@@ -47,60 +51,10 @@ export class ProjectsComponent {
|
||||
this.activatedRoute.queryParams
|
||||
.pipe(takeUntilDestroyed())
|
||||
.subscribe((params) => {
|
||||
this.urlSearchTerm.set(params['search'] || '');
|
||||
this.urlSortBy.set(params['sort_by'] || 'relevance');
|
||||
this.urlSortingOrder.set(params['sorting_order'] || 'desc');
|
||||
this.urlChips.set(
|
||||
(params['selected_project_types'] || 'eu,bund,dfg').split(','),
|
||||
);
|
||||
});
|
||||
|
||||
effect(() => {
|
||||
const searchTerm = this.urlSearchTerm();
|
||||
this.router.navigate([], {
|
||||
queryParams: { search: searchTerm },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
handleSearchTermChange(newTerm: string): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: { search: newTerm, page: 0, size: 10 },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
clearSearchTerm(): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: { search: null },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
handlePageChange(event: PageEvent): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: { page: event.pageIndex, size: event.pageSize },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
handleSortFieldChange(event: Event): void {
|
||||
const selectElement = event.target as HTMLSelectElement;
|
||||
const sortField = selectElement.value;
|
||||
this.router.navigate([], {
|
||||
queryParams: { sort_by: sortField },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
handleSortOrderChange(event: Event): void {
|
||||
const selectElement = event.target as HTMLSelectElement;
|
||||
const sortOrder = selectElement.value;
|
||||
this.router.navigate([], {
|
||||
queryParams: { sorting_order: sortOrder },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
handleChipBoxChange(change: MatChipListboxChange): void {
|
||||
|
||||
@@ -1,11 +1,44 @@
|
||||
<div class="hierarchy-container">
|
||||
@if (searchQuery()) {
|
||||
<div
|
||||
class="search-mode-selector"
|
||||
style="
|
||||
margin-bottom: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
border-bottom: 1px solid rgba(0, 0, 0, 0.08);
|
||||
padding-bottom: 8px;
|
||||
">
|
||||
<span
|
||||
style="
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: var(--sg-text);
|
||||
opacity: 0.8;
|
||||
"
|
||||
>Modus:</span
|
||||
>
|
||||
<mat-radio-group
|
||||
[value]="searchType()"
|
||||
(change)="onSearchTypeChange($event.value)"
|
||||
style="display: flex; gap: 16px">
|
||||
<mat-radio-button value="hybrid">
|
||||
<span style="font-size: 12px; color: var(--sg-text)">Hybrid</span>
|
||||
</mat-radio-button>
|
||||
<mat-radio-button value="semantic">
|
||||
<span style="font-size: 12px; color: var(--sg-text)">Semantisch</span>
|
||||
</mat-radio-button>
|
||||
</mat-radio-group>
|
||||
</div>
|
||||
}
|
||||
@if (loading()) {
|
||||
<div class="loading-state">
|
||||
<mat-spinner diameter="24"></mat-spinner>
|
||||
<span>Lade Themen...</span>
|
||||
</div>
|
||||
} @else {
|
||||
@if (searchQuery) {
|
||||
@if (searchQuery()) {
|
||||
<!-- Flat Search Results Mode -->
|
||||
<div class="search-results">
|
||||
<span class="results-meta"
|
||||
@@ -15,8 +48,13 @@
|
||||
@for (topic of filteredFlatTopics; track topic.id) {
|
||||
<div class="flat-row">
|
||||
<mat-checkbox
|
||||
[checked]="selectedTopics.has(topic.name)"
|
||||
(change)="toggleTopic(topic.name)">
|
||||
#tooltip="matTooltip"
|
||||
[checked]="selectedTopics().has(topic.name)"
|
||||
(change)="toggleTopic(topic.name)"
|
||||
[matTooltip]="topic.name"
|
||||
matTooltipPosition="above"
|
||||
(focusin)="tooltip.show()"
|
||||
(focusout)="tooltip.hide()">
|
||||
<span class="topic-name">{{ topic.name }}</span>
|
||||
</mat-checkbox>
|
||||
<span class="topic-path" [title]="topic.path">{{
|
||||
@@ -103,13 +141,18 @@
|
||||
<!-- LEVEL 4: Topic Checkbox -->
|
||||
<div class="tree-leaf topic-node">
|
||||
<mat-checkbox
|
||||
[checked]="selectedTopics.has(topic.name)"
|
||||
(change)="toggleTopic(topic.name)">
|
||||
<span
|
||||
class="topic-label"
|
||||
[title]="topic.name"
|
||||
>{{ topic.name }}</span
|
||||
>
|
||||
#tooltip="matTooltip"
|
||||
[checked]="
|
||||
selectedTopics().has(topic.name)
|
||||
"
|
||||
(change)="toggleTopic(topic.name)"
|
||||
[matTooltip]="topic.name"
|
||||
matTooltipPosition="above"
|
||||
(focusin)="tooltip.show()"
|
||||
(focusout)="tooltip.hide()">
|
||||
<span class="topic-label">{{
|
||||
topic.name
|
||||
}}</span>
|
||||
</mat-checkbox>
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -2,11 +2,13 @@
|
||||
width: 100%;
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
border: 1px solid var(--sg-border);
|
||||
border-radius: var(--sg-radius-sm);
|
||||
background: var(--sg-background);
|
||||
padding: 4px;
|
||||
padding: 4px 8px 4px 4px;
|
||||
margin-top: 4px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.loading-state {
|
||||
@@ -55,6 +57,11 @@
|
||||
font-size: 12px;
|
||||
color: var(--sg-text);
|
||||
font-weight: 500;
|
||||
display: block;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.topic-path {
|
||||
@@ -92,7 +99,7 @@
|
||||
width: 100%;
|
||||
background: transparent;
|
||||
border: none;
|
||||
padding: 4px 6px;
|
||||
padding: 4px;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
@@ -122,6 +129,7 @@
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,37 +166,62 @@
|
||||
}
|
||||
|
||||
.domain-children {
|
||||
padding-left: 12px;
|
||||
padding-left: 10px;
|
||||
border-left: 1px solid var(--sg-border-soft);
|
||||
margin-left: 12px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.field-children {
|
||||
padding-left: 14px;
|
||||
padding-left: 10px;
|
||||
border-left: 1px solid var(--sg-border-soft);
|
||||
margin-left: 14px;
|
||||
margin-left: 12px;
|
||||
}
|
||||
|
||||
.subfield-children {
|
||||
padding-left: 14px;
|
||||
padding-left: 10px;
|
||||
border-left: 1px dashed var(--sg-border-soft);
|
||||
margin-left: 14px;
|
||||
margin-left: 12px;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.tree-leaf {
|
||||
padding: 2px 4px;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.topic-node {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
|
||||
.topic-label {
|
||||
font-size: 11px;
|
||||
color: var(--sg-text);
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
overflow: hidden;
|
||||
display: block;
|
||||
max-width: 190px;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
mat-checkbox {
|
||||
display: block !important;
|
||||
width: 100% !important;
|
||||
|
||||
::ng-deep {
|
||||
.mdc-form-field {
|
||||
width: 100% !important;
|
||||
display: flex !important;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.mdc-label {
|
||||
flex: 1 !important;
|
||||
min-width: 0 !important;
|
||||
overflow: hidden;
|
||||
padding-left: 8px !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
import {
|
||||
Component,
|
||||
Input,
|
||||
Output,
|
||||
EventEmitter,
|
||||
OnInit,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { Component, input, model, output, OnInit, signal } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||
import { MatRadioModule } from '@angular/material/radio';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { TopicsService } from '../../api/api/topics.service';
|
||||
import { Subject, of } from 'rxjs';
|
||||
import { combineLatest, of } from 'rxjs';
|
||||
import { toObservable } from '@angular/core/rxjs-interop';
|
||||
import {
|
||||
debounceTime,
|
||||
distinctUntilChanged,
|
||||
@@ -53,28 +49,18 @@ interface FlatTopic {
|
||||
MatCheckboxModule,
|
||||
MatIconModule,
|
||||
MatProgressSpinnerModule,
|
||||
MatRadioModule,
|
||||
MatTooltipModule,
|
||||
],
|
||||
templateUrl: './topic-hierarchy.component.html',
|
||||
styleUrl: './topic-hierarchy.component.scss',
|
||||
})
|
||||
export class TopicHierarchyComponent implements OnInit {
|
||||
@Input() selectedTopics: Set<string> = new Set<string>();
|
||||
selectedTopics = input<Set<string>>(new Set<string>());
|
||||
searchQuery = input<string>('');
|
||||
searchType = model<'hybrid' | 'semantic'>('hybrid');
|
||||
|
||||
private _searchQuery = '';
|
||||
@Input()
|
||||
set searchQuery(value: string) {
|
||||
if (value.length < 2) {
|
||||
this._searchQuery = '';
|
||||
} else {
|
||||
this._searchQuery = value;
|
||||
}
|
||||
this.filterFlatTopics();
|
||||
}
|
||||
get searchQuery(): string {
|
||||
return this._searchQuery;
|
||||
}
|
||||
|
||||
@Output() selectionChange = new EventEmitter<Set<string>>();
|
||||
selectionChange = output<Set<string>>();
|
||||
|
||||
domains: DomainNode[] = [];
|
||||
flatTopics: FlatTopic[] = [];
|
||||
@@ -86,32 +72,37 @@ export class TopicHierarchyComponent implements OnInit {
|
||||
expandedFields = new Set<string>();
|
||||
expandedSubfields = new Set<string>();
|
||||
|
||||
private readonly searchSubject = new Subject<string>();
|
||||
|
||||
constructor(private topicsService: TopicsService) {
|
||||
this.searchSubject
|
||||
combineLatest([
|
||||
toObservable(this.searchQuery),
|
||||
toObservable(this.searchType),
|
||||
])
|
||||
.pipe(
|
||||
debounceTime(300),
|
||||
distinctUntilChanged(),
|
||||
switchMap((query) => {
|
||||
if (!query) {
|
||||
distinctUntilChanged(
|
||||
(prev, curr) => prev[0] === curr[0] && prev[1] === curr[1],
|
||||
),
|
||||
switchMap(([query, searchType]) => {
|
||||
if (!query || query.length < 2) {
|
||||
this.filteredFlatTopics = [];
|
||||
return of({ results: [] });
|
||||
}
|
||||
this.loading.set(true);
|
||||
return this.topicsService.vectorSearchTopics(query, 50).pipe(
|
||||
catchError((err) => {
|
||||
console.error('Error in semantic topic search:', err);
|
||||
// Fallback to local filtering
|
||||
const q = query.toLowerCase();
|
||||
this.filteredFlatTopics = this.flatTopics.filter(
|
||||
(t) =>
|
||||
t.name.toLowerCase().includes(q) ||
|
||||
t.path.toLowerCase().includes(q),
|
||||
);
|
||||
return of({ results: [] });
|
||||
}),
|
||||
);
|
||||
return this.topicsService
|
||||
.vectorSearchTopics(query, 50, searchType)
|
||||
.pipe(
|
||||
catchError((err) => {
|
||||
console.error('Error in semantic topic search:', err);
|
||||
// Fallback to local filtering
|
||||
const q = query.toLowerCase();
|
||||
this.filteredFlatTopics = this.flatTopics.filter(
|
||||
(t) =>
|
||||
t.name.toLowerCase().includes(q) ||
|
||||
t.path.toLowerCase().includes(q),
|
||||
);
|
||||
return of({ results: [] });
|
||||
}),
|
||||
);
|
||||
}),
|
||||
)
|
||||
.subscribe((response) => {
|
||||
@@ -167,19 +158,14 @@ export class TopicHierarchyComponent implements OnInit {
|
||||
});
|
||||
});
|
||||
this.flatTopics = flat;
|
||||
this.filterFlatTopics();
|
||||
}
|
||||
|
||||
filterFlatTopics(): void {
|
||||
if (!this.searchQuery) {
|
||||
this.filteredFlatTopics = [];
|
||||
return;
|
||||
}
|
||||
this.searchSubject.next(this.searchQuery);
|
||||
onSearchTypeChange(type: 'hybrid' | 'semantic'): void {
|
||||
this.searchType.set(type);
|
||||
}
|
||||
|
||||
toggleTopic(name: string): void {
|
||||
const nextSelection = new Set(this.selectedTopics);
|
||||
const nextSelection = new Set(this.selectedTopics());
|
||||
if (nextSelection.has(name)) {
|
||||
nextSelection.delete(name);
|
||||
} else {
|
||||
|
||||
@@ -8,6 +8,11 @@ import {
|
||||
WorksFilterProperties,
|
||||
} from '../api';
|
||||
|
||||
const DEFAULT_MIN_CONTRIBUTORS = 2;
|
||||
const DEFAULT_MAX_CONTRIBUTORS = 10;
|
||||
const DEFAULT_MIN_COLLABORATIONS = 1;
|
||||
const DEFAULT_MAX_COLLABORATIONS = 100;
|
||||
|
||||
export const collaborationNetworkResolver: ResolveFn<CollaborationNetwork> = (
|
||||
route,
|
||||
state,
|
||||
@@ -38,10 +43,10 @@ export const collaborationNetworkResolver: ResolveFn<CollaborationNetwork> = (
|
||||
end_year: endYear ? Number.parseInt(endYear, 10) : undefined,
|
||||
min_contributors: minContributors
|
||||
? Number.parseInt(minContributors, 10)
|
||||
: undefined,
|
||||
: DEFAULT_MIN_CONTRIBUTORS,
|
||||
max_contributors: maxContributors
|
||||
? Number.parseInt(maxContributors, 10)
|
||||
: undefined,
|
||||
: DEFAULT_MAX_CONTRIBUTORS,
|
||||
allowed_topics: topics ? topics.split(',') : undefined,
|
||||
};
|
||||
}
|
||||
@@ -49,10 +54,10 @@ export const collaborationNetworkResolver: ResolveFn<CollaborationNetwork> = (
|
||||
authorsFilterProperties = {
|
||||
min_collaborations: minCollaborations
|
||||
? Number.parseInt(minCollaborations, 10)
|
||||
: undefined,
|
||||
: DEFAULT_MIN_COLLABORATIONS,
|
||||
max_collaborations: maxCollaborations
|
||||
? Number.parseInt(maxCollaborations, 10)
|
||||
: undefined,
|
||||
: DEFAULT_MAX_COLLABORATIONS,
|
||||
allowed_institutions: institutions ? institutions.split(',') : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,10 +7,9 @@ import {
|
||||
} from '../api';
|
||||
import { inject } from '@angular/core';
|
||||
|
||||
export const cordisEuProjectPageResolver: ResolveFn<EuOrganizationProjectSummaryPage> = (
|
||||
route,
|
||||
state,
|
||||
) => {
|
||||
export const cordisEuProjectPageResolver: ResolveFn<
|
||||
EuOrganizationProjectSummaryPage
|
||||
> = (route, state) => {
|
||||
const page = route.queryParamMap.get('page') ?? '1';
|
||||
const size = route.queryParamMap.get('size') ?? '10';
|
||||
let institutionId = route.paramMap.get('institutionId');
|
||||
|
||||
@@ -12,7 +12,7 @@ export const personListResolver: ResolveFn<CustomAuthorsListResponse> = (
|
||||
return [val];
|
||||
};
|
||||
const defaultIncludes =
|
||||
'display_name,works_count,cited_by_count,summary_stats,topics,orcid,relevance_rating,last_known_institutions,affiliations';
|
||||
'display_name,works_count,cited_by_count,summary_stats,topics,orcid,relevance_rating,last_known_institutions,affiliations,career_metrics';
|
||||
const params = route.queryParamMap;
|
||||
|
||||
const query = params.get('query') || undefined;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user