Compare commits
60
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bdf5fabd45 | ||
|
|
db604feb37 | ||
|
|
cd0e98ec5f | ||
|
|
42685ae44f | ||
|
|
9be024bb13 | ||
|
|
87b7e207e3 | ||
|
|
8eaa9c2420 | ||
|
|
87b02ed0a4 | ||
|
|
a6d30dd897 | ||
|
|
134055b8b9 | ||
|
|
be72d28bda | ||
|
|
2bfb877e77 | ||
|
|
48e33e7fe5 | ||
|
|
f469594c17 | ||
|
|
3e115619a6 | ||
|
|
13b2fb3350 | ||
|
|
d26ddb8cb4 | ||
|
|
269c1a7a55 | ||
|
|
1c6dbb540f | ||
|
|
cf9a5df4e9 | ||
|
|
d120c62576 | ||
|
|
213edf8a5f | ||
|
|
c277fcfece | ||
|
|
8efbbf1f1a | ||
|
|
9ad6d5cd8c | ||
|
|
77540e4002 | ||
|
|
fd3ceb54aa | ||
|
|
7baeab92c2 | ||
|
|
0c526be983 | ||
|
|
53f5440d01 | ||
|
|
e86a19f800 | ||
|
|
61fd920a9f | ||
|
|
7eed7e6614 | ||
|
|
e34e1fe3d5 | ||
|
|
058c92227a | ||
|
|
bf38147acc | ||
|
|
3f23845c89 | ||
|
|
52e70a5b24 | ||
|
|
d502431102 | ||
|
|
3533b994d0 | ||
|
|
5d22f4831a | ||
|
|
8130192a44 | ||
|
|
0723bb5c5b | ||
|
|
e4dbe07436 | ||
|
|
19c6574945 | ||
|
|
0b750d27e7 | ||
|
|
398ea7b56c | ||
|
|
0176eea873 | ||
|
|
b0e8c86743 | ||
|
|
03a2954c72 | ||
|
|
b9d382c78a | ||
|
|
78a8e5d919 | ||
|
|
f9f6a58ad5 | ||
|
|
5cc110174a | ||
|
|
c3ec93fba1 | ||
|
|
169b825195 | ||
|
|
e1f58d6380 | ||
|
|
1cf80ae074 | ||
|
|
8261c0a52f | ||
|
|
e76bd217ac |
@@ -38,6 +38,7 @@ def add_entry(index: str, entry: dict):
|
||||
"news_id": entry["news_id"],
|
||||
"relevant": int(entry["relevant"]),
|
||||
"authors": entry["authors"],
|
||||
"keywords": entry.get("keywords", []),
|
||||
}
|
||||
|
||||
response_data = _send_es_request("POST", endpoint, payload=document_body)
|
||||
@@ -47,6 +48,13 @@ def add_entry(index: str, entry: dict):
|
||||
|
||||
return created_id
|
||||
|
||||
def update_entry(index: str, document_id: str, partial_doc: dict):
|
||||
|
||||
encoded_document_id = quote(document_id, safe="")
|
||||
endpoint = f"{INSE_URL}/{index}/_update/{encoded_document_id}"
|
||||
|
||||
return _send_es_request("POST", endpoint, payload={"doc": partial_doc})
|
||||
|
||||
def get_entry(index: str, document_id: str) -> dict:
|
||||
|
||||
encoded_document_id = quote(document_id, safe="")
|
||||
@@ -103,4 +111,18 @@ def delete_all_entries(index: str):
|
||||
"query": {"match_all": {}}
|
||||
}
|
||||
|
||||
return _send_es_request("POST", endpoint, payload=payload)
|
||||
|
||||
def remove_field_all(index: str, field: str):
|
||||
|
||||
endpoint = f"{INSE_URL}/{index}/_update_by_query"
|
||||
|
||||
payload = {
|
||||
"query": {"exists": {"field": field}},
|
||||
"script": {
|
||||
"source": f"ctx._source.remove('{field}')",
|
||||
"lang": "painless",
|
||||
},
|
||||
}
|
||||
|
||||
return _send_es_request("POST", endpoint, payload=payload)
|
||||
@@ -23,6 +23,17 @@ SYSTEM_PROMPT_NAMES = ("""
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
""")
|
||||
|
||||
SYSTEM_PROMPT_KEYWORDS = ("""
|
||||
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
|
||||
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
|
||||
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
|
||||
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
|
||||
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
|
||||
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
|
||||
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"keywords\": [\"Schlagwort\", \"Schlagwort\"]}
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
""")
|
||||
|
||||
_client = OpenAI(
|
||||
base_url=LLM_BASE_URL,
|
||||
api_key=LLM_API_KEY,
|
||||
@@ -62,3 +73,14 @@ def extract_names(text: str) -> list[str]:
|
||||
return data.get("person", [])
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
def extract_keywords(text: str) -> list[str]:
|
||||
result = call(SYSTEM_PROMPT_KEYWORDS, text)
|
||||
if result is None:
|
||||
return []
|
||||
try:
|
||||
import json
|
||||
data = json.loads(result)
|
||||
return data.get("keywords", [])
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
@@ -16,10 +16,12 @@ def sync_single_news(news_id, max_retries=3):
|
||||
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
|
||||
is_news_relevant = llm_client.is_news_relevant(news_text)
|
||||
authors = llm_client.extract_names(news_text)
|
||||
keywords = llm_client.extract_keywords(news_text)
|
||||
new_entry = {
|
||||
"news_id": news_id,
|
||||
"relevant": is_news_relevant,
|
||||
"authors": authors,
|
||||
"keywords": keywords,
|
||||
}
|
||||
es_client.add_entry("aktuell_postproc", new_entry)
|
||||
return True
|
||||
@@ -32,6 +34,25 @@ def sync_single_news(news_id, max_retries=3):
|
||||
print(f"Error: {news_id} - {error}")
|
||||
return False
|
||||
|
||||
def update_keywords_single(postproc_entry, max_retries=3):
|
||||
doc_id = postproc_entry["_id"]
|
||||
news_id = postproc_entry["_source"]["news_id"]
|
||||
attempt = 0
|
||||
while attempt < max_retries:
|
||||
try:
|
||||
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
|
||||
keywords = llm_client.extract_keywords(news_text)
|
||||
es_client.update_entry("aktuell_postproc", doc_id, {"keywords": keywords})
|
||||
return True
|
||||
except Exception as error:
|
||||
attempt += 1
|
||||
print(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})")
|
||||
if attempt < max_retries:
|
||||
time.sleep(1)
|
||||
else:
|
||||
print(f"Error: {news_id} - {error}")
|
||||
return False
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Synchronize news articles from 'aktuell' index to 'aktuell_postproc' index with relevance and author extraction using LLM.")
|
||||
|
||||
@@ -47,6 +68,18 @@ def main():
|
||||
help="Sync only missing entries from 'aktuell' to 'aktuell_postproc'.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--update-keywords",
|
||||
action="store_true",
|
||||
help="Add 'keywords' to existing 'aktuell_postproc' entries that don't have them yet (keeps relevant/authors).",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--reset-keywords",
|
||||
action="store_true",
|
||||
help="Remove the 'keywords' field from all 'aktuell_postproc' entries (keeps relevant/authors). Run before re-extracting with a new prompt.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--stats",
|
||||
action="store_true",
|
||||
@@ -60,11 +93,22 @@ def main():
|
||||
help="Number of threads for --sync-delta (Default: 4).",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--limit",
|
||||
type=int,
|
||||
default=None,
|
||||
help="Process at most this many entries (used by --update-keywords, e.g. for a smoke test).",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.delete_all:
|
||||
es_client.delete_all_entries("aktuell_postproc")
|
||||
|
||||
if args.reset_keywords:
|
||||
result = es_client.remove_field_all("aktuell_postproc", "keywords")
|
||||
print(f"Removed 'keywords' from {result.get('updated', 0)} entries.")
|
||||
|
||||
if args.sync_delta:
|
||||
start_time = time.time()
|
||||
aktuell_ids_raw = es_client.get_all_entries("aktuell", fields=["_id"])
|
||||
@@ -96,23 +140,58 @@ def main():
|
||||
end_time = time.time()
|
||||
print(f"Sync DONE: {succeeded} entries synced.")
|
||||
print(f"Time taken: {end_time - start_time} seconds.")
|
||||
|
||||
|
||||
if args.update_keywords:
|
||||
start_time = time.time()
|
||||
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["news_id", "keywords"])
|
||||
|
||||
pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")]
|
||||
print(f"Number of entries without keywords: {len(pending)}")
|
||||
|
||||
if args.limit is not None:
|
||||
pending = pending[:args.limit]
|
||||
|
||||
total = len(pending)
|
||||
print(f"Processing {total} entries.")
|
||||
|
||||
processed = 0
|
||||
succeeded = 0
|
||||
progress_lock = threading.Lock()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.threads) as executor:
|
||||
futures = [executor.submit(update_keywords_single, entry) for entry in pending]
|
||||
for future in as_completed(futures):
|
||||
was_successful = future.result()
|
||||
with progress_lock:
|
||||
processed += 1
|
||||
if was_successful:
|
||||
succeeded += 1
|
||||
print(f"Update keywords: {processed} / {total}")
|
||||
|
||||
end_time = time.time()
|
||||
print(f"Update keywords DONE: {succeeded} entries updated.")
|
||||
print(f"Time taken: {end_time - start_time} seconds.")
|
||||
|
||||
if args.stats:
|
||||
aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"])
|
||||
print(f"Total entries in 'aktuell': {len(aktuell_entries)}")
|
||||
|
||||
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors"])
|
||||
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors", "keywords"])
|
||||
total_entries = len(postproc_entries)
|
||||
relevant_count = sum(1 for entry in postproc_entries if entry["_source"]["relevant"] == 1)
|
||||
irrelevant_count = total_entries - relevant_count
|
||||
news_with_extracted_names = sum(1 for entry in postproc_entries if entry["_source"]["authors"])
|
||||
news_without_extracted_names = total_entries - news_with_extracted_names
|
||||
news_with_keywords = sum(1 for entry in postproc_entries if entry["_source"].get("keywords"))
|
||||
news_without_keywords = total_entries - news_with_keywords
|
||||
|
||||
print(f"Total entries in 'aktuell_postproc': {total_entries}")
|
||||
print(f"Relevant entries: {relevant_count}")
|
||||
print(f"Irrelevant entries: {irrelevant_count}")
|
||||
print(f"Entries with extracted names: {news_with_extracted_names}")
|
||||
print(f"Entries without extracted names: {news_without_extracted_names}")
|
||||
print(f"Entries with keywords: {news_with_keywords}")
|
||||
print(f"Entries without keywords: {news_without_keywords}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because one or more lines are too long
@@ -17,6 +17,7 @@ class AccountProfile(BaseModel):
|
||||
email: str
|
||||
name: str
|
||||
role: UserRole
|
||||
permissions: list[str] = Field(default_factory=list)
|
||||
organization_id: uuid.UUID
|
||||
organization_name: str
|
||||
deleted: bool
|
||||
|
||||
@@ -6,6 +6,7 @@ from sqlmodel import Session, func, or_, select
|
||||
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole
|
||||
from inse.auth.permissions import Permission, get_permission_values, has_permission
|
||||
|
||||
from .model import (
|
||||
AccountPage,
|
||||
@@ -16,8 +17,12 @@ from .model import (
|
||||
)
|
||||
|
||||
|
||||
def _is_admin(role: UserRole) -> bool:
|
||||
return role in {UserRole.SUPER_ADMIN, UserRole.ADMIN}
|
||||
def _can_read_accounts(role: UserRole) -> bool:
|
||||
return has_permission(role, Permission.READ_ACCOUNTS)
|
||||
|
||||
|
||||
def _can_manage_accounts(role: UserRole) -> bool:
|
||||
return has_permission(role, Permission.MANAGE_ACCOUNTS)
|
||||
|
||||
|
||||
def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool:
|
||||
@@ -35,6 +40,7 @@ def _account_to_profile(account: Account, token: AccessTokenMetadata) -> Account
|
||||
email=account.email,
|
||||
name=account.name,
|
||||
role=account.role,
|
||||
permissions=get_permission_values(token.effective_role),
|
||||
organization_id=account.organization_id,
|
||||
organization_name=organization_name,
|
||||
deleted=account.deleted,
|
||||
@@ -109,11 +115,7 @@ def list_accounts(
|
||||
search: Optional[str] = None,
|
||||
organization_id: Optional[uuid.UUID] = None,
|
||||
) -> AccountPage:
|
||||
if access_token.effective_role not in {
|
||||
UserRole.SUPER_ADMIN,
|
||||
UserRole.ADMIN,
|
||||
UserRole.MANAGER,
|
||||
}:
|
||||
if not _can_read_accounts(access_token.effective_role):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only managers and admins can list accounts.",
|
||||
@@ -160,7 +162,7 @@ def create_account(
|
||||
access_token: AccessTokenMetadata,
|
||||
payload: CreateAccountRequest,
|
||||
) -> AccountProfile:
|
||||
if not _is_admin(access_token.effective_role):
|
||||
if not _can_manage_accounts(access_token.effective_role):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only admins can create accounts.",
|
||||
@@ -241,7 +243,7 @@ def update_account(
|
||||
_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)
|
||||
can_admin_update = _can_manage_accounts(access_token.effective_role)
|
||||
|
||||
if not can_admin_update and not is_self_update:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
@@ -314,7 +316,7 @@ def delete_account(
|
||||
_ensure_account_in_editor_scope(account, access_token)
|
||||
|
||||
if (
|
||||
not _is_admin(access_token.effective_role)
|
||||
not _can_manage_accounts(access_token.effective_role)
|
||||
or account.id == access_token.effective_account_id
|
||||
):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
@@ -322,4 +324,4 @@ def delete_account(
|
||||
account.deleted = True
|
||||
account.epoch += 1
|
||||
session.add(account)
|
||||
session.commit()
|
||||
session.commit()
|
||||
@@ -0,0 +1,44 @@
|
||||
from enum import StrEnum
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from inse.auth.model import UserRole
|
||||
|
||||
|
||||
class Permission(StrEnum):
|
||||
MANAGE_ORGANIZATIONS = "MANAGE_ORGANIZATIONS"
|
||||
READ_ACCOUNTS = "READ_ACCOUNTS"
|
||||
MANAGE_ACCOUNTS = "MANAGE_ACCOUNTS"
|
||||
|
||||
|
||||
ROLE_PERMISSIONS: dict[UserRole, set[Permission]] = {
|
||||
UserRole.SUPER_ADMIN: {
|
||||
Permission.MANAGE_ORGANIZATIONS,
|
||||
Permission.READ_ACCOUNTS,
|
||||
Permission.MANAGE_ACCOUNTS,
|
||||
},
|
||||
UserRole.ADMIN: {
|
||||
Permission.READ_ACCOUNTS,
|
||||
Permission.MANAGE_ACCOUNTS,
|
||||
},
|
||||
UserRole.MANAGER: {
|
||||
Permission.READ_ACCOUNTS,
|
||||
},
|
||||
UserRole.USER: set(),
|
||||
}
|
||||
|
||||
|
||||
def has_permission(role: UserRole, permission: Permission) -> bool:
|
||||
return permission in ROLE_PERMISSIONS.get(role, set())
|
||||
|
||||
|
||||
def require_permission(role: UserRole, permission: Permission) -> None:
|
||||
if not has_permission(role, permission):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Missing permission.",
|
||||
)
|
||||
|
||||
def get_permission_values(role: UserRole) -> list[str]:
|
||||
permissions = ROLE_PERMISSIONS.get(role, set())
|
||||
return [permission.value for permission in permissions]
|
||||
@@ -36,6 +36,8 @@ class ESIndex(StrEnum):
|
||||
OPENALEX_PUBLICATIONS = "openalex-publications"
|
||||
OPENALEX_COUNTRIES = "openalex-countries"
|
||||
OPENALEX_CONTINENTS = "openalex-continents"
|
||||
OPENALEX_TOPICS = "openalex-topics"
|
||||
OPENALEX_TOPIC_VECTORS = "topicvectors"
|
||||
|
||||
EPO_INDEX = "epo_index_1.0"
|
||||
USPTO_INDEX = "uspto_patents_3.0"
|
||||
|
||||
@@ -12,7 +12,8 @@ from inse.exceptions import ElasticsearchException
|
||||
|
||||
from ..integrations import elasticsearch, llm
|
||||
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
|
||||
from .model import MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
|
||||
from ..topics.logic import vector_search_topics
|
||||
from .model import MatchedTopic, MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -20,14 +21,19 @@ TOPIC_LIMIT = 4
|
||||
TOPIC_QUERY_CONTENT_CHARS = 300
|
||||
TOPIC_NUM_CANDIDATES = 100
|
||||
TOPIC_SIMILARITY = 0.5
|
||||
TOPIC_MATCHES_PER_KEYWORD = 1
|
||||
|
||||
KEYWORD_LIMIT = 6
|
||||
KEYWORD_CONTENT_CHARS = 4000
|
||||
KEYWORD_SYSTEM_PROMPT = """\
|
||||
Extrahiere aus dem folgenden Nachrichtenartikel die wichtigsten Schlagwörter (Keywords).
|
||||
Gib maximal sechs prägnante Begriffe oder kurze Phrasen zurück, die den inhaltlichen Kern
|
||||
des Artikels erfassen. Antworte ausschließlich mit einem JSON-Array von Strings, ohne
|
||||
weiteren Text, zum Beispiel ["Künstliche Intelligenz", "Klimaforschung"].
|
||||
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
|
||||
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
|
||||
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
|
||||
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
|
||||
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
|
||||
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
|
||||
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {"keywords": ["Schlagwort", "Schlagwort"]}
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
"""
|
||||
|
||||
RELATED_BLOCK_SIZE = 5
|
||||
@@ -247,7 +253,6 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
source = response.get("_source", {})
|
||||
|
||||
relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id)
|
||||
topics = await _get_article_topics(source.get("maintitle"), source.get("full_content"))
|
||||
keywords = await _get_article_keywords(
|
||||
news_id,
|
||||
postproc_id,
|
||||
@@ -255,6 +260,7 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
source.get("maintitle"),
|
||||
source.get("full_content"),
|
||||
)
|
||||
topics = await _match_topics_for_keywords(keywords)
|
||||
|
||||
return NewsArticleDetail(
|
||||
id=response.get("_id"),
|
||||
@@ -265,22 +271,11 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
full_content=source.get("full_content"),
|
||||
relevant=relevant,
|
||||
authors=await _build_mentioned_persons(authors),
|
||||
topics=topics,
|
||||
keywords=keywords,
|
||||
topics=topics,
|
||||
)
|
||||
|
||||
|
||||
async def _get_article_topics(maintitle: str | None, full_content: str | None) -> list:
|
||||
query = " ".join(
|
||||
part for part in (maintitle, (full_content or "")[:TOPIC_QUERY_CONTENT_CHARS]) if part
|
||||
).strip()
|
||||
if not query:
|
||||
return []
|
||||
|
||||
topics = await _topic_vector_search(query, TOPIC_LIMIT, ["display_name"])
|
||||
return [topic["display_name"] for topic in topics if topic.get("display_name")]
|
||||
|
||||
|
||||
async def _get_article_keywords(
|
||||
news_id: str,
|
||||
postproc_id: str | None,
|
||||
@@ -315,7 +310,12 @@ def _parse_keywords(raw: str) -> list:
|
||||
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
candidates = parsed if isinstance(parsed, list) else []
|
||||
if isinstance(parsed, list):
|
||||
candidates = parsed
|
||||
elif isinstance(parsed, dict):
|
||||
candidates = parsed.get("keywords", [])
|
||||
else:
|
||||
candidates = []
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
candidates = re.split(r"[,\n]", raw)
|
||||
|
||||
@@ -350,6 +350,35 @@ async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list)
|
||||
logger.exception(f"Failed to cache keywords for {news_id}.")
|
||||
|
||||
|
||||
async def _match_topics_for_keywords(keywords: list) -> list:
|
||||
matched = []
|
||||
seen_ids = set()
|
||||
|
||||
for keyword in keywords:
|
||||
try:
|
||||
response = await vector_search_topics(query=keyword, limit=TOPIC_MATCHES_PER_KEYWORD)
|
||||
except Exception:
|
||||
logger.exception(f"Topic-Matching fuer Keyword '{keyword}' fehlgeschlagen.")
|
||||
continue
|
||||
|
||||
for topic in response.results or []:
|
||||
if not topic.id or topic.id in seen_ids:
|
||||
continue
|
||||
seen_ids.add(topic.id)
|
||||
matched.append(
|
||||
MatchedTopic(
|
||||
id=topic.id,
|
||||
display_name=topic.display_name,
|
||||
subfield_name=topic.subfield.display_name if topic.subfield else None,
|
||||
field_name=topic.var_field.display_name if topic.var_field else None,
|
||||
domain_name=topic.domain.display_name if topic.domain else None,
|
||||
source_keyword=keyword,
|
||||
)
|
||||
)
|
||||
|
||||
return matched
|
||||
|
||||
|
||||
async def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||
try:
|
||||
from ..util import get_model
|
||||
|
||||
@@ -23,12 +23,21 @@ class MentionedPerson(BaseModel):
|
||||
person_id: Optional[str] = None
|
||||
|
||||
|
||||
class MatchedTopic(BaseModel):
|
||||
id: Optional[str] = None
|
||||
display_name: Optional[str] = None
|
||||
subfield_name: Optional[str] = None
|
||||
field_name: Optional[str] = None
|
||||
domain_name: Optional[str] = None
|
||||
source_keyword: Optional[str] = None
|
||||
|
||||
|
||||
class NewsArticleDetail(NewsArticle):
|
||||
full_content: Optional[str] = None
|
||||
relevant: Optional[bool] = None
|
||||
authors: List[MentionedPerson] = []
|
||||
topics: List[str] = []
|
||||
keywords: List[str] = []
|
||||
topics: List[MatchedTopic] = []
|
||||
|
||||
|
||||
class NewsPage(BaseModel):
|
||||
|
||||
@@ -4,7 +4,9 @@ from typing import Optional
|
||||
from fastapi import HTTPException, status
|
||||
from sqlmodel import Session, func, select
|
||||
|
||||
from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole
|
||||
from inse.auth.model import AccessTokenMetadata, Account, Organization
|
||||
from inse.auth.permissions import Permission, has_permission, require_permission
|
||||
|
||||
|
||||
from .model import (
|
||||
CreateOrganizationRequest,
|
||||
@@ -14,12 +16,11 @@ from .model import (
|
||||
)
|
||||
|
||||
|
||||
def _require_super_admin(access_token: AccessTokenMetadata) -> None:
|
||||
if access_token.effective_role != UserRole.SUPER_ADMIN:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only superadmins can manage organizations.",
|
||||
)
|
||||
def _require_manage_organizations(access_token: AccessTokenMetadata) -> None:
|
||||
require_permission(
|
||||
access_token.effective_role,
|
||||
Permission.MANAGE_ORGANIZATIONS,
|
||||
)
|
||||
|
||||
|
||||
def _normalize_name(name: str) -> str:
|
||||
@@ -117,7 +118,7 @@ def get_organizations(
|
||||
statement = select(Organization)
|
||||
count_statement = select(func.count()).select_from(Organization)
|
||||
|
||||
if access_token.effective_role != UserRole.SUPER_ADMIN:
|
||||
if not has_permission(access_token.effective_role, Permission.MANAGE_ORGANIZATIONS):
|
||||
scope_filter = Organization.id == access_token.effective_organization_id
|
||||
statement = statement.where(scope_filter)
|
||||
count_statement = count_statement.where(scope_filter)
|
||||
@@ -148,7 +149,7 @@ def create_organization(
|
||||
access_token: AccessTokenMetadata,
|
||||
payload: CreateOrganizationRequest,
|
||||
) -> OrganizationProfile:
|
||||
_require_super_admin(access_token)
|
||||
_require_manage_organizations(access_token)
|
||||
name = _normalize_name(payload.name)
|
||||
_ensure_name_available(session, name)
|
||||
|
||||
@@ -168,7 +169,7 @@ def update_organization(
|
||||
organization_id: uuid.UUID,
|
||||
payload: UpdateOrganizationRequest,
|
||||
) -> OrganizationProfile:
|
||||
_require_super_admin(access_token)
|
||||
_require_manage_organizations(access_token)
|
||||
organization = _get_organization_or_404(session, organization_id)
|
||||
|
||||
if payload.name is not None:
|
||||
@@ -194,10 +195,10 @@ def delete_organization(
|
||||
access_token: AccessTokenMetadata,
|
||||
organization_id: uuid.UUID,
|
||||
) -> None:
|
||||
_require_super_admin(access_token)
|
||||
_require_manage_organizations(access_token)
|
||||
organization = _get_organization_or_404(session, organization_id)
|
||||
if not organization.deleted:
|
||||
_deactivate_organization_accounts(session, organization.id)
|
||||
organization.deleted = True
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
session.commit()
|
||||
@@ -32,6 +32,7 @@ from inse.persons.model import (
|
||||
CustomAuthorsListResponse,
|
||||
CareerMetrics,
|
||||
)
|
||||
from inse.works.logic import enrich_topic_descriptions
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
INDEX_NAME = "openalex-authors"
|
||||
@@ -728,6 +729,10 @@ async def advanced_search_persons(
|
||||
)
|
||||
results.append(custom_author)
|
||||
|
||||
await enrich_topic_descriptions(
|
||||
[topic for author in results for topic in author.topics or []]
|
||||
)
|
||||
|
||||
return CustomAuthorsListResponse(
|
||||
results=results, meta=Meta(count=total_count, page=page, per_page=page_size)
|
||||
)
|
||||
|
||||
@@ -4,13 +4,12 @@
|
||||
Business logic for OpenAlex topics.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
import asyncio
|
||||
from pydantic import ValidationError
|
||||
|
||||
from inse.exceptions import (
|
||||
UpstreamAPIException,
|
||||
BadRequestException,
|
||||
@@ -23,8 +22,8 @@ from inse.models.openalex.autocomplete_response_results_inner import (
|
||||
AutocompleteResponseResultsInner,
|
||||
)
|
||||
from inse.models.openalex.topics_list_response import TopicsListResponse
|
||||
from inse.model import ESCluster
|
||||
from .search_client import OpenAlexTopicsClient
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from .search_client import TopicsSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -40,15 +39,15 @@ async def list_topics(
|
||||
cursor: str | None = None,
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
client: OpenAlexTopicsClient | None = None,
|
||||
client: TopicsSearchClient | None = None,
|
||||
) -> TopicsListResponse:
|
||||
if sample is not None and (sort or page not in (None, 1)):
|
||||
raise BadRequestException("sample cannot be combined with sort or page.")
|
||||
|
||||
openalex_client = client or OpenAlexTopicsClient()
|
||||
topics_client = client or TopicsSearchClient()
|
||||
|
||||
try:
|
||||
data = await openalex_client.list_topics(
|
||||
data = await topics_client.list_topics(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
@@ -59,25 +58,24 @@ async def list_topics(
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
except httpx.HTTPStatusError as exc:
|
||||
status_code = exc.response.status_code
|
||||
detail = "OpenAlex topics request failed."
|
||||
try:
|
||||
error_body = exc.response.json()
|
||||
detail = error_body.get("message") or error_body.get("error") or detail
|
||||
except ValueError:
|
||||
if exc.response.text:
|
||||
detail = exc.response.text
|
||||
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex topics request failed.")
|
||||
except ValueError as exc:
|
||||
raise BadRequestException(str(exc)) from exc
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("OpenAlex topics Elasticsearch request failed.")
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex topics request failed.",
|
||||
message="OpenAlex topics Elasticsearch request failed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
try:
|
||||
normalized_data = _normalize_topics_response(data)
|
||||
openalex_style_data = _elasticsearch_to_topics_response(
|
||||
data,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
group_by=group_by,
|
||||
)
|
||||
normalized_data = _normalize_topics_response(openalex_style_data)
|
||||
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
|
||||
except ValidationError as exc:
|
||||
logger.exception("OpenAlex topics response could not be parsed.")
|
||||
@@ -94,7 +92,7 @@ async def autocomplete_topics(
|
||||
field_id: str | None = None,
|
||||
subfield_id: str | None = None,
|
||||
limit: int = 10,
|
||||
client: OpenAlexTopicsClient | None = None,
|
||||
client: TopicsSearchClient | None = None,
|
||||
) -> AutocompleteResponse:
|
||||
filters = []
|
||||
if domain_id:
|
||||
@@ -153,6 +151,99 @@ async def autocomplete_topics(
|
||||
)
|
||||
|
||||
|
||||
def _elasticsearch_to_topics_response(
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
per_page: int,
|
||||
page: int | None,
|
||||
cursor: str | None,
|
||||
group_by: str | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Converts an Elasticsearch search response into the OpenAlex-style topics
|
||||
response expected by TopicsListResponse.
|
||||
|
||||
Elasticsearch response shape:
|
||||
|
||||
{
|
||||
"took": 12,
|
||||
"hits": {
|
||||
"total": {"value": 123},
|
||||
"hits": [
|
||||
{"_source": {...}, "sort": [...]}
|
||||
]
|
||||
},
|
||||
"aggregations": {...}
|
||||
}
|
||||
|
||||
OpenAlex-style response shape:
|
||||
|
||||
{
|
||||
"meta": {...},
|
||||
"results": [...],
|
||||
"group_by": [...]
|
||||
}
|
||||
"""
|
||||
hits_root = data.get("hits") or {}
|
||||
raw_hits = hits_root.get("hits") or []
|
||||
|
||||
total = hits_root.get("total")
|
||||
if isinstance(total, dict):
|
||||
count = total.get("value")
|
||||
else:
|
||||
count = total
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
for hit in raw_hits:
|
||||
if not isinstance(hit, dict):
|
||||
continue
|
||||
|
||||
source = hit.get("_source")
|
||||
if isinstance(source, dict):
|
||||
results.append(source)
|
||||
|
||||
groups = _extract_group_by_results(data) if group_by else []
|
||||
|
||||
meta = {
|
||||
"count": count,
|
||||
"db_response_time_ms": data.get("took"),
|
||||
"page": page if cursor is None else None,
|
||||
"per_page": per_page,
|
||||
"groups_count": len(groups) if group_by else None,
|
||||
"next_cursor": (data.get("meta") or {}).get("next_cursor"),
|
||||
"cost_usd": None,
|
||||
}
|
||||
|
||||
return {
|
||||
"meta": meta,
|
||||
"results": results,
|
||||
"group_by": groups,
|
||||
}
|
||||
|
||||
|
||||
def _extract_group_by_results(data: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
aggregations = data.get("aggregations") or {}
|
||||
group_by_agg = aggregations.get("group_by") or {}
|
||||
buckets = group_by_agg.get("buckets") or []
|
||||
|
||||
groups: list[dict[str, Any]] = []
|
||||
|
||||
for bucket in buckets:
|
||||
if not isinstance(bucket, dict):
|
||||
continue
|
||||
|
||||
key = bucket.get("key")
|
||||
groups.append(
|
||||
{
|
||||
"key": key,
|
||||
"key_display_name": bucket.get("key_as_string") or key,
|
||||
"count": bucket.get("doc_count"),
|
||||
}
|
||||
)
|
||||
|
||||
return groups
|
||||
|
||||
|
||||
def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]:
|
||||
normalized = deepcopy(data)
|
||||
|
||||
@@ -264,7 +355,6 @@ def _datetime_str_or_none(value: Any) -> str | None:
|
||||
return f"{text}T00:00:00Z"
|
||||
return text
|
||||
|
||||
|
||||
# Configuration for vector search similarity thresholds and boosts
|
||||
SIMILARITY_THRESHOLD = (
|
||||
0.8 # intfloat/multilingual-e5-base uses cosine similarity between 0.7 - 1
|
||||
@@ -388,7 +478,7 @@ async def vector_search_topics(
|
||||
|
||||
try:
|
||||
raw_results = await elasticsearch.search(
|
||||
index="topicvectors", body=body, cluster=ESCluster.NES
|
||||
index=ESIndex.OPENALEX_TOPIC_VECTORS, body=body, cluster=ESCluster.NES
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Elasticsearch vector search failed with unexpected error.")
|
||||
@@ -458,7 +548,7 @@ async def vector_search_topics_batch(
|
||||
)
|
||||
tasks.append(
|
||||
elasticsearch.search(
|
||||
index="topicvectors", body=body, cluster=ESCluster.NES
|
||||
index=ESIndex.OPENALEX_TOPIC_VECTORS, body=body, cluster=ESCluster.NES
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -1,33 +1,200 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
HTTP client for OpenAlex topics.
|
||||
Elasticsearch search client for OpenAlex topics.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
from .. import config
|
||||
from inse.integrations.elasticsearch import search as elasticsearch_search
|
||||
|
||||
|
||||
class OpenAlexTopicsClient:
|
||||
class TopicsSearchClient:
|
||||
"""
|
||||
Search client for OpenAlex topics backed by Elasticsearch.
|
||||
|
||||
This replaces the old OpenAlex HTTP API client and uses the internal
|
||||
Elasticsearch wrapper instead.
|
||||
"""
|
||||
|
||||
DEFAULT_SEARCH_FIELDS = [
|
||||
"display_name^5",
|
||||
"description^3",
|
||||
"keywords",
|
||||
"domain.display_name^2",
|
||||
"field.display_name^2",
|
||||
"subfield.display_name^2",
|
||||
]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float | None = None,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
*,
|
||||
index: ESIndex | str | None = None,
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.openalex_api_key
|
||||
self.timeout = (
|
||||
timeout
|
||||
if timeout is not None
|
||||
else config.settings.openalex_api_timeout_seconds
|
||||
)
|
||||
self.transport = transport
|
||||
self.index = index or self._default_index()
|
||||
self.cluster = cluster
|
||||
|
||||
def list_topics_params(
|
||||
@staticmethod
|
||||
def _default_index() -> str:
|
||||
"""
|
||||
Resolve the OpenAlex topics index name.
|
||||
|
||||
Prefer a configured value if present, otherwise fall back to a sensible
|
||||
default string index name.
|
||||
"""
|
||||
return (
|
||||
ESIndex.OPENALEX_TOPICS.value
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _split_csv(value: str | None) -> list[str]:
|
||||
if not value:
|
||||
return []
|
||||
return [part.strip() for part in value.split(",") if part.strip()]
|
||||
|
||||
@staticmethod
|
||||
def _encode_cursor(sort_values: list[Any]) -> str:
|
||||
raw = json.dumps(sort_values).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
@staticmethod
|
||||
def _decode_cursor(cursor: str | None) -> list[Any] | None:
|
||||
if not cursor or cursor == "*":
|
||||
return None
|
||||
|
||||
padding = "=" * (-len(cursor) % 4)
|
||||
raw = base64.urlsafe_b64decode(cursor + padding)
|
||||
return json.loads(raw.decode("utf-8"))
|
||||
|
||||
@staticmethod
|
||||
def _parse_select(select: str | None) -> list[str] | None:
|
||||
fields = TopicsSearchClient._split_csv(select)
|
||||
return fields or None
|
||||
|
||||
@staticmethod
|
||||
def _parse_sort(sort: str | None) -> list[dict[str, Any]] | None:
|
||||
"""
|
||||
Parses OpenAlex-style sort syntax into Elasticsearch sort syntax.
|
||||
|
||||
Examples:
|
||||
"works_count:desc"
|
||||
"cited_by_count:desc,display_name:asc"
|
||||
"-works_count"
|
||||
"""
|
||||
parts = TopicsSearchClient._split_csv(sort)
|
||||
if not parts:
|
||||
return None
|
||||
|
||||
parsed: list[dict[str, Any]] = []
|
||||
|
||||
for part in parts:
|
||||
direction = "asc"
|
||||
field = part
|
||||
|
||||
if part.startswith("-"):
|
||||
direction = "desc"
|
||||
field = part[1:]
|
||||
elif ":" in part:
|
||||
field, direction = part.split(":", 1)
|
||||
field = field.strip()
|
||||
direction = direction.strip().lower()
|
||||
|
||||
if direction not in {"asc", "desc"}:
|
||||
direction = "asc"
|
||||
|
||||
if field in {"score", "_score", "relevance_score"}:
|
||||
parsed.append({"_score": {"order": direction}})
|
||||
else:
|
||||
parsed.append({field: {"order": direction, "missing": "_last"}})
|
||||
|
||||
return parsed
|
||||
|
||||
@staticmethod
|
||||
def _parse_filter_clause(expression: str) -> tuple[dict[str, Any] | None, bool]:
|
||||
"""
|
||||
Parses a single simple OpenAlex-style filter expression.
|
||||
|
||||
Supported examples:
|
||||
"works_count:>100"
|
||||
"works_count:>=100"
|
||||
"display_name:Physics"
|
||||
"ids.openalex:T123"
|
||||
"field.id:F1|F2"
|
||||
"is_active:true"
|
||||
"is_active:!true"
|
||||
|
||||
Returns:
|
||||
tuple[clause, is_negative]
|
||||
"""
|
||||
if ":" not in expression:
|
||||
return None, False
|
||||
|
||||
field, value = expression.split(":", 1)
|
||||
field = field.strip()
|
||||
value = value.strip()
|
||||
|
||||
if not field or not value:
|
||||
return None, False
|
||||
|
||||
is_negative = False
|
||||
if value.startswith("!"):
|
||||
is_negative = True
|
||||
value = value[1:].strip()
|
||||
|
||||
range_ops = {
|
||||
">=": "gte",
|
||||
"<=": "lte",
|
||||
">": "gt",
|
||||
"<": "lt",
|
||||
}
|
||||
|
||||
for prefix, op in range_ops.items():
|
||||
if value.startswith(prefix):
|
||||
range_value = value[len(prefix):].strip()
|
||||
return {"range": {field: {op: range_value}}}, is_negative
|
||||
|
||||
if "|" in value:
|
||||
values = [v.strip() for v in value.split("|") if v.strip()]
|
||||
return {"terms": {field: values}}, is_negative
|
||||
|
||||
lowered = value.lower()
|
||||
if lowered == "true":
|
||||
typed_value: Any = True
|
||||
elif lowered == "false":
|
||||
typed_value = False
|
||||
else:
|
||||
typed_value = value
|
||||
|
||||
return {"term": {field: typed_value}}, is_negative
|
||||
|
||||
@classmethod
|
||||
def _parse_filters(
|
||||
cls,
|
||||
filter: str | None,
|
||||
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
filter_clauses: list[dict[str, Any]] = []
|
||||
must_not_clauses: list[dict[str, Any]] = []
|
||||
|
||||
for expression in cls._split_csv(filter):
|
||||
clause, is_negative = cls._parse_filter_clause(expression)
|
||||
if clause is None:
|
||||
continue
|
||||
|
||||
if is_negative:
|
||||
must_not_clauses.append(clause)
|
||||
else:
|
||||
filter_clauses.append(clause)
|
||||
|
||||
return filter_clauses, must_not_clauses
|
||||
|
||||
def build_search_body(
|
||||
self,
|
||||
*,
|
||||
search: str | None = None,
|
||||
@@ -40,28 +207,118 @@ class OpenAlexTopicsClient:
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
params: dict[str, Any] = {"per_page": per_page}
|
||||
"""
|
||||
Build the Elasticsearch search body from the previous OpenAlex-style API
|
||||
parameters.
|
||||
"""
|
||||
filter_clauses, must_not_clauses = self._parse_filters(filter)
|
||||
|
||||
must_clauses: list[dict[str, Any]] = []
|
||||
|
||||
if search:
|
||||
params["search"] = search
|
||||
if filter:
|
||||
params["filter"] = filter
|
||||
if sort:
|
||||
params["sort"] = sort
|
||||
if group_by:
|
||||
params["group_by"] = group_by
|
||||
if cursor:
|
||||
params["cursor"] = cursor
|
||||
elif page is not None:
|
||||
params["page"] = page
|
||||
if sample is not None:
|
||||
params["sample"] = sample
|
||||
if select:
|
||||
params["select"] = select
|
||||
if self.api_key:
|
||||
params["api_key"] = self.api_key
|
||||
must_clauses.append(
|
||||
{
|
||||
"multi_match": {
|
||||
"query": search,
|
||||
"fields": self.DEFAULT_SEARCH_FIELDS,
|
||||
"type": "best_fields",
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return params
|
||||
if must_clauses or filter_clauses or must_not_clauses:
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"must": must_clauses or [{"match_all": {}}],
|
||||
"filter": filter_clauses,
|
||||
"must_not": must_not_clauses,
|
||||
}
|
||||
}
|
||||
else:
|
||||
query = {"match_all": {}}
|
||||
|
||||
if sample is not None:
|
||||
query = {
|
||||
"function_score": {
|
||||
"query": query,
|
||||
"random_score": {},
|
||||
}
|
||||
}
|
||||
|
||||
size = sample if sample is not None else per_page
|
||||
|
||||
body: dict[str, Any] = {
|
||||
"query": query,
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
}
|
||||
|
||||
source = self._parse_select(select)
|
||||
if source is not None:
|
||||
body["_source"] = source
|
||||
|
||||
sort_clause = self._parse_sort(sort)
|
||||
if sort_clause is not None:
|
||||
body["sort"] = sort_clause
|
||||
|
||||
search_after = self._decode_cursor(cursor)
|
||||
if search_after is not None:
|
||||
body["search_after"] = search_after
|
||||
elif cursor is None and page is not None:
|
||||
body["from"] = max(page - 1, 0) * per_page
|
||||
|
||||
if group_by:
|
||||
body["size"] = 0
|
||||
body["aggs"] = {
|
||||
"group_by": {
|
||||
"terms": {
|
||||
"field": group_by,
|
||||
"size": per_page,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return body
|
||||
|
||||
async def search_topics(
|
||||
self,
|
||||
*,
|
||||
search: str | None = None,
|
||||
filter: str | None = None,
|
||||
sort: str | None = None,
|
||||
group_by: str | None = None,
|
||||
per_page: int = 25,
|
||||
page: int | None = 1,
|
||||
cursor: str | None = None,
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
body = self.build_search_body(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
|
||||
result = await elasticsearch_search(
|
||||
index=self.index,
|
||||
body=body,
|
||||
cluster=self.cluster,
|
||||
)
|
||||
|
||||
hits = result.get("hits", {}).get("hits", [])
|
||||
if hits:
|
||||
last_sort = hits[-1].get("sort")
|
||||
if last_sort is not None:
|
||||
result.setdefault("meta", {})["next_cursor"] = self._encode_cursor(last_sort)
|
||||
|
||||
return result
|
||||
|
||||
async def list_topics(
|
||||
self,
|
||||
@@ -76,24 +333,17 @@ class OpenAlexTopicsClient:
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.get(
|
||||
"/topics",
|
||||
params=self.list_topics_params(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
),
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
"""
|
||||
Backwards-compatible alias for the old OpenAlex client method name.
|
||||
"""
|
||||
return await self.search_topics(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
@@ -1,9 +1,7 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from inse.exceptions import BadRequestException
|
||||
|
||||
from inse.exceptions import BadRequestException
|
||||
from inse.topics import logic
|
||||
from inse.topics.search_client import OpenAlexTopicsClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -11,108 +9,144 @@ def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
class FakeTopicsSearchClient:
|
||||
def __init__(self, response: dict):
|
||||
self.response = response
|
||||
self.calls: list[dict] = []
|
||||
|
||||
async def list_topics(self, **kwargs):
|
||||
self.calls.append(kwargs)
|
||||
return self.response
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_maps_openalex_response_to_model():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
async def test_list_topics_maps_elasticsearch_response_to_model():
|
||||
client = FakeTopicsSearchClient(
|
||||
{
|
||||
"took": 12,
|
||||
"hits": {
|
||||
"total": {"value": 1, "relation": "eq"},
|
||||
"hits": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"description": "Methods that learn from data.",
|
||||
"keywords": ["machine learning", "classification"],
|
||||
"subfield": {
|
||||
"id": "https://openalex.org/subfields/1702",
|
||||
"display_name": "Artificial Intelligence",
|
||||
"_id": "https://openalex.org/T12419",
|
||||
"_source": {
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"description": "Methods that learn from data.",
|
||||
"keywords": ["machine learning", "classification"],
|
||||
"subfield": {
|
||||
"id": "https://openalex.org/subfields/1702",
|
||||
"display_name": "Artificial Intelligence",
|
||||
},
|
||||
"field": {
|
||||
"id": "https://openalex.org/fields/17",
|
||||
"display_name": "Computer Science",
|
||||
},
|
||||
"domain": {
|
||||
"id": "https://openalex.org/domains/4",
|
||||
"display_name": "Physical Sciences",
|
||||
},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {
|
||||
"openalex": "https://openalex.org/T12419",
|
||||
"wikipedia": "https://en.wikipedia.org/wiki/Machine_learning",
|
||||
},
|
||||
"works_api_url": (
|
||||
"https://api.openalex.org/works?"
|
||||
"filter=topics.id:T12419"
|
||||
),
|
||||
"created_date": "2023-12-25",
|
||||
"updated_date": "2023-11-07T05:31:56Z",
|
||||
},
|
||||
"field": {
|
||||
"id": "https://openalex.org/fields/17",
|
||||
"display_name": "Computer Science",
|
||||
},
|
||||
"domain": {
|
||||
"id": "https://openalex.org/domains/4",
|
||||
"display_name": "Physical Sciences",
|
||||
},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {
|
||||
"openalex": "https://openalex.org/T12419",
|
||||
"wikipedia": "https://en.wikipedia.org/wiki/Machine_learning",
|
||||
},
|
||||
"works_api_url": "https://api.openalex.org/works?filter=topics.id:T12419",
|
||||
"created_date": "2023-12-25",
|
||||
"updated_date": "2023-11-07T05:31:56Z",
|
||||
}
|
||||
],
|
||||
"group_by": [
|
||||
{
|
||||
"key": "https://openalex.org/domains/4",
|
||||
"key_display_name": "Physical Sciences",
|
||||
"count": 1,
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
"aggregations": {
|
||||
"group_by": {
|
||||
"buckets": [
|
||||
{
|
||||
"key": "https://openalex.org/domains/4",
|
||||
"key_as_string": "Physical Sciences",
|
||||
"doc_count": 1,
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
result = await logic.list_topics(search="machine learning", client=client)
|
||||
result = await logic.list_topics(
|
||||
search="machine learning",
|
||||
group_by="domain.id",
|
||||
client=client,
|
||||
)
|
||||
|
||||
assert client.calls[0]["search"] == "machine learning"
|
||||
assert client.calls[0]["group_by"] == "domain.id"
|
||||
|
||||
assert result.meta.count == 1
|
||||
assert result.meta.db_response_time_ms == 12
|
||||
|
||||
topic = result.results[0]
|
||||
assert topic.display_name == "Machine learning"
|
||||
assert topic.var_field.display_name == "Computer Science"
|
||||
assert topic.subfield.display_name == "Artificial Intelligence"
|
||||
assert topic.domain.display_name == "Physical Sciences"
|
||||
assert topic.ids.openalex == "https://openalex.org/T12419"
|
||||
|
||||
assert result.group_by[0].key == "https://openalex.org/domains/4"
|
||||
assert result.group_by[0].key_display_name == "Physical Sciences"
|
||||
assert result.group_by[0].count == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_rejects_sample_with_sort():
|
||||
with pytest.raises(BadRequestException) as exc_info:
|
||||
with pytest.raises(BadRequestException):
|
||||
await logic.list_topics(sample=10, sort="works_count:desc")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_accepts_practical_openalex_type_variants():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": "1", "page": "1", "per_page": "25"},
|
||||
"results": [
|
||||
client = FakeTopicsSearchClient(
|
||||
{
|
||||
"took": "10",
|
||||
"hits": {
|
||||
"total": {"value": "1", "relation": "eq"},
|
||||
"hits": [
|
||||
{
|
||||
"id": 123,
|
||||
"display_name": 456,
|
||||
"description": True,
|
||||
"keywords": ["topic", 123],
|
||||
"subfield": {"id": 1, "display_name": 2},
|
||||
"field": {"id": 3, "display_name": 4},
|
||||
"domain": {"id": 5, "display_name": 6},
|
||||
"works_count": "12.0",
|
||||
"cited_by_count": False,
|
||||
"ids": {"openalex": 123, "wikipedia": 456},
|
||||
"created_date": "2023-12-25T10:11:12Z",
|
||||
"updated_date": "2023-12-25",
|
||||
"_id": "123",
|
||||
"_source": {
|
||||
"id": 123,
|
||||
"display_name": 456,
|
||||
"description": True,
|
||||
"keywords": ["topic", 123],
|
||||
"subfield": {"id": 1, "display_name": 2},
|
||||
"field": {"id": 3, "display_name": 4},
|
||||
"domain": {"id": 5, "display_name": 6},
|
||||
"works_count": "12.0",
|
||||
"cited_by_count": False,
|
||||
"ids": {"openalex": 123, "wikipedia": 456},
|
||||
"created_date": "2023-12-25T10:11:12Z",
|
||||
"updated_date": "2023-12-25",
|
||||
},
|
||||
}
|
||||
],
|
||||
"group_by": [{"key": True, "count": "1"}],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
"aggregations": {
|
||||
"group_by": {
|
||||
"buckets": [
|
||||
{
|
||||
"key": True,
|
||||
"doc_count": "1",
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
result = await logic.list_topics(client=client)
|
||||
result = await logic.list_topics(group_by="domain.id", client=client)
|
||||
|
||||
topic = result.results[0]
|
||||
assert topic.id == "123"
|
||||
@@ -131,42 +165,33 @@ async def test_list_topics_accepts_practical_openalex_type_variants():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_autocomplete_topics_returns_frontend_options():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.url.params["search"] == "machine learning"
|
||||
assert request.url.params["filter"] == (
|
||||
"domain.id:https://openalex.org/domains/4,"
|
||||
"field.id:https://openalex.org/fields/17,"
|
||||
"subfield.id:https://openalex.org/subfields/1702"
|
||||
)
|
||||
assert request.url.params["sort"] == "works_count:desc"
|
||||
assert request.url.params["per_page"] == "5"
|
||||
assert request.url.params["select"] == (
|
||||
"id,display_name,description,keywords,subfield,field,domain,"
|
||||
"works_count,cited_by_count,ids"
|
||||
)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "db_response_time_ms": 12},
|
||||
"results": [
|
||||
client = FakeTopicsSearchClient(
|
||||
{
|
||||
"took": 12,
|
||||
"hits": {
|
||||
"total": {"value": 1, "relation": "eq"},
|
||||
"hits": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"description": "Methods that learn from data.",
|
||||
"field": {"display_name": "Computer Science"},
|
||||
"subfield": {"display_name": "Artificial Intelligence"},
|
||||
"domain": {"display_name": "Physical Sciences"},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {"openalex": "https://openalex.org/T12419"},
|
||||
"_id": "https://openalex.org/T12419",
|
||||
"_source": {
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"description": "Methods that learn from data.",
|
||||
"field": {"display_name": "Computer Science"},
|
||||
"subfield": {
|
||||
"display_name": "Artificial Intelligence",
|
||||
},
|
||||
"domain": {"display_name": "Physical Sciences"},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {
|
||||
"openalex": "https://openalex.org/T12419",
|
||||
},
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
}
|
||||
)
|
||||
|
||||
result = await logic.autocomplete_topics(
|
||||
@@ -178,9 +203,24 @@ async def test_autocomplete_topics_returns_frontend_options():
|
||||
client=client,
|
||||
)
|
||||
|
||||
assert client.calls[0]["search"] == "machine learning"
|
||||
assert client.calls[0]["filter"] == (
|
||||
"domain.id:https://openalex.org/domains/4,"
|
||||
"field.id:https://openalex.org/fields/17,"
|
||||
"subfield.id:https://openalex.org/subfields/1702"
|
||||
)
|
||||
assert client.calls[0]["sort"] == "works_count:desc"
|
||||
assert client.calls[0]["per_page"] == 5
|
||||
assert client.calls[0]["page"] == 1
|
||||
assert client.calls[0]["select"] == (
|
||||
"id,display_name,description,keywords,subfield,field,domain,"
|
||||
"works_count,cited_by_count,ids"
|
||||
)
|
||||
|
||||
assert result.meta.count == 1
|
||||
assert result.meta.db_response_time_ms == 12
|
||||
assert len(result.results) == 1
|
||||
|
||||
option = result.results[0]
|
||||
assert option.id == "https://openalex.org/T12419"
|
||||
assert option.display_name == "Machine learning"
|
||||
@@ -190,4 +230,4 @@ async def test_autocomplete_topics_returns_frontend_options():
|
||||
assert option.works_count == 123
|
||||
assert option.cited_by_count == 456
|
||||
assert option.entity_type == "topic"
|
||||
assert option.external_id == "https://openalex.org/T12419"
|
||||
assert option.external_id == "https://openalex.org/T12419"
|
||||
@@ -1,7 +1,7 @@
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.topics.search_client import OpenAlexTopicsClient
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.topics.search_client import TopicsSearchClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -9,10 +9,10 @@ def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
def test_list_topics_params_include_openalex_query_parameters():
|
||||
client = OpenAlexTopicsClient(api_key="test-key")
|
||||
def test_build_search_body_includes_openalex_query_parameters():
|
||||
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
|
||||
|
||||
params = client.list_topics_params(
|
||||
body = client.build_search_body(
|
||||
search="machine learning",
|
||||
filter="domain.id:4,works_count:>1000",
|
||||
sort="works_count:desc",
|
||||
@@ -22,54 +22,128 @@ def test_list_topics_params_include_openalex_query_parameters():
|
||||
select="id,display_name",
|
||||
)
|
||||
|
||||
assert params == {
|
||||
"search": "machine learning",
|
||||
"filter": "domain.id:4,works_count:>1000",
|
||||
"sort": "works_count:desc",
|
||||
"group_by": "domain.id",
|
||||
"per_page": 10,
|
||||
"page": 2,
|
||||
"select": "id,display_name",
|
||||
"api_key": "test-key",
|
||||
assert body["query"] == {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"multi_match": {
|
||||
"query": "machine learning",
|
||||
"fields": client.DEFAULT_SEARCH_FIELDS,
|
||||
"type": "best_fields",
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
],
|
||||
"filter": [
|
||||
{"term": {"domain.id": "4"}},
|
||||
{"range": {"works_count": {"gt": "1000"}}},
|
||||
],
|
||||
"must_not": [],
|
||||
}
|
||||
}
|
||||
|
||||
assert body["_source"] == ["id", "display_name"]
|
||||
assert body["sort"] == [
|
||||
{"works_count": {"order": "desc", "missing": "_last"}}
|
||||
]
|
||||
|
||||
# group_by queries use aggregations and no regular hits
|
||||
assert body["size"] == 0
|
||||
assert body["from"] == 10
|
||||
assert body["track_total_hits"] is True
|
||||
assert body["aggs"] == {
|
||||
"group_by": {
|
||||
"terms": {
|
||||
"field": "domain.id",
|
||||
"size": 10,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def test_list_topics_params_prefers_cursor_over_page():
|
||||
client = OpenAlexTopicsClient(api_key="test-key")
|
||||
def test_build_search_body_prefers_cursor_over_page():
|
||||
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
|
||||
|
||||
params = client.list_topics_params(cursor="*", page=3)
|
||||
cursor = client._encode_cursor(["Machine learning", "https://openalex.org/T12419"])
|
||||
|
||||
assert params["cursor"] == "*"
|
||||
assert "page" not in params
|
||||
body = client.build_search_body(
|
||||
cursor=cursor,
|
||||
page=3,
|
||||
per_page=25,
|
||||
)
|
||||
|
||||
assert body["search_after"] == [
|
||||
"Machine learning",
|
||||
"https://openalex.org/T12419",
|
||||
]
|
||||
assert "from" not in body
|
||||
|
||||
|
||||
def test_build_search_body_with_plain_cursor_star_does_not_use_page_offset():
|
||||
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
|
||||
|
||||
body = client.build_search_body(
|
||||
cursor="*",
|
||||
page=3,
|
||||
per_page=25,
|
||||
)
|
||||
|
||||
assert "search_after" not in body
|
||||
assert "from" not in body
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_calls_openalex_topics_endpoint():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.method == "GET"
|
||||
assert request.url.path == "/topics"
|
||||
assert request.url.params["search"] == "machine learning"
|
||||
assert request.url.params["api_key"] == "test-key"
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
async def test_list_topics_calls_elasticsearch_search_wrapper(monkeypatch):
|
||||
captured = {}
|
||||
|
||||
async def fake_elasticsearch_search(*, index, body, cluster):
|
||||
captured["index"] = index
|
||||
captured["body"] = body
|
||||
captured["cluster"] = cluster
|
||||
|
||||
return {
|
||||
"took": 3,
|
||||
"hits": {
|
||||
"total": {"value": 1, "relation": "eq"},
|
||||
"hits": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"_id": "https://openalex.org/T12419",
|
||||
"_source": {
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
},
|
||||
"sort": [1000, "https://openalex.org/T12419"],
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
base_url="https://api.openalex.org",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
monkeypatch.setattr(
|
||||
"inse.topics.search_client.elasticsearch_search",
|
||||
fake_elasticsearch_search,
|
||||
)
|
||||
|
||||
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
|
||||
|
||||
result = await client.list_topics(search="machine learning")
|
||||
|
||||
assert result["meta"]["count"] == 1
|
||||
assert result["results"][0]["display_name"] == "Machine learning"
|
||||
assert captured["index"] == ESIndex.OPENALEX_TOPICS
|
||||
assert captured["cluster"] == ESCluster.NES
|
||||
|
||||
assert captured["body"]["query"]["bool"]["must"] == [
|
||||
{
|
||||
"multi_match": {
|
||||
"query": "machine learning",
|
||||
"fields": client.DEFAULT_SEARCH_FIELDS,
|
||||
"type": "best_fields",
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
]
|
||||
assert captured["body"]["size"] == 25
|
||||
assert captured["body"]["from"] == 0
|
||||
assert captured["body"]["track_total_hits"] is True
|
||||
|
||||
assert result["hits"]["total"]["value"] == 1
|
||||
assert result["hits"]["hits"][0]["_source"]["display_name"] == "Machine learning"
|
||||
assert result["meta"]["next_cursor"] is not None
|
||||
@@ -71,6 +71,7 @@ async def get_author_works(
|
||||
)
|
||||
|
||||
elements, total = _parse_full_work_search_response(data)
|
||||
await _enrich_work_topic_descriptions(elements)
|
||||
offset = (page - 1) * size
|
||||
last_page = offset + len(elements) >= total
|
||||
|
||||
@@ -166,6 +167,15 @@ async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
"primary_topics": {
|
||||
"terms": {"field": "primary_topic.id", "size": 1000},
|
||||
},
|
||||
"all_topics": {
|
||||
"nested": {"path": "topics"},
|
||||
"aggs": {
|
||||
"topic_ids": {
|
||||
"terms": {"field": "topics.id", "size": 1000},
|
||||
"aggs": {"works": {"reverse_nested": {}}},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -180,10 +190,25 @@ async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
|
||||
aggregations = response.get("aggregations", {})
|
||||
buckets = aggregations.get("primary_topics", {}).get("buckets", [])
|
||||
topic_buckets = (
|
||||
aggregations.get("all_topics", {}).get("topic_ids", {}).get("buckets", [])
|
||||
)
|
||||
|
||||
broad_counts = {
|
||||
bucket["key"]: bucket.get("works", {}).get("doc_count", bucket["doc_count"])
|
||||
for bucket in topic_buckets
|
||||
}
|
||||
|
||||
|
||||
counts = []
|
||||
for bucket in buckets:
|
||||
counts.append({"id": bucket["key"], "count": bucket["doc_count"]})
|
||||
topic_id = bucket["key"]
|
||||
counts.append(
|
||||
{
|
||||
"id": topic_id,
|
||||
"count": max(broad_counts.get(topic_id, 0), bucket["doc_count"]),
|
||||
}
|
||||
)
|
||||
|
||||
return counts
|
||||
|
||||
@@ -202,9 +227,44 @@ async def get_work(
|
||||
elements, _ = _parse_full_work_search_response(response_by_title)
|
||||
if not elements:
|
||||
return None
|
||||
await _enrich_work_topic_descriptions(elements[:1])
|
||||
return elements[0]
|
||||
|
||||
|
||||
async def enrich_topic_descriptions(topics: List) -> None:
|
||||
"""Batch-fill missing descriptions on dehydrated topics.
|
||||
|
||||
OpenAlex work and author documents carry dehydrated topics without a
|
||||
description, so we batch-load the details from the openalex-topics index.
|
||||
"""
|
||||
pending = [topic for topic in topics if topic.id and not topic.description]
|
||||
|
||||
if not pending:
|
||||
return
|
||||
|
||||
details = await _get_topic_details(list({topic.id for topic in pending}))
|
||||
|
||||
if not details:
|
||||
return
|
||||
|
||||
for topic in pending:
|
||||
info = details.get(topic.id)
|
||||
if info:
|
||||
topic.description = info.get("description")
|
||||
|
||||
|
||||
async def _enrich_work_topic_descriptions(works: List[Work]) -> None:
|
||||
topics = []
|
||||
|
||||
for work in works:
|
||||
topics.extend(work.topics or [])
|
||||
|
||||
if work.primary_topic:
|
||||
topics.append(work.primary_topic)
|
||||
|
||||
await enrich_topic_descriptions(topics)
|
||||
|
||||
|
||||
async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||
if not topic_ids:
|
||||
return {}
|
||||
|
||||
@@ -76,6 +76,7 @@ class OpenAlexWorksSearchClient:
|
||||
return {
|
||||
"from": (page - 1) * size,
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": must_clauses,
|
||||
|
||||
@@ -14,6 +14,7 @@ export interface AccountProfile {
|
||||
email: string;
|
||||
name: string;
|
||||
role: UserRole;
|
||||
permissions?: Array<string>;
|
||||
organization_id: string;
|
||||
organization_name: string;
|
||||
deleted: boolean;
|
||||
|
||||
@@ -6,6 +6,7 @@ import { collaborationNetworkResolver } from './resolvers/collaboration-network.
|
||||
import { personListResolver } from './resolvers/person-list.resolver';
|
||||
import { personBioResolver } from './resolvers/person-bio.resolver';
|
||||
import { personResolver } from './resolvers/person.resolver';
|
||||
import { personNewsResolver } from './resolvers/person-news.resolver';
|
||||
import { institutionResolver } from './resolvers/institution.resolver';
|
||||
import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver';
|
||||
import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver';
|
||||
@@ -23,7 +24,11 @@ import { accountViewerGuard } from './shared/guards/account-viewer.guard';
|
||||
import { accountsPageResolver } from './resolvers/accounts-page.resolver';
|
||||
import { accountsOrganizationResolver } from './resolvers/accounts-organizations.resolver';
|
||||
import { organizationsOrganizationsResolver } from './resolvers/organizations-organizations.resolver';
|
||||
|
||||
import { KeywordsToPersonsResultsComponent } from './modules/keywords-search/search-results/persons-results/persons-results.component';
|
||||
import { KeywordsToProjectsResultsComponent } from './modules/keywords-search/search-results/projects-results/projects-results.component';
|
||||
import { KeywordsToPatentsResultsComponent } from './modules/keywords-search/search-results/patents-results/patents-results.component';
|
||||
import { KeywordsToNewsResultsComponent } from './modules/keywords-search/search-results/news-results/news-results.component';
|
||||
import { KeywordsToWorksResultsComponent } from './modules/keywords-search/search-results/works-results/works-results.component';
|
||||
export const routes: Routes = [
|
||||
{
|
||||
path: '',
|
||||
@@ -102,6 +107,21 @@ export const routes: Routes = [
|
||||
(mod) => mod.KeywordsSearchComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'keywords/search-results',
|
||||
loadComponent: () =>
|
||||
import('./modules/keywords-search/search-results/search-results.component').then(
|
||||
(mod) => mod.KeywordsSearchResultsComponent,
|
||||
),
|
||||
children: [
|
||||
{ path: '', pathMatch: 'full', redirectTo: 'persons' },
|
||||
{ path: 'persons', component: KeywordsToPersonsResultsComponent },
|
||||
{ path: 'projects', component: KeywordsToProjectsResultsComponent },
|
||||
{ path: 'patents', component: KeywordsToPatentsResultsComponent },
|
||||
{ path: 'works', component: KeywordsToWorksResultsComponent },
|
||||
{ path: 'news', component: KeywordsToNewsResultsComponent },
|
||||
],
|
||||
},
|
||||
{
|
||||
path: 'news',
|
||||
canActivate: [userGuard],
|
||||
@@ -280,6 +300,23 @@ export const routes: Routes = [
|
||||
(mod) => mod.PersonFundingComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'news',
|
||||
loadComponent: () =>
|
||||
import('./modules/person-news/person-news.component').then(
|
||||
(mod) => mod.PersonNewsComponent,
|
||||
),
|
||||
resolve: {
|
||||
newsPage: personNewsResolver,
|
||||
},
|
||||
runGuardsAndResolvers: (from, to) => {
|
||||
const keys = ['page', 'pageSize', 'sortOrder', 'query'];
|
||||
|
||||
return keys.some(
|
||||
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'patents',
|
||||
loadComponent: () =>
|
||||
@@ -393,6 +430,20 @@ export const routes: Routes = [
|
||||
(mod) => mod.PatentsComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'news',
|
||||
canActivate: [userGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/news/news.component').then((mod) => mod.NewsComponent),
|
||||
},
|
||||
{
|
||||
path: 'news/:id',
|
||||
canActivate: [userGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/news-detail/news-detail.component').then(
|
||||
(mod) => mod.NewsDetailComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'error',
|
||||
loadComponent: () =>
|
||||
|
||||
@@ -63,7 +63,13 @@
|
||||
[formField]="changePasswordForm.showPasswords"
|
||||
>Passwörter anzeigen</mat-slide-toggle
|
||||
>
|
||||
<button mat-raised-button color="primary" type="submit">
|
||||
<button
|
||||
mat-raised-button
|
||||
color="primary"
|
||||
type="submit"
|
||||
[disabled]="
|
||||
changePasswordForm().invalid() || changePasswordForm().submitting()
|
||||
">
|
||||
Passwort ändern
|
||||
</button>
|
||||
</form>
|
||||
|
||||
@@ -28,6 +28,7 @@ import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
|
||||
import { CredentialService } from '../../shared/services/credential.service';
|
||||
import { MatSnackBar } from '@angular/material/snack-bar';
|
||||
import { Router } from '@angular/router';
|
||||
|
||||
interface ChangePasswordForm {
|
||||
oldPassword: string;
|
||||
@@ -62,6 +63,7 @@ export class AccountComponent {
|
||||
|
||||
private readonly _credentialService = inject(CredentialService);
|
||||
private readonly _snackBar = inject(MatSnackBar);
|
||||
private readonly _router = inject(Router);
|
||||
|
||||
roles: UserRole[] = [];
|
||||
|
||||
@@ -143,21 +145,36 @@ export class AccountComponent {
|
||||
const newPassword = field.newPassword().value().trim();
|
||||
|
||||
if (!oldPassword || !newPassword) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await this._credentialService.changePassword(
|
||||
oldPassword,
|
||||
newPassword,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Error changing password:', error);
|
||||
this._snackBar.open(
|
||||
'Fehler beim Ändern des Passworts. Bitte versuchen Sie es erneut.',
|
||||
'OK',
|
||||
{ duration: 7000 },
|
||||
);
|
||||
return {} as any;
|
||||
}
|
||||
this._credentialService
|
||||
.changePassword(oldPassword, newPassword)
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this._credentialService.refreshAccessToken().subscribe({
|
||||
next: () => {
|
||||
this._router.navigate(['/dashboard']);
|
||||
},
|
||||
error: (error) => {
|
||||
this._snackBar.open(
|
||||
'Fehler beim Aktualisieren des Zugriffstokens. Bitte melden Sie sich erneut an.',
|
||||
'OK',
|
||||
{ duration: 7000 },
|
||||
);
|
||||
},
|
||||
});
|
||||
},
|
||||
error: (error) => {
|
||||
console.error('Error changing password:', error);
|
||||
this._snackBar.open(
|
||||
'Fehler beim Ändern des Passworts. Bitte versuchen Sie es erneut.',
|
||||
'OK',
|
||||
{ duration: 7000 },
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
return {} as any;
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -83,7 +83,8 @@
|
||||
mat-stroked-button
|
||||
color="primary"
|
||||
(click)="deselectAll()"
|
||||
[disabled]="isExtracting()">
|
||||
[disabled]="isExtracting()"
|
||||
matTooltip="Alle extrahierten Keywords abwählen">
|
||||
<mat-icon>select_all</mat-icon>
|
||||
<span>Alle abwählen</span>
|
||||
</button>
|
||||
@@ -98,9 +99,17 @@
|
||||
<span>Alle auswählen</span>
|
||||
</button>
|
||||
}
|
||||
<button
|
||||
mat-stroked-button
|
||||
color="warn"
|
||||
[disabled]="isExtracting()"
|
||||
(click)="clearKeywords()"
|
||||
matTooltip="Alle extrahierten Keywords löschen">
|
||||
<mat-icon>delete_outline</mat-icon>
|
||||
<span>Alle löschen</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="toolbar-divider"></div>
|
||||
|
||||
<mat-button-toggle-group
|
||||
[value]="keywordView()"
|
||||
(change)="onViewToggleChange($event.value)"
|
||||
@@ -112,26 +121,26 @@
|
||||
<mat-icon>text_fields</mat-icon>
|
||||
<span>Extrahierte Keywords</span>
|
||||
</mat-button-toggle>
|
||||
<mat-button-toggle
|
||||
[disabled]="isExtracting()"
|
||||
value="topic"
|
||||
matTooltip="Topic Mapping">
|
||||
<mat-icon>account_tree</mat-icon>
|
||||
<span>Topic Mapping</span>
|
||||
</mat-button-toggle>
|
||||
@if (topicMappingSearch()) {
|
||||
<mat-button-toggle
|
||||
[disabled]="isExtracting()"
|
||||
value="topic"
|
||||
matTooltip="Topic Mapping">
|
||||
<mat-icon>account_tree</mat-icon>
|
||||
<span>Topic Mapping</span>
|
||||
</mat-button-toggle>
|
||||
}
|
||||
</mat-button-toggle-group>
|
||||
<div class="toolbar-divider"></div>
|
||||
|
||||
<div class="toolbar-group toolbar-group--view">
|
||||
<button
|
||||
mat-stroked-button
|
||||
color="warn"
|
||||
[disabled]="isExtracting()"
|
||||
(click)="clearKeywords()"
|
||||
matTooltip="Alle extrahierten Keywords löschen">
|
||||
<mat-icon>delete_outline</mat-icon>
|
||||
<span>Alle löschen</span>
|
||||
</button>
|
||||
<mat-slide-toggle
|
||||
(change)="onToggleTopicMappingSearch($event)"
|
||||
labelPosition="before"
|
||||
[checked]="topicMappingSearch()"
|
||||
class="mapping-toggle">
|
||||
Topic Mapping
|
||||
</mat-slide-toggle>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -344,14 +353,16 @@
|
||||
<mat-expansion-panel-header>
|
||||
<mat-panel-title>Quellentext: {{ sourceUrl() }}</mat-panel-title>
|
||||
</mat-expansion-panel-header>
|
||||
<div class="source-text">{{ sourceContent() }}</div>
|
||||
<div
|
||||
class="source-text"
|
||||
[innerHTML]="highlightedSourceContent()"></div>
|
||||
</mat-expansion-panel>
|
||||
}
|
||||
</mat-card-content>
|
||||
@if (isExtracting() && !keywordsExist()) {
|
||||
<app-loading
|
||||
text="{{ statusMessage() }}"
|
||||
icon="group"
|
||||
icon="manage_search"
|
||||
[size]="200"
|
||||
[diameter]="200" />
|
||||
}
|
||||
@@ -363,8 +374,8 @@
|
||||
</div>
|
||||
|
||||
@if (keywordsExist()) {
|
||||
<!-- Search Buttons -->
|
||||
<div class="search-container" style="display: flex; gap: 1rem">
|
||||
<!-- Search buttons -->
|
||||
<div class="search-actions">
|
||||
<button
|
||||
mat-flat-button
|
||||
color="primary"
|
||||
@@ -374,6 +385,7 @@
|
||||
<mat-icon>search</mat-icon>
|
||||
Suchen
|
||||
</button>
|
||||
|
||||
<button
|
||||
mat-flat-button
|
||||
color="accent"
|
||||
|
||||
@@ -50,23 +50,26 @@ $touch-target: 44px;
|
||||
|
||||
::ng-deep app-topic-legend .topic-legend {
|
||||
width: 100%;
|
||||
|
||||
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
|
||||
border-bottom: none;
|
||||
border-radius: 4px;
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.toolbar-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
justify-content: space-around;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: nowrap; /* fixed: was invalid "no-wrap" */
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: var(--sg-background-muted, #f4f5f7);
|
||||
}
|
||||
.toolbar-wrapper {
|
||||
display: grid;
|
||||
grid-template-columns: 3fr 1.3fr;
|
||||
border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08));
|
||||
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.toolbar-controls--placeholder {
|
||||
@@ -78,6 +81,25 @@ $touch-target: 44px;
|
||||
.manual-input-controls {
|
||||
min-width: 0;
|
||||
}
|
||||
.toolbar-group {
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
gap: auto;
|
||||
|
||||
::ng-deep .mdc-switch {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
}
|
||||
::ng-deep .mdc-form-field {
|
||||
position: relative;
|
||||
min-width: 90px;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
::ng-deep .mdc-label {
|
||||
position: absolute;
|
||||
top: 30px;
|
||||
}
|
||||
}
|
||||
|
||||
@container keyword-tool (max-width: #{$tablet}) {
|
||||
.toolbar-wrapper {
|
||||
@@ -92,8 +114,10 @@ $touch-target: 44px;
|
||||
|
||||
.toolbar-group {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: nowrap; /* fixed: was invalid "no-wrap" */
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.toolbar-group button {
|
||||
@@ -188,14 +212,13 @@ mat-button-toggle-group {
|
||||
}
|
||||
|
||||
.keyword-card {
|
||||
background-color: var(--sg-background);
|
||||
padding: 0.5rem;
|
||||
|
||||
padding: 0 !important;
|
||||
background: var(--sg-background-muted, #f4f5f7);
|
||||
.mat-card-header {
|
||||
padding: 0 0 0.5rem 0;
|
||||
}
|
||||
|
||||
.mat-card-content {
|
||||
.mat-mdc-card-content {
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
@@ -209,12 +232,12 @@ mat-button-toggle-group {
|
||||
}
|
||||
|
||||
.table-head {
|
||||
border-top: 2px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
|
||||
padding-top: 0.5rem;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr) 1.3fr;
|
||||
column-gap: 1rem;
|
||||
border-bottom: 2px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||
border-bottom: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
|
||||
padding-bottom: 0.5rem;
|
||||
background: var(--sg-background-muted, #f4f5f7);
|
||||
}
|
||||
@@ -235,12 +258,13 @@ mat-button-toggle-group {
|
||||
}
|
||||
|
||||
.table-body {
|
||||
min-height: 200px;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr) 1.3fr;
|
||||
column-gap: 1rem;
|
||||
row-gap: 0.4rem;
|
||||
align-items: start;
|
||||
border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08));
|
||||
//border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
|
||||
}
|
||||
|
||||
.table-col {
|
||||
@@ -249,7 +273,7 @@ mat-button-toggle-group {
|
||||
min-width: 0;
|
||||
padding: 0.5rem;
|
||||
height: 100%;
|
||||
border-right: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08));
|
||||
border-right: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
|
||||
|
||||
&:last-child {
|
||||
border-right: none;
|
||||
@@ -263,10 +287,14 @@ mat-button-toggle-group {
|
||||
width: 100%;
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
::ng-deep app-topic-chip .topic-chip__count {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.thick-border {
|
||||
border-right: 5px solid var(--sg-divider, rgba(0, 0, 0, 0.1)) !important;
|
||||
border-right: 5px solid var(--sg-divider, rgba(0, 0, 0, 0.08)) !important;
|
||||
}
|
||||
|
||||
@container keyword-tool (max-width: #{$tablet}) {
|
||||
@@ -411,33 +439,68 @@ mat-button-toggle-group {
|
||||
opacity: 0.6;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
SEARCH BUTTON (sticky on mobile — improves conversion/UX)
|
||||
SEARCH BUTTONS
|
||||
============================================================ */
|
||||
.search-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin-top: 0.5rem;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
margin-top: 1rem;
|
||||
padding: 0 1rem;
|
||||
}
|
||||
|
||||
.search-btn {
|
||||
min-width: 240px;
|
||||
align-self: center;
|
||||
.search-actions {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.search-btn,
|
||||
.visualize-btn {
|
||||
min-width: 220px;
|
||||
min-height: $touch-target;
|
||||
align-self: center;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Tablet */
|
||||
@media (max-width: $tablet) {
|
||||
.search-container {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.search-actions {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.search-btn,
|
||||
.visualize-btn {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
/* Phone */
|
||||
@media (max-width: $phone) {
|
||||
.search-container {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
z-index: 5;
|
||||
background: var(--sg-background);
|
||||
background: var(--sg-background, #fff);
|
||||
padding: 0.75rem 0.5rem;
|
||||
margin-top: 0.75rem;
|
||||
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.search-btn {
|
||||
.search-actions {
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.search-btn,
|
||||
.visualize-btn {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
@@ -504,7 +567,7 @@ mat-button-toggle-group {
|
||||
margin: 0.75rem 0;
|
||||
background: var(--sg-background-muted, #f5f5f5);
|
||||
border-radius: 4px;
|
||||
border-left: 4px solid var(--sg-primary, #1976d2);
|
||||
//border-left: 4px solid var(--sg-primary, #1976d2);
|
||||
|
||||
.mat-expansion-panel-header {
|
||||
padding: 0.5rem 0.75rem;
|
||||
@@ -554,7 +617,6 @@ mat-button-toggle-group {
|
||||
PROGRESS BAR
|
||||
============================================================ */
|
||||
.progress-container {
|
||||
min-height: 300px;
|
||||
margin-top: 0.5rem;
|
||||
position: relative;
|
||||
padding: 1rem;
|
||||
|
||||
@@ -28,8 +28,10 @@ import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.compon
|
||||
import { TopicLegendComponent } from '../../shared/ui/topic-legend/topic-legend.component';
|
||||
import { Topic } from '../../api/model/topic';
|
||||
import { NgTemplateOutlet } from '@angular/common';
|
||||
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
import { MatSliderModule } from '@angular/material/slider';
|
||||
import {
|
||||
MatButtonToggleModule,
|
||||
MatButtonToggleGroup,
|
||||
@@ -45,6 +47,8 @@ import {
|
||||
} from '../../resolvers/utils/topic-legend';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { A11yModule } from '@angular/cdk/a11y';
|
||||
import { DomSanitizer } from '@angular/platform-browser';
|
||||
import { SearchResultsPayload } from './search-results/search-results-state.service';
|
||||
type InputMode = 'url' | 'text';
|
||||
type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual';
|
||||
type KeywordView = 'llm' | 'topic';
|
||||
@@ -71,12 +75,15 @@ type KeywordView = 'llm' | 'topic';
|
||||
A11yModule,
|
||||
NgTemplateOutlet,
|
||||
LoadingComponent,
|
||||
MatSlideToggleModule,
|
||||
MatSliderModule,
|
||||
],
|
||||
templateUrl: './keywords-search.component.html',
|
||||
styleUrl: './keywords-search.component.scss',
|
||||
})
|
||||
export class KeywordsSearchComponent {
|
||||
private readonly formBuilder = inject(FormBuilder);
|
||||
private readonly sanitizer = inject(DomSanitizer);
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
private readonly router = inject(Router);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
@@ -90,6 +97,8 @@ export class KeywordsSearchComponent {
|
||||
});
|
||||
|
||||
private readonly SESSION_KEY = 'keywords-search-source';
|
||||
private readonly SEARCH_RESULTS_HANDOFF_KEY = 'search-results-handoff';
|
||||
|
||||
// in component class:
|
||||
private breakpointObserver = inject(BreakpointObserver);
|
||||
|
||||
@@ -116,6 +125,7 @@ export class KeywordsSearchComponent {
|
||||
readonly loadingNewKeyword = signal(false);
|
||||
readonly extractionSource = signal<InputMode | null>(null);
|
||||
readonly showVisualization = signal<boolean>(false);
|
||||
readonly topicMappingSearch = signal<boolean>(false);
|
||||
|
||||
readonly keywordsExist = computed(
|
||||
() =>
|
||||
@@ -128,6 +138,55 @@ export class KeywordsSearchComponent {
|
||||
readonly sourceContent = signal<string>('');
|
||||
readonly sourceUrl = signal<string | null>(null);
|
||||
|
||||
readonly highlightedSourceContent = computed(() => {
|
||||
const content = this.sourceContent();
|
||||
if (!content) return '';
|
||||
|
||||
const selectedKeywords = this.selectedKeywords();
|
||||
if (selectedKeywords.length === 0) return content;
|
||||
|
||||
let highlightedContent = content;
|
||||
|
||||
// replace the keyword with highlighted spans
|
||||
for (const keyword of selectedKeywords) {
|
||||
const normalizedKeyword = this.normalizeKeyword(keyword);
|
||||
|
||||
// Find the first keyword entry that matches this normalized keyword
|
||||
const entry = this.allKeywordEntries().find(
|
||||
(e) =>
|
||||
this.normalizeKeyword(this.getKeywordLabel(e)) === normalizedKeyword,
|
||||
);
|
||||
|
||||
if (entry) {
|
||||
const topic = this.getTopic(entry);
|
||||
if (topic) {
|
||||
const color = this.getTopicColor(topic);
|
||||
// Escape HTML special characters in the keyword before using it in HTML
|
||||
const escapedKeyword = keyword
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
|
||||
// Create the replacement span HTML
|
||||
const replacement = `<span style="text-decoration: underline; background-color: color-mix(in srgb, ${color} 27%, #ffffff); 100%); font-weight: bold;" title="Keyword: ${keyword}">${escapedKeyword}</span>`;
|
||||
|
||||
const escapedRegexKeyword = keyword.replace(
|
||||
/[.*+?^${}()|[\]\\]/g,
|
||||
'\\$&',
|
||||
);
|
||||
const regex = new RegExp(escapedRegexKeyword, 'g');
|
||||
|
||||
highlightedContent = highlightedContent.replace(regex, replacement);
|
||||
}
|
||||
}
|
||||
}
|
||||
console.log(
|
||||
'Highlighted content:',
|
||||
this.sanitizer.bypassSecurityTrustHtml(highlightedContent),
|
||||
);
|
||||
return this.sanitizer.bypassSecurityTrustHtml(highlightedContent);
|
||||
});
|
||||
|
||||
private isRestoringState = false;
|
||||
|
||||
// Set right before we call router.navigate() ourselves (from
|
||||
@@ -161,9 +220,6 @@ export class KeywordsSearchComponent {
|
||||
constructor() {
|
||||
this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe(() => {
|
||||
if (this.isOwnNavigation) {
|
||||
// This emission is just the router confirming the navigation we
|
||||
// triggered ourselves in updateQueryParams(); our signals are
|
||||
// already correct, so skip re-deriving state from the URL.
|
||||
this.isOwnNavigation = false;
|
||||
return;
|
||||
}
|
||||
@@ -186,15 +242,13 @@ export class KeywordsSearchComponent {
|
||||
.getMessages()
|
||||
.subscribe((event: WsEvent) => this.handleWsEvent(event));
|
||||
|
||||
// Clear session storage on component destroy, unless this is a page
|
||||
// reload (in which case we want the cache to survive).
|
||||
this.destroyRef.onDestroy(() => {
|
||||
this.websocketService.close();
|
||||
const isReload = this.router.lastSuccessfulNavigation === null;
|
||||
if (!isReload) {
|
||||
this.clearSourceFromSession();
|
||||
}
|
||||
});
|
||||
// this.destroyRef.onDestroy(() => {
|
||||
// this.websocketService.close();
|
||||
// const isReload = this.router.lastSuccessfulNavigation === null;
|
||||
// if (!isReload) {
|
||||
// this.clearStateFromSession();
|
||||
// }
|
||||
// });
|
||||
}
|
||||
|
||||
// --- Websocket event handling ---------------------------------------
|
||||
@@ -461,7 +515,7 @@ export class KeywordsSearchComponent {
|
||||
this.extractionSource.set(null);
|
||||
|
||||
// updateQueryParams() persists this cleared state to sessionStorage too
|
||||
// (see saveSourceToSession() call inside it), so there's no need to
|
||||
// (see saveStateToSession() call inside it), so there's no need to
|
||||
// separately wipe the session key here.
|
||||
this.updateQueryParams();
|
||||
}
|
||||
@@ -513,7 +567,7 @@ export class KeywordsSearchComponent {
|
||||
this.selectedKeywords().filter((k) => allExtracted.includes(k)),
|
||||
);
|
||||
|
||||
// updateQueryParams() also calls saveSourceToSession() - no need to call
|
||||
// updateQueryParams() also calls saveStateToSession() - no need to call
|
||||
// it separately here.
|
||||
this.updateQueryParams();
|
||||
}
|
||||
@@ -554,15 +608,34 @@ export class KeywordsSearchComponent {
|
||||
|
||||
search(): void {
|
||||
this.showVisualization.set(false);
|
||||
const payload = {
|
||||
|
||||
const payload: SearchResultsPayload = {
|
||||
extractedKeywords: this.getSelectedExtractedKeywordEntries(),
|
||||
manualKeywords: this.getSelectedManualKeywordEntries(),
|
||||
keywords: this.selectedKeywords(),
|
||||
options: {
|
||||
softSearch: this.topicMappingSearch(),
|
||||
},
|
||||
};
|
||||
|
||||
console.log('searching for keywords:', payload);
|
||||
// e.g. navigate to search results page with the full payload in navigation state
|
||||
// this.router.navigate(['/search'], { state: payload });
|
||||
// Best-effort cache for the heavier, topic-enriched entries.
|
||||
// Not authoritative — search-results must work without it.
|
||||
try {
|
||||
sessionStorage.setItem(
|
||||
this.SEARCH_RESULTS_HANDOFF_KEY,
|
||||
JSON.stringify(payload),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Failed to cache search-results handoff:', error);
|
||||
}
|
||||
|
||||
// Authoritative, reload-safe, shareable.
|
||||
this.router.navigate(['keywords/search-results'], {
|
||||
queryParams: {
|
||||
keywords: this.serializeKeywords(payload.keywords),
|
||||
softSearch: payload.options.softSearch ? true : false,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
visualize(): void {
|
||||
@@ -621,14 +694,16 @@ export class KeywordsSearchComponent {
|
||||
this.normalizeKeyword(this.getKeywordLabel(item)) !== normalized,
|
||||
);
|
||||
}
|
||||
|
||||
onViewToggleChange(value: KeywordView): void {
|
||||
if (this.keywordView() !== value) {
|
||||
this.keywordView.set(value);
|
||||
}
|
||||
this.updateQueryParams();
|
||||
}
|
||||
|
||||
onToggleTopicMappingSearch(event: any): void {
|
||||
this.topicMappingSearch.set(event.checked);
|
||||
this.updateQueryParams();
|
||||
}
|
||||
onSubfieldLegendVisibleChange(visible: boolean): void {
|
||||
this.subfieldLegendVisible.set(visible);
|
||||
this.updateQueryParams();
|
||||
@@ -759,18 +834,23 @@ export class KeywordsSearchComponent {
|
||||
const view = queryParams.get('view') ?? 'llm';
|
||||
const legend = queryParams.get('legend') ?? 'on';
|
||||
const legendExpanded = queryParams.get('legendExpanded') ?? 'off';
|
||||
|
||||
const softSearch = queryParams.get('softSearch') === 'true';
|
||||
this.isRestoringState = true;
|
||||
|
||||
this.form.patchValue(
|
||||
{ selectedInputType: mode, urlInput, textInput },
|
||||
{
|
||||
selectedInputType: mode,
|
||||
urlInput,
|
||||
textInput,
|
||||
},
|
||||
{ emitEvent: false },
|
||||
);
|
||||
this.keywordView.set(view as KeywordView);
|
||||
this.subfieldLegendVisible.set(legend === 'on');
|
||||
this.subfieldLegendExpanded.set(legendExpanded === 'on');
|
||||
this.extractionSource.set(source as InputMode);
|
||||
this.restoreSourceFromSession();
|
||||
this.topicMappingSearch.set(softSearch);
|
||||
this.restoreStateFromSession();
|
||||
|
||||
const merged = this.uniqueKeywordEntries([
|
||||
...this.manualKeywordEntries(), // session restored entries
|
||||
@@ -808,7 +888,7 @@ export class KeywordsSearchComponent {
|
||||
this.normalizeKeyword(k),
|
||||
),
|
||||
);
|
||||
const validSelected = selected.filter(
|
||||
const validSelected = [...this.selectedKeywords(), ...selected].filter(
|
||||
(k) =>
|
||||
manualKeywordSet.has(this.normalizeKeyword(k)) ||
|
||||
broadKeywordSet.has(this.normalizeKeyword(k)) ||
|
||||
@@ -837,6 +917,7 @@ export class KeywordsSearchComponent {
|
||||
view: this.keywordView(),
|
||||
legend: this.subfieldLegendVisible() ? 'on' : 'off',
|
||||
legendExpanded: this.subfieldLegendExpanded() ? 'on' : 'off',
|
||||
softSearch: this.topicMappingSearch() ? true : false,
|
||||
broad: this.serializeKeywords(
|
||||
this.getKeywordLabels(this.broadKeywords()),
|
||||
),
|
||||
@@ -873,13 +954,13 @@ export class KeywordsSearchComponent {
|
||||
// session cache was only saved after a full extraction completed, so
|
||||
// adding a manual keyword (or removing one, etc.) never updated it. The
|
||||
// *next* query-param change then triggered restoreStateFromQueryParams()
|
||||
// -> restoreSourceFromSession(), which overwrote the fresh manual
|
||||
// -> restoreStateFromSession(), which overwrote the fresh manual
|
||||
// keyword with that stale snapshot - making manually added keywords
|
||||
// seem to vanish immediately. Saving here fixes that race.
|
||||
this.saveSourceToSession();
|
||||
this.saveStateToSession();
|
||||
}
|
||||
|
||||
private saveSourceToSession(): void {
|
||||
private saveStateToSession(): void {
|
||||
const data = {
|
||||
source: this.extractionSource(),
|
||||
sourceContent: this.sourceContent(),
|
||||
@@ -888,6 +969,7 @@ export class KeywordsSearchComponent {
|
||||
coarseKeywordEntries: this.coarseKeywordEntries(),
|
||||
fineKeywordEntries: this.fineKeywordEntries(),
|
||||
manualKeywordEntries: this.manualKeywordEntries(),
|
||||
selectedKeywords: this.selectedKeywords(),
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -897,7 +979,7 @@ export class KeywordsSearchComponent {
|
||||
}
|
||||
}
|
||||
|
||||
private restoreSourceFromSession(): void {
|
||||
private restoreStateFromSession(): void {
|
||||
const raw = sessionStorage.getItem(this.SESSION_KEY);
|
||||
if (!raw) return;
|
||||
|
||||
@@ -910,6 +992,7 @@ export class KeywordsSearchComponent {
|
||||
coarseKeywordEntries,
|
||||
fineKeywordEntries,
|
||||
manualKeywordEntries,
|
||||
selectedKeywords,
|
||||
} = JSON.parse(raw);
|
||||
|
||||
this.extractionSource.set(source as InputMode);
|
||||
@@ -919,12 +1002,13 @@ export class KeywordsSearchComponent {
|
||||
this.coarseKeywordEntries.set(coarseKeywordEntries ?? []);
|
||||
this.fineKeywordEntries.set(fineKeywordEntries ?? []);
|
||||
this.manualKeywordEntries.set(manualKeywordEntries ?? []);
|
||||
this.selectedKeywords.set(selectedKeywords ?? []);
|
||||
} catch {
|
||||
sessionStorage.removeItem(this.SESSION_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
private clearSourceFromSession(): void {
|
||||
private clearStateFromSession(): void {
|
||||
sessionStorage.removeItem(this.SESSION_KEY);
|
||||
}
|
||||
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
<div class="result-layout">
|
||||
<mat-card class="results-card">
|
||||
<mat-card-content class="results-placeholder">
|
||||
<mat-icon>groups</mat-icon>
|
||||
<h2>Newsliste</h2>
|
||||
<p>
|
||||
Die aktuelle Gewichtung ist unter <code>normalized</code> verfügbar.
|
||||
</p>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
|
||||
<mat-card class="weights-card">
|
||||
<mat-card-content>
|
||||
<app-weights-sliders
|
||||
[options]="weightOptions"
|
||||
[initialWeights]="defaultWeights"
|
||||
title="News-Gewichtung"
|
||||
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
|
||||
resetLabel="Ausgewogen"
|
||||
applyLabel="Neu gewichten"
|
||||
normalizedTitle="Normalisiert"
|
||||
queryParamPrefix="newsW_"
|
||||
[persistInQueryParams]="true"
|
||||
[showApplyButton]="true"
|
||||
[showResetButton]="true"
|
||||
[showNormalizedPreview]="true"
|
||||
(weightsChange)="onWeightsChange($event)"
|
||||
(applyWeights)="onApplyWeights($event)" />
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* ============================================================
|
||||
RESULT LAYOUT
|
||||
============================================================ */
|
||||
.result-layout {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(300px, 420px) 1fr;
|
||||
grid-template-areas: 'summary results';
|
||||
gap: 0.75rem;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.search-summary-card {
|
||||
grid-area: summary;
|
||||
}
|
||||
|
||||
.results-card {
|
||||
grid-area: results;
|
||||
}
|
||||
|
||||
.search-summary-card,
|
||||
.results-card {
|
||||
background: var(--sg-surface, #ffffff);
|
||||
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||
box-shadow: none;
|
||||
|
||||
.mat-mdc-card-content {
|
||||
padding: 0.75rem;
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
import { Component, inject, signal } from '@angular/core';
|
||||
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
|
||||
import {
|
||||
WeightMap,
|
||||
WeightSliderOption,
|
||||
WeightsSlidersComponent,
|
||||
WeightsSlidersValue,
|
||||
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
|
||||
|
||||
import { SearchResultsStateService } from '../search-results-state.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-news-results',
|
||||
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
|
||||
templateUrl: './news-results.component.html',
|
||||
styleUrl: './news-results.component.scss',
|
||||
})
|
||||
export class KeywordsToNewsResultsComponent {
|
||||
// injects the state set by the parent route — no duplicate parsing here
|
||||
private readonly state = inject(SearchResultsStateService);
|
||||
|
||||
readonly defaultWeights: WeightMap = {
|
||||
param1: 0.33,
|
||||
param2: 0.33,
|
||||
param3: 0.34,
|
||||
};
|
||||
|
||||
readonly weightOptions: WeightSliderOption[] = [
|
||||
{
|
||||
key: 'param1',
|
||||
label: 'Parameter 1',
|
||||
icon: 'workspace_premium',
|
||||
description: 'Gewichtet Parameter 1.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wParam1',
|
||||
},
|
||||
{
|
||||
key: 'param2',
|
||||
label: 'Parameter 2',
|
||||
icon: 'workspace_premium',
|
||||
description: 'Gewichtet Parameter 2.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wParam2',
|
||||
},
|
||||
{
|
||||
key: 'param3',
|
||||
label: 'Parameter 3',
|
||||
icon: 'workspace_premium',
|
||||
description: 'Gewichtet Parameter 3.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wParam3',
|
||||
},
|
||||
];
|
||||
|
||||
readonly currentWeights = signal<WeightsSlidersValue>({
|
||||
raw: this.defaultWeights,
|
||||
normalized: {
|
||||
param1: 0.33,
|
||||
param2: 0.33,
|
||||
param3: 0.34,
|
||||
},
|
||||
rawSum: 2.5,
|
||||
normalizedSum: 1,
|
||||
valid: true,
|
||||
});
|
||||
|
||||
readonly projects = signal<unknown[]>([]); // placeholder until the results service lands
|
||||
|
||||
private hasLoadedInitial = false;
|
||||
constructor() {
|
||||
console.log('check', this.state.payload());
|
||||
}
|
||||
onWeightsChange(value: WeightsSlidersValue): void {
|
||||
this.currentWeights.set(value);
|
||||
|
||||
// fires once with the query-param-aware initial state — use it to load
|
||||
if (!this.hasLoadedInitial) {
|
||||
this.hasLoadedInitial = true;
|
||||
this.loadprojects();
|
||||
}
|
||||
}
|
||||
|
||||
onApplyWeights(value: WeightsSlidersValue): void {
|
||||
this.currentWeights.set(value);
|
||||
this.loadprojects();
|
||||
}
|
||||
|
||||
private loadprojects(): void {
|
||||
const weights = this.currentWeights();
|
||||
|
||||
const requestPayload = {
|
||||
manualKeywords: this.state.manualKeywords(),
|
||||
extractedKeywords: this.state.extractedKeywords(),
|
||||
keywords: this.state.keywords(),
|
||||
softSearch: this.state.softSearch(),
|
||||
weights: {
|
||||
raw: weights.raw,
|
||||
normalized: weights.normalized,
|
||||
},
|
||||
};
|
||||
|
||||
console.log(requestPayload);
|
||||
|
||||
/**
|
||||
* TODO:
|
||||
* this.projectsService.searchprojects(requestPayload).subscribe({
|
||||
* next: results => this.projects.set(results),
|
||||
* error: error => console.error(error),
|
||||
* });
|
||||
*/
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
<div class="result-layout">
|
||||
<mat-card class="results-card">
|
||||
<mat-card-content class="results-placeholder">
|
||||
<mat-icon>groups</mat-icon>
|
||||
<h2>Patentenliste</h2>
|
||||
<p>
|
||||
Die aktuelle Gewichtung ist unter <code>normalized</code> verfügbar.
|
||||
</p>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
|
||||
<mat-card class="weights-card">
|
||||
<mat-card-content>
|
||||
<app-weights-sliders
|
||||
[options]="weightOptions"
|
||||
[initialWeights]="defaultWeights"
|
||||
title="Patenten-Gewichtung"
|
||||
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
|
||||
resetLabel="Ausgewogen"
|
||||
applyLabel="Neu gewichten"
|
||||
normalizedTitle="Normalisiert"
|
||||
queryParamPrefix="patentW_"
|
||||
[persistInQueryParams]="true"
|
||||
[showApplyButton]="true"
|
||||
[showResetButton]="true"
|
||||
[showNormalizedPreview]="true"
|
||||
(weightsChange)="onWeightsChange($event)"
|
||||
(applyWeights)="onApplyWeights($event)" />
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* ============================================================
|
||||
RESULT LAYOUT
|
||||
============================================================ */
|
||||
.result-layout {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(300px, 420px) 1fr;
|
||||
grid-template-areas: 'summary results';
|
||||
gap: 0.75rem;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.search-summary-card {
|
||||
grid-area: summary;
|
||||
}
|
||||
|
||||
.results-card {
|
||||
grid-area: results;
|
||||
}
|
||||
|
||||
.search-summary-card,
|
||||
.results-card {
|
||||
background: var(--sg-surface, #ffffff);
|
||||
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||
box-shadow: none;
|
||||
|
||||
.mat-mdc-card-content {
|
||||
padding: 0.75rem;
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
import { Component, inject, signal } from '@angular/core';
|
||||
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
|
||||
import {
|
||||
WeightMap,
|
||||
WeightSliderOption,
|
||||
WeightsSlidersComponent,
|
||||
WeightsSlidersValue,
|
||||
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
|
||||
import { SearchResultsStateService } from '../search-results-state.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-patents-results',
|
||||
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
|
||||
templateUrl: './patents-results.component.html',
|
||||
styleUrl: './patents-results.component.scss',
|
||||
})
|
||||
export class KeywordsToPatentsResultsComponent {
|
||||
// injects the state set by the parent route — no duplicate parsing here
|
||||
private readonly state = inject(SearchResultsStateService);
|
||||
|
||||
readonly defaultWeights: WeightMap = {
|
||||
param1: 0.33,
|
||||
param2: 0.33,
|
||||
param3: 0.34,
|
||||
};
|
||||
|
||||
readonly weightOptions: WeightSliderOption[] = [
|
||||
{
|
||||
key: 'param1',
|
||||
label: 'Parameter 1',
|
||||
icon: 'workspace_premium',
|
||||
description: 'Gewichtet Parameter 1.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wParam1',
|
||||
},
|
||||
{
|
||||
key: 'param2',
|
||||
label: 'Parameter 2',
|
||||
icon: 'workspace_premium',
|
||||
description: 'Gewichtet Parameter 2.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wParam2',
|
||||
},
|
||||
{
|
||||
key: 'param3',
|
||||
label: 'Parameter 3',
|
||||
icon: 'workspace_premium',
|
||||
description: 'Gewichtet Parameter 3.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wParam3',
|
||||
},
|
||||
];
|
||||
|
||||
readonly currentWeights = signal<WeightsSlidersValue>({
|
||||
raw: this.defaultWeights,
|
||||
normalized: {
|
||||
param1: 0.33,
|
||||
param2: 0.33,
|
||||
param3: 0.34,
|
||||
},
|
||||
rawSum: 2.5,
|
||||
normalizedSum: 1,
|
||||
valid: true,
|
||||
});
|
||||
|
||||
readonly projects = signal<unknown[]>([]); // placeholder until the results service lands
|
||||
|
||||
private hasLoadedInitial = false;
|
||||
|
||||
onWeightsChange(value: WeightsSlidersValue): void {
|
||||
this.currentWeights.set(value);
|
||||
|
||||
// fires once with the query-param-aware initial state — use it to load
|
||||
if (!this.hasLoadedInitial) {
|
||||
this.hasLoadedInitial = true;
|
||||
this.loadprojects();
|
||||
}
|
||||
}
|
||||
|
||||
onApplyWeights(value: WeightsSlidersValue): void {
|
||||
this.currentWeights.set(value);
|
||||
this.loadprojects();
|
||||
}
|
||||
|
||||
private loadprojects(): void {
|
||||
const weights = this.currentWeights();
|
||||
|
||||
const requestPayload = {
|
||||
manualKeywords: this.state.manualKeywords(),
|
||||
extractedKeywords: this.state.extractedKeywords(),
|
||||
keywords: this.state.keywords(),
|
||||
softSearch: this.state.softSearch(),
|
||||
weights: {
|
||||
raw: weights.raw,
|
||||
normalized: weights.normalized,
|
||||
},
|
||||
};
|
||||
|
||||
console.log(requestPayload);
|
||||
|
||||
/**
|
||||
* TODO:
|
||||
* this.projectsService.searchprojects(requestPayload).subscribe({
|
||||
* next: results => this.projects.set(results),
|
||||
* error: error => console.error(error),
|
||||
* });
|
||||
*/
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
<div class="result-layout">
|
||||
<mat-card class="results-card">
|
||||
<mat-card-content class="results-placeholder">
|
||||
<mat-icon>groups</mat-icon>
|
||||
<h2>Personenliste</h2>
|
||||
<p>
|
||||
Die aktuelle Gewichtung ist unter <code>normalized</code> verfügbar.
|
||||
</p>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
|
||||
<mat-card class="weights-card">
|
||||
<mat-card-content>
|
||||
<app-weights-sliders
|
||||
[options]="weightOptions"
|
||||
[initialWeights]="defaultWeights"
|
||||
title="Personen-Gewichtung"
|
||||
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
|
||||
resetLabel="Ausgewogen"
|
||||
applyLabel="Neu gewichten"
|
||||
normalizedTitle="Normalisiert"
|
||||
queryParamPrefix="personW_"
|
||||
[persistInQueryParams]="true"
|
||||
[showApplyButton]="true"
|
||||
[showResetButton]="true"
|
||||
[showNormalizedPreview]="true"
|
||||
(weightsChange)="onWeightsChange($event)"
|
||||
(applyWeights)="onApplyWeights($event)" />
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* ============================================================
|
||||
RESULT LAYOUT
|
||||
============================================================ */
|
||||
.result-layout {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(300px, 420px) 1fr;
|
||||
grid-template-areas: 'summary results';
|
||||
gap: 0.75rem;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.search-summary-card {
|
||||
grid-area: summary;
|
||||
}
|
||||
|
||||
.results-card {
|
||||
grid-area: results;
|
||||
}
|
||||
|
||||
.search-summary-card,
|
||||
.results-card {
|
||||
background: var(--sg-surface, #ffffff);
|
||||
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||
box-shadow: none;
|
||||
|
||||
.mat-mdc-card-content {
|
||||
padding: 0.75rem;
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
import { Component, inject, signal } from '@angular/core';
|
||||
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
|
||||
import {
|
||||
WeightMap,
|
||||
WeightSliderOption,
|
||||
WeightsSlidersComponent,
|
||||
WeightsSlidersValue,
|
||||
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
|
||||
|
||||
import { SearchResultsStateService } from '../search-results-state.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-persons-results',
|
||||
standalone: true,
|
||||
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
|
||||
templateUrl: './persons-results.component.html',
|
||||
styleUrl: './persons-results.component.scss',
|
||||
})
|
||||
export class KeywordsToPersonsResultsComponent {
|
||||
// injects the state set by the parent route — no duplicate parsing here
|
||||
private readonly state = inject(SearchResultsStateService);
|
||||
|
||||
readonly defaultWeights: WeightMap = {
|
||||
publications: 0.5,
|
||||
citations: 0.5,
|
||||
patents: 0.5,
|
||||
projects: 0.5,
|
||||
mediaVisibility: 0.5,
|
||||
};
|
||||
|
||||
readonly weightOptions: WeightSliderOption[] = [
|
||||
{
|
||||
key: 'publications',
|
||||
label: 'Publikationen',
|
||||
icon: 'article',
|
||||
description:
|
||||
'Gewichtet die Anzahl und Relevanz wissenschaftlicher Arbeiten.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wPublications',
|
||||
},
|
||||
{
|
||||
key: 'citations',
|
||||
label: 'Zitationen',
|
||||
icon: 'format_quote',
|
||||
description: 'Gewichtet wissenschaftlichen Einfluss über Zitationen.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wCitations',
|
||||
},
|
||||
{
|
||||
key: 'patents',
|
||||
label: 'Patente',
|
||||
icon: 'workspace_premium',
|
||||
description: 'Gewichtet Innovations- und Transferleistung.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wPatents',
|
||||
},
|
||||
{
|
||||
key: 'projects',
|
||||
label: 'Projekte',
|
||||
icon: 'account_tree',
|
||||
description: 'Gewichtet Beteiligung an relevanten Forschungsprojekten.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wProjects',
|
||||
},
|
||||
{
|
||||
key: 'mediaVisibility',
|
||||
label: 'Medien-Sichtbarkeit',
|
||||
icon: 'visibility',
|
||||
description: 'Gewichtet öffentliche und mediale Sichtbarkeit.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wMedia',
|
||||
},
|
||||
];
|
||||
|
||||
readonly currentWeights = signal<WeightsSlidersValue>({
|
||||
raw: this.defaultWeights,
|
||||
normalized: {
|
||||
publications: 0.2,
|
||||
citations: 0.2,
|
||||
patents: 0.2,
|
||||
projects: 0.2,
|
||||
mediaVisibility: 0.2,
|
||||
},
|
||||
rawSum: 2.5,
|
||||
normalizedSum: 1,
|
||||
valid: true,
|
||||
});
|
||||
|
||||
readonly persons = signal<unknown[]>([]); // placeholder until the results service lands
|
||||
|
||||
private hasLoadedInitial = false;
|
||||
|
||||
onWeightsChange(value: WeightsSlidersValue): void {
|
||||
this.currentWeights.set(value);
|
||||
|
||||
// fires once with the query-param-aware initial state — use it to load
|
||||
if (!this.hasLoadedInitial) {
|
||||
this.hasLoadedInitial = true;
|
||||
this.loadPersons();
|
||||
}
|
||||
}
|
||||
|
||||
onApplyWeights(value: WeightsSlidersValue): void {
|
||||
this.currentWeights.set(value);
|
||||
this.loadPersons();
|
||||
}
|
||||
|
||||
private loadPersons(): void {
|
||||
const weights = this.currentWeights();
|
||||
|
||||
const requestPayload = {
|
||||
manualKeywords: this.state.manualKeywords(),
|
||||
extractedKeywords: this.state.extractedKeywords(),
|
||||
keywords: this.state.keywords(),
|
||||
softSearch: this.state.softSearch(),
|
||||
weights: {
|
||||
raw: weights.raw,
|
||||
normalized: weights.normalized,
|
||||
},
|
||||
};
|
||||
|
||||
console.log(requestPayload);
|
||||
|
||||
/**
|
||||
* TODO:
|
||||
* this.personsService.searchPersons(requestPayload).subscribe({
|
||||
* next: results => this.persons.set(results),
|
||||
* error: error => console.error(error),
|
||||
* });
|
||||
*/
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
<div class="result-layout">
|
||||
<mat-card class="results-card">
|
||||
<mat-card-content class="results-placeholder">
|
||||
<mat-icon>groups</mat-icon>
|
||||
<h2>Projectsliste</h2>
|
||||
<p>
|
||||
Die aktuelle Gewichtung ist unter <code>normalized</code> verfügbar.
|
||||
</p>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
|
||||
<mat-card class="weights-card">
|
||||
<mat-card-content>
|
||||
<app-weights-sliders
|
||||
[options]="weightOptions"
|
||||
[initialWeights]="defaultWeights"
|
||||
title="Projects-Gewichtung"
|
||||
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
|
||||
resetLabel="Ausgewogen"
|
||||
applyLabel="Neu gewichten"
|
||||
normalizedTitle="Normalisiert"
|
||||
queryParamPrefix="projectW_"
|
||||
[persistInQueryParams]="true"
|
||||
[showApplyButton]="true"
|
||||
[showResetButton]="true"
|
||||
[showNormalizedPreview]="true"
|
||||
(weightsChange)="onWeightsChange($event)"
|
||||
(applyWeights)="onApplyWeights($event)" />
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* ============================================================
|
||||
RESULT LAYOUT
|
||||
============================================================ */
|
||||
.result-layout {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(300px, 420px) 1fr;
|
||||
grid-template-areas: 'summary results';
|
||||
gap: 0.75rem;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.search-summary-card {
|
||||
grid-area: summary;
|
||||
}
|
||||
|
||||
.results-card {
|
||||
grid-area: results;
|
||||
}
|
||||
|
||||
.search-summary-card,
|
||||
.results-card {
|
||||
background: var(--sg-surface, #ffffff);
|
||||
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||
box-shadow: none;
|
||||
|
||||
.mat-mdc-card-content {
|
||||
padding: 0.75rem;
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
import { Component, inject, signal } from '@angular/core';
|
||||
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
|
||||
import {
|
||||
WeightMap,
|
||||
WeightSliderOption,
|
||||
WeightsSlidersComponent,
|
||||
WeightsSlidersValue,
|
||||
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
|
||||
import { SearchResultsStateService } from '../search-results-state.service';
|
||||
@Component({
|
||||
selector: 'app-projects-results',
|
||||
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
|
||||
templateUrl: './projects-results.component.html',
|
||||
styleUrl: './projects-results.component.scss',
|
||||
})
|
||||
export class KeywordsToProjectsResultsComponent {
|
||||
// injects the state set by the parent route — no duplicate parsing here
|
||||
private readonly state = inject(SearchResultsStateService);
|
||||
|
||||
readonly defaultWeights: WeightMap = {
|
||||
param1: 0.33,
|
||||
param2: 0.33,
|
||||
param3: 0.34,
|
||||
};
|
||||
|
||||
readonly weightOptions: WeightSliderOption[] = [
|
||||
{
|
||||
key: 'param1',
|
||||
label: 'Parameter 1',
|
||||
icon: 'workspace_premium',
|
||||
description: 'Gewichtet Parameter 1.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wParam1',
|
||||
},
|
||||
{
|
||||
key: 'param2',
|
||||
label: 'Parameter 2',
|
||||
icon: 'workspace_premium',
|
||||
description: 'Gewichtet Parameter 2.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wParam2',
|
||||
},
|
||||
{
|
||||
key: 'param3',
|
||||
label: 'Parameter 3',
|
||||
icon: 'workspace_premium',
|
||||
description: 'Gewichtet Parameter 3.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wParam3',
|
||||
},
|
||||
];
|
||||
|
||||
readonly currentWeights = signal<WeightsSlidersValue>({
|
||||
raw: this.defaultWeights,
|
||||
normalized: {
|
||||
param1: 0.33,
|
||||
param2: 0.33,
|
||||
param3: 0.34,
|
||||
},
|
||||
rawSum: 2.5,
|
||||
normalizedSum: 1,
|
||||
valid: true,
|
||||
});
|
||||
|
||||
readonly projects = signal<unknown[]>([]); // placeholder until the results service lands
|
||||
|
||||
private hasLoadedInitial = false;
|
||||
|
||||
onWeightsChange(value: WeightsSlidersValue): void {
|
||||
this.currentWeights.set(value);
|
||||
|
||||
// fires once with the query-param-aware initial state — use it to load
|
||||
if (!this.hasLoadedInitial) {
|
||||
this.hasLoadedInitial = true;
|
||||
this.loadprojects();
|
||||
}
|
||||
}
|
||||
|
||||
onApplyWeights(value: WeightsSlidersValue): void {
|
||||
this.currentWeights.set(value);
|
||||
this.loadprojects();
|
||||
}
|
||||
|
||||
private loadprojects(): void {
|
||||
const weights = this.currentWeights();
|
||||
|
||||
const requestPayload = {
|
||||
manualKeywords: this.state.manualKeywords(),
|
||||
extractedKeywords: this.state.extractedKeywords(),
|
||||
keywords: this.state.keywords(),
|
||||
softSearch: this.state.softSearch(),
|
||||
weights: {
|
||||
raw: weights.raw,
|
||||
normalized: weights.normalized,
|
||||
},
|
||||
};
|
||||
|
||||
console.log(requestPayload);
|
||||
|
||||
/**
|
||||
* TODO:
|
||||
* this.projectsService.searchprojects(requestPayload).subscribe({
|
||||
* next: results => this.projects.set(results),
|
||||
* error: error => console.error(error),
|
||||
* });
|
||||
*/
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { Injectable, computed, signal } from '@angular/core';
|
||||
import { KeywordEntryWithTopic } from '../../../api/model/keywordEntryWithTopic';
|
||||
|
||||
export interface SearchResultsPayload {
|
||||
extractedKeywords: KeywordEntryWithTopic[];
|
||||
manualKeywords: KeywordEntryWithTopic[];
|
||||
keywords: string[];
|
||||
options: {
|
||||
softSearch: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Provided at the parent route (KeywordsSearchResultsComponent) so it's
|
||||
* created once when entering /search-results and destroyed when leaving it.
|
||||
* Child routes (persons/projects/patents) inject it read-only to build
|
||||
* their own search requests without re-deriving the keyword state.
|
||||
*/
|
||||
@Injectable()
|
||||
export class SearchResultsStateService {
|
||||
private readonly _payload = signal<SearchResultsPayload | null>(null);
|
||||
|
||||
readonly payload = this._payload.asReadonly();
|
||||
|
||||
readonly hasValidSearch = computed(() => {
|
||||
const payload = this._payload();
|
||||
return !!payload && payload.keywords.length > 0;
|
||||
});
|
||||
|
||||
readonly keywords = computed(() => this._payload()?.keywords ?? []);
|
||||
readonly softSearch = computed(
|
||||
() => this._payload()?.options.softSearch ?? false,
|
||||
);
|
||||
readonly extractedKeywords = computed(
|
||||
() => this._payload()?.extractedKeywords ?? [],
|
||||
);
|
||||
readonly manualKeywords = computed(
|
||||
() => this._payload()?.manualKeywords ?? [],
|
||||
);
|
||||
|
||||
setPayload(payload: SearchResultsPayload): void {
|
||||
this._payload.set(payload);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<div class="search-results-page">
|
||||
<div class="search-results-header">
|
||||
<button mat-stroked-button color="primary" (click)="goBackToSearch()">
|
||||
<mat-icon>arrow_back</mat-icon>
|
||||
Keywords anpassen
|
||||
</button>
|
||||
</div>
|
||||
@if (state.hasValidSearch()) {
|
||||
<mat-card class="summary-card">
|
||||
<mat-card-content>
|
||||
<div class="summary-header">
|
||||
<div>
|
||||
<span class="summary-label">Suchprofil</span>
|
||||
<span class="summary-count"
|
||||
>{{ selectedKeywordCount() }} Keywords</span
|
||||
>
|
||||
</div>
|
||||
<span class="mode-badge">
|
||||
<mat-icon>account_tree</mat-icon>
|
||||
{{ state.softSearch() ? 'Topic Mapping' : 'Keyword Matching' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="keyword-stack">
|
||||
@for (entry of selectedKeywordEntries(); track getEntryTrack(entry)) {
|
||||
<app-topic-chip
|
||||
[label]="getChipLabel(entry)"
|
||||
[count]="getChipCount(entry)"
|
||||
[description]="getChipDescription(entry)"
|
||||
[subfieldName]="getChipSubfieldName(entry)"
|
||||
[fieldName]="getChipFieldName(entry)"
|
||||
[domainName]="getChipDomainName(entry)"
|
||||
[color]="getTopicColor(entry.topic_mapping?.topic)"
|
||||
[active]="true"
|
||||
countIcon="article"
|
||||
descriptionTooltipTarget="button" />
|
||||
}
|
||||
@for (keyword of missingKeywordLabels(); track keyword) {
|
||||
<app-topic-chip
|
||||
[label]="keyword"
|
||||
[active]="true"
|
||||
countIcon="article" />
|
||||
}
|
||||
</div>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
|
||||
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
|
||||
@for (route of childRoutes; track route.path) {
|
||||
<a
|
||||
mat-tab-link
|
||||
[routerLink]="route.path"
|
||||
routerLinkActive
|
||||
#rla="routerLinkActive"
|
||||
[active]="rla.isActive"
|
||||
[queryParams]="{
|
||||
keywords: state.payload()?.keywords?.join(','),
|
||||
softSearch: state.payload()?.options?.softSearch,
|
||||
}">
|
||||
<mat-icon>{{ route.icon }}</mat-icon>
|
||||
{{ route.label }}
|
||||
</a>
|
||||
}
|
||||
</nav>
|
||||
|
||||
<mat-tab-nav-panel #resultTabPanel>
|
||||
<router-outlet />
|
||||
</mat-tab-nav-panel>
|
||||
} @else {
|
||||
<mat-card class="empty-card">
|
||||
<mat-card-content class="empty-state">
|
||||
<mat-icon>manage_search</mat-icon>
|
||||
<h2>Keine Suchdaten</h2>
|
||||
<p>Starte eine neue Suche, um Ergebnisse zu sehen.</p>
|
||||
<button mat-flat-button color="primary" (click)="goBackToSearch()">
|
||||
Zur Suche
|
||||
</button>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
}
|
||||
</div>
|
||||
@@ -0,0 +1,209 @@
|
||||
/* ============================================================
|
||||
DESIGN TOKENS
|
||||
============================================================ */
|
||||
$phone: 599px;
|
||||
$tablet: 900px;
|
||||
$touch-target: 44px;
|
||||
|
||||
/* ============================================================
|
||||
SEARCH RESULTS PAGE (parent shell)
|
||||
============================================================ */
|
||||
.search-results-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
padding: 0.75rem 1rem;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.75rem;
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: clamp(1.2rem, 2vw, 1.6rem);
|
||||
font-weight: 650;
|
||||
color: var(--sg-text-primary);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0.2rem 0 0;
|
||||
color: var(--sg-text-secondary);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
KEYWORD SUMMARY CARD
|
||||
============================================================ */
|
||||
.summary-card {
|
||||
background: var(--sg-surface, #ffffff);
|
||||
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||
box-shadow: none;
|
||||
|
||||
.mat-mdc-card-content {
|
||||
padding: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.summary-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.summary-label {
|
||||
display: block;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
color: var(--sg-text-secondary);
|
||||
}
|
||||
|
||||
.summary-count {
|
||||
display: block;
|
||||
margin-top: 0.15rem;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 650;
|
||||
color: var(--sg-text-primary);
|
||||
}
|
||||
|
||||
.mode-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
border-radius: 999px;
|
||||
padding: 0.25rem 0.5rem;
|
||||
background: var(--sg-background-muted, #f4f5f7);
|
||||
color: var(--sg-text-secondary);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
|
||||
mat-icon {
|
||||
font-size: 16px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.keyword-stack {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.6rem;
|
||||
|
||||
::ng-deep app-topic-chip .topic-chip__count {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
CHILD ROUTE NAV
|
||||
============================================================ */
|
||||
.result-nav {
|
||||
display: flex;
|
||||
gap: 0.25rem;
|
||||
border-bottom: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||
}
|
||||
|
||||
.result-nav__link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
padding: 0.5rem 0.85rem;
|
||||
border-radius: 6px 6px 0 0;
|
||||
color: var(--sg-text-secondary);
|
||||
text-decoration: none;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
border-bottom: 2px solid transparent;
|
||||
transition:
|
||||
color 0.15s ease,
|
||||
border-color 0.15s ease;
|
||||
|
||||
mat-icon {
|
||||
font-size: 18px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
color: var(--sg-text-primary);
|
||||
}
|
||||
|
||||
&--active {
|
||||
color: var(--sg-text-primary);
|
||||
border-bottom-color: var(--sg-primary, currentColor);
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
EMPTY STATE
|
||||
============================================================ */
|
||||
.empty-card {
|
||||
background: var(--sg-surface, #ffffff);
|
||||
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
min-height: 240px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
text-align: center;
|
||||
color: var(--sg-text-secondary);
|
||||
|
||||
mat-icon {
|
||||
font-size: 48px;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
color: var(--sg-text-primary);
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
max-width: 480px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
button {
|
||||
margin-top: 0.5rem;
|
||||
min-height: $touch-target;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
PHONE
|
||||
============================================================ */
|
||||
@media (max-width: $phone) {
|
||||
.search-results-page {
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.summary-header {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
.mode-badge {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.result-nav {
|
||||
overflow-x: auto;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import { Component, computed, inject } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import {
|
||||
ActivatedRoute,
|
||||
Router,
|
||||
RouterLink,
|
||||
RouterLinkActive,
|
||||
RouterOutlet,
|
||||
} from '@angular/router';
|
||||
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
|
||||
import { KeywordEntryWithTopic } from '../../../api/model/keywordEntryWithTopic';
|
||||
import { Topic } from '../../../api/model/topic';
|
||||
import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component';
|
||||
import {
|
||||
topicHierarchyColor,
|
||||
TopicHierarchyColorInput,
|
||||
} from '../../../resolvers/utils/topic-colors';
|
||||
import { MatTabsModule } from '@angular/material/tabs';
|
||||
import {
|
||||
SearchResultsPayload,
|
||||
SearchResultsStateService,
|
||||
} from './search-results-state.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-keywords-search-results',
|
||||
standalone: true,
|
||||
imports: [
|
||||
RouterLink,
|
||||
RouterLinkActive,
|
||||
RouterOutlet,
|
||||
MatButtonModule,
|
||||
MatCardModule,
|
||||
MatIconModule,
|
||||
TopicChipComponent,
|
||||
MatTabsModule,
|
||||
],
|
||||
providers: [SearchResultsStateService],
|
||||
templateUrl: './search-results.component.html',
|
||||
styleUrl: './search-results.component.scss',
|
||||
})
|
||||
export class KeywordsSearchResultsComponent {
|
||||
private readonly router = inject(Router);
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
|
||||
protected readonly state = inject(SearchResultsStateService);
|
||||
|
||||
// Must match KeywordsSearchComponent.SEARCH_RESULTS_HANDOFF_KEY exactly —
|
||||
// that's where search() writes the enriched entries before navigating.
|
||||
private readonly HANDOFF_KEY = 'search-results-handoff';
|
||||
|
||||
protected readonly childRoutes = [
|
||||
{ path: 'persons', label: 'Personen', icon: 'groups' },
|
||||
{ path: 'projects', label: 'Projekte', icon: 'work' },
|
||||
{ path: 'patents', label: 'Patente', icon: 'workspace_premium' },
|
||||
{ path: 'works', label: 'Publikationen', icon: 'article' },
|
||||
{ path: 'news', label: 'Nachrichten', icon: 'newspaper' },
|
||||
];
|
||||
|
||||
readonly selectedKeywordCount = computed(() => this.state.keywords().length);
|
||||
|
||||
readonly selectedKeywordEntries = computed(() => {
|
||||
const payload = this.state.payload();
|
||||
if (!payload) return [];
|
||||
|
||||
const allEntries = [
|
||||
...(payload.extractedKeywords ?? []),
|
||||
...(payload.manualKeywords ?? []),
|
||||
];
|
||||
|
||||
const entryByKeyword = new Map<string, KeywordEntryWithTopic>();
|
||||
|
||||
for (const entry of allEntries) {
|
||||
entryByKeyword.set(
|
||||
this.normalizeKeyword(this.getKeywordLabel(entry)),
|
||||
entry,
|
||||
);
|
||||
}
|
||||
|
||||
const result: KeywordEntryWithTopic[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const keyword of payload.keywords) {
|
||||
const normalized = this.normalizeKeyword(keyword);
|
||||
const entry = entryByKeyword.get(normalized);
|
||||
|
||||
if (!entry || seen.has(normalized)) continue;
|
||||
|
||||
seen.add(normalized);
|
||||
result.push(entry);
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
|
||||
readonly missingKeywordLabels = computed(() => {
|
||||
const payload = this.state.payload();
|
||||
if (!payload) return [];
|
||||
|
||||
const entryKeywordSet = new Set(
|
||||
this.selectedKeywordEntries().map((entry) =>
|
||||
this.normalizeKeyword(this.getKeywordLabel(entry)),
|
||||
),
|
||||
);
|
||||
|
||||
return payload.keywords.filter(
|
||||
(keyword) => !entryKeywordSet.has(this.normalizeKeyword(keyword)),
|
||||
);
|
||||
});
|
||||
|
||||
constructor() {
|
||||
// Query params are authoritative (URL survives reload, deep links,
|
||||
// browser back/forward). sessionStorage is a best-effort cache for the
|
||||
// heavier, topic-enriched entries — only trusted if its keyword set
|
||||
// still matches what's in the URL right now, so a stale cache from a
|
||||
// previous search never gets silently applied to a new one.
|
||||
this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe((params) => {
|
||||
const keywords = this.parseKeywordList(params.get('keywords'));
|
||||
const softSearch = params.get('softSearch') === 'on';
|
||||
|
||||
const cached = this.readHandoffCache();
|
||||
const cacheMatches =
|
||||
cached && this.sameKeywordSet(cached.keywords, keywords);
|
||||
|
||||
this.state.setPayload({
|
||||
keywords,
|
||||
options: { softSearch },
|
||||
extractedKeywords: cacheMatches ? cached!.extractedKeywords : [],
|
||||
manualKeywords: cacheMatches ? cached!.manualKeywords : [],
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
goBackToSearch(): void {
|
||||
void this.router.navigate(['/keywords']);
|
||||
}
|
||||
|
||||
getChipLabel(keyword: KeywordEntryWithTopic): string {
|
||||
return keyword.llm_keyword?.keyword ?? '';
|
||||
}
|
||||
|
||||
getChipDescription(item: KeywordEntryWithTopic): string | null {
|
||||
return this.getTopic(item)?.description ?? null;
|
||||
}
|
||||
|
||||
getChipSubfieldName(item: KeywordEntryWithTopic): string | null {
|
||||
return this.getTopic(item)?.subfield?.display_name ?? null;
|
||||
}
|
||||
|
||||
getChipFieldName(item: KeywordEntryWithTopic): string | null {
|
||||
return this.getTopic(item)?.field?.display_name ?? null;
|
||||
}
|
||||
|
||||
getChipDomainName(item: KeywordEntryWithTopic): string | null {
|
||||
return this.getTopic(item)?.domain?.display_name ?? null;
|
||||
}
|
||||
|
||||
getChipCount(item: KeywordEntryWithTopic): number | null {
|
||||
return this.getTopic(item)?.works_count ?? null;
|
||||
}
|
||||
|
||||
getTopicColor(topic: Topic | undefined | null): string {
|
||||
const topicInput: TopicHierarchyColorInput = {
|
||||
id: topic?.id ?? null,
|
||||
name: topic?.display_name ?? null,
|
||||
field_id: topic?.field?.id ?? null,
|
||||
field_name: topic?.field?.display_name ?? null,
|
||||
domain_id: topic?.domain?.id ?? null,
|
||||
domain_name: topic?.domain?.display_name ?? null,
|
||||
};
|
||||
|
||||
return topicHierarchyColor(topicInput);
|
||||
}
|
||||
|
||||
getEntryTrack(entry: KeywordEntryWithTopic): string {
|
||||
return this.getKeywordLabel(entry);
|
||||
}
|
||||
|
||||
private readHandoffCache(): SearchResultsPayload | null {
|
||||
const raw = sessionStorage.getItem(this.HANDOFF_KEY);
|
||||
if (!raw) return null;
|
||||
|
||||
try {
|
||||
return this.parsePayload(JSON.parse(raw));
|
||||
} catch {
|
||||
sessionStorage.removeItem(this.HANDOFF_KEY);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private parsePayload(value: unknown): SearchResultsPayload | null {
|
||||
if (!value || typeof value !== 'object') return null;
|
||||
|
||||
const maybePayload = value as Partial<SearchResultsPayload>;
|
||||
|
||||
if (!Array.isArray(maybePayload.keywords)) return null;
|
||||
|
||||
return {
|
||||
extractedKeywords: maybePayload.extractedKeywords ?? [],
|
||||
manualKeywords: maybePayload.manualKeywords ?? [],
|
||||
keywords: maybePayload.keywords ?? [],
|
||||
options: {
|
||||
softSearch: maybePayload.options?.softSearch ?? false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private sameKeywordSet(a: string[], b: string[]): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
const setA = new Set(a.map((k) => this.normalizeKeyword(k)));
|
||||
return b.every((k) => setA.has(this.normalizeKeyword(k)));
|
||||
}
|
||||
|
||||
private parseKeywordList(raw: string | null): string[] {
|
||||
if (!raw) return [];
|
||||
return raw
|
||||
.split(',')
|
||||
.map((v) => v.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
private getKeywordLabel(item: KeywordEntryWithTopic): string {
|
||||
return item.llm_keyword.keyword;
|
||||
}
|
||||
|
||||
private getTopic(item: KeywordEntryWithTopic): Topic | null {
|
||||
return item.topic_mapping?.topic ?? null;
|
||||
}
|
||||
|
||||
private normalizeKeyword(value: string): string {
|
||||
return value.trim().toLowerCase();
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
<div class="result-layout">
|
||||
<mat-card class="results-card">
|
||||
<mat-card-content class="results-placeholder">
|
||||
<mat-icon>groups</mat-icon>
|
||||
<h2>Publikationsliste</h2>
|
||||
<p>
|
||||
Die aktuelle Gewichtung ist unter <code>normalized</code> verfügbar.
|
||||
</p>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
|
||||
<mat-card class="weights-card">
|
||||
<mat-card-content>
|
||||
<app-weights-sliders
|
||||
[options]="weightOptions"
|
||||
[initialWeights]="defaultWeights"
|
||||
title="Publikations-Gewichtung"
|
||||
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
|
||||
resetLabel="Ausgewogen"
|
||||
applyLabel="Neu gewichten"
|
||||
normalizedTitle="Normalisiert"
|
||||
queryParamPrefix="workW_"
|
||||
[persistInQueryParams]="true"
|
||||
[showApplyButton]="true"
|
||||
[showResetButton]="true"
|
||||
[showNormalizedPreview]="true"
|
||||
(weightsChange)="onWeightsChange($event)"
|
||||
(applyWeights)="onApplyWeights($event)" />
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* ============================================================
|
||||
RESULT LAYOUT
|
||||
============================================================ */
|
||||
.result-layout {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(300px, 420px) 1fr;
|
||||
grid-template-areas: 'summary results';
|
||||
gap: 0.75rem;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.search-summary-card {
|
||||
grid-area: summary;
|
||||
}
|
||||
|
||||
.results-card {
|
||||
grid-area: results;
|
||||
}
|
||||
|
||||
.search-summary-card,
|
||||
.results-card {
|
||||
background: var(--sg-surface, #ffffff);
|
||||
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||
box-shadow: none;
|
||||
|
||||
.mat-mdc-card-content {
|
||||
padding: 0.75rem;
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
import { Component, inject, signal } from '@angular/core';
|
||||
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
|
||||
import {
|
||||
WeightMap,
|
||||
WeightSliderOption,
|
||||
WeightsSlidersComponent,
|
||||
WeightsSlidersValue,
|
||||
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
|
||||
import { SearchResultsStateService } from '../search-results-state.service';
|
||||
@Component({
|
||||
selector: 'app-works-results',
|
||||
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
|
||||
templateUrl: './works-results.component.html',
|
||||
styleUrl: './works-results.component.scss',
|
||||
})
|
||||
export class KeywordsToWorksResultsComponent {
|
||||
// injects the state set by the parent route — no duplicate parsing here
|
||||
private readonly state = inject(SearchResultsStateService);
|
||||
|
||||
readonly defaultWeights: WeightMap = {
|
||||
param1: 0.33,
|
||||
param2: 0.33,
|
||||
param3: 0.34,
|
||||
};
|
||||
|
||||
readonly weightOptions: WeightSliderOption[] = [
|
||||
{
|
||||
key: 'param1',
|
||||
label: 'Parameter 1',
|
||||
icon: 'workspace_premium',
|
||||
description: 'Gewichtet Parameter 1.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wParam1',
|
||||
},
|
||||
{
|
||||
key: 'param2',
|
||||
label: 'Parameter 2',
|
||||
icon: 'workspace_premium',
|
||||
description: 'Gewichtet Parameter 2.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wParam2',
|
||||
},
|
||||
{
|
||||
key: 'param3',
|
||||
label: 'Parameter 3',
|
||||
icon: 'workspace_premium',
|
||||
description: 'Gewichtet Parameter 3.',
|
||||
defaultValue: 0.5,
|
||||
queryParamName: 'wParam3',
|
||||
},
|
||||
];
|
||||
|
||||
readonly currentWeights = signal<WeightsSlidersValue>({
|
||||
raw: this.defaultWeights,
|
||||
normalized: {
|
||||
param1: 0.33,
|
||||
param2: 0.33,
|
||||
param3: 0.34,
|
||||
},
|
||||
rawSum: 2.5,
|
||||
normalizedSum: 1,
|
||||
valid: true,
|
||||
});
|
||||
|
||||
readonly works = signal<unknown[]>([]); // placeholder until the results service lands
|
||||
|
||||
private hasLoadedInitial = false;
|
||||
|
||||
onWeightsChange(value: WeightsSlidersValue): void {
|
||||
this.currentWeights.set(value);
|
||||
|
||||
// fires once with the query-param-aware initial state — use it to load
|
||||
if (!this.hasLoadedInitial) {
|
||||
this.hasLoadedInitial = true;
|
||||
this.loadworks();
|
||||
}
|
||||
}
|
||||
|
||||
onApplyWeights(value: WeightsSlidersValue): void {
|
||||
this.currentWeights.set(value);
|
||||
this.loadworks();
|
||||
}
|
||||
|
||||
private loadworks(): void {
|
||||
const weights = this.currentWeights();
|
||||
|
||||
const requestPayload = {
|
||||
manualKeywords: this.state.manualKeywords(),
|
||||
extractedKeywords: this.state.extractedKeywords(),
|
||||
keywords: this.state.keywords(),
|
||||
softSearch: this.state.softSearch(),
|
||||
weights: {
|
||||
raw: weights.raw,
|
||||
normalized: weights.normalized,
|
||||
},
|
||||
};
|
||||
|
||||
console.log(requestPayload);
|
||||
|
||||
/**
|
||||
* TODO:
|
||||
* this.worksService.searchworks(requestPayload).subscribe({
|
||||
* next: results => this.works.set(results),
|
||||
* error: error => console.error(error),
|
||||
* });
|
||||
*/
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,10 @@
|
||||
|
||||
<div class="article-body">
|
||||
@if (article.full_content) {
|
||||
<p class="content">{{ article.full_content }}</p>
|
||||
<p
|
||||
#articleBody
|
||||
class="content"
|
||||
[innerHTML]="highlightedContent"></p>
|
||||
} @else {
|
||||
<p class="placeholder">Kein Inhalt verfügbar.</p>
|
||||
}
|
||||
@@ -76,55 +79,175 @@
|
||||
|
||||
<aside class="sidebar">
|
||||
<div class="sidebar-card">
|
||||
<h3>
|
||||
<mat-icon>group</mat-icon>
|
||||
Erwähnte Personen
|
||||
</h3>
|
||||
<div class="person-list">
|
||||
@if (article.authors && article.authors.length) {
|
||||
@for (person of article.authors; track person.name) {
|
||||
@if (person.is_ude && person.person_id) {
|
||||
<a
|
||||
class="person-item is-link"
|
||||
[routerLink]="['/person', person.person_id, 'overview']">
|
||||
<div class="avatar">{{ person.name.charAt(0) }}</div>
|
||||
<span class="person-name">{{ person.name }}</span>
|
||||
<span class="ude-badge">UDE</span>
|
||||
</a>
|
||||
} @else {
|
||||
<article class="person-item is-muted">
|
||||
<div class="avatar">{{ person.name.charAt(0) }}</div>
|
||||
<span class="person-name">{{ person.name }}</span>
|
||||
</article>
|
||||
}
|
||||
<div class="accordion-panel">
|
||||
<button
|
||||
type="button"
|
||||
class="accordion-header"
|
||||
(click)="openPanel = openPanel === 'persons' ? null : 'persons'"
|
||||
[attr.aria-expanded]="openPanel === 'persons'">
|
||||
<mat-icon>group</mat-icon>
|
||||
<span class="accordion-title">Erwähnte Personen</span>
|
||||
<mat-icon
|
||||
class="info-icon"
|
||||
matTooltip="Personen, die im Text erwähnt wurden. Klicke auf eine der UDE angehörige Person, um zu ihrem Profil zu gelangen."
|
||||
matTooltipPosition="above"
|
||||
(click)="$event.stopPropagation()"
|
||||
>info_outline</mat-icon
|
||||
>
|
||||
@if (article.authors?.length) {
|
||||
<span class="count-badge">{{ article.authors!.length }}</span>
|
||||
}
|
||||
} @else {
|
||||
<p class="placeholder">Keine erwähnten Personen gefunden.</p>
|
||||
<mat-icon
|
||||
class="chevron"
|
||||
[class.rotated]="openPanel !== 'persons'"
|
||||
>expand_more</mat-icon
|
||||
>
|
||||
</button>
|
||||
@if (openPanel === 'persons') {
|
||||
<div class="accordion-body">
|
||||
@if (article.authors && article.authors.length) {
|
||||
<div class="person-list">
|
||||
@for (person of pagedPersons; track person.name) {
|
||||
@if (person.is_ude && person.person_id) {
|
||||
<a
|
||||
class="person-item is-link"
|
||||
[routerLink]="[
|
||||
'/person',
|
||||
person.person_id,
|
||||
'overview',
|
||||
]">
|
||||
<div class="avatar">
|
||||
{{ personInitials(person.name) }}
|
||||
</div>
|
||||
<span class="person-name">{{ person.name }}</span>
|
||||
<span class="ude-badge">UDE</span>
|
||||
</a>
|
||||
} @else {
|
||||
<div class="person-item is-muted">
|
||||
<div class="avatar">
|
||||
{{ personInitials(person.name) }}
|
||||
</div>
|
||||
<span class="person-name">{{ person.name }}</span>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
@if (personsPageCount > 1) {
|
||||
<div class="persons-pagination">
|
||||
<button
|
||||
type="button"
|
||||
class="page-btn"
|
||||
[disabled]="personsPage === 0"
|
||||
(click)="personsPage = personsPage - 1">
|
||||
<mat-icon>chevron_left</mat-icon>
|
||||
</button>
|
||||
<span class="page-indicator"
|
||||
>{{ personsPage + 1 }} / {{ personsPageCount }}</span
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="page-btn"
|
||||
[disabled]="personsPage === personsPageCount - 1"
|
||||
(click)="personsPage = personsPage + 1">
|
||||
<mat-icon>chevron_right</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
} @else {
|
||||
<p class="placeholder">Keine erwähnten Personen gefunden.</p>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sidebar-card">
|
||||
<h3>
|
||||
<mat-icon>label</mat-icon>
|
||||
Schlüsselwörter
|
||||
</h3>
|
||||
<div class="chip-list">
|
||||
@if (article.keywords && article.keywords.length) {
|
||||
@for (
|
||||
keyword of article.keywords;
|
||||
track keyword;
|
||||
let i = $index
|
||||
) {
|
||||
<span
|
||||
class="topic-chip"
|
||||
(click)="onKeywordClick(keyword)"
|
||||
[ngClass]="chipColor(i)"
|
||||
>{{ keyword }}</span
|
||||
>
|
||||
<div class="accordion-panel">
|
||||
<button
|
||||
type="button"
|
||||
class="accordion-header"
|
||||
(click)="openPanel = openPanel === 'topics' ? null : 'topics'"
|
||||
[attr.aria-expanded]="openPanel === 'topics'">
|
||||
<mat-icon>label</mat-icon>
|
||||
<span class="accordion-title">Themen & Schlüsselwörter</span>
|
||||
<mat-icon
|
||||
class="info-icon"
|
||||
matTooltip="Themen, die mit den extrahierten Schlüsselwörtern des Artikels assoziiert werden. Klicke auf ein Schlüsselwort, um zum hervorgehobenen Begriff im Text zu springen."
|
||||
matTooltipPosition="above"
|
||||
(click)="$event.stopPropagation()"
|
||||
>info_outline</mat-icon
|
||||
>
|
||||
@if (article.topics?.length) {
|
||||
<span class="count-badge">{{ article.topics!.length }}</span>
|
||||
}
|
||||
} @else {
|
||||
<p class="placeholder">Keine Schlüsselwörter gefunden.</p>
|
||||
<mat-icon class="chevron" [class.rotated]="openPanel !== 'topics'"
|
||||
>expand_more</mat-icon
|
||||
>
|
||||
</button>
|
||||
@if (openPanel === 'topics') {
|
||||
<div class="accordion-body">
|
||||
@if (article.topics && article.topics.length) {
|
||||
<div class="topics-accordion">
|
||||
@for (
|
||||
topic of article.topics;
|
||||
track topic.id ?? topic.display_name
|
||||
) {
|
||||
<div
|
||||
class="topic-item"
|
||||
[style.--t]="getTopicColor(topic)">
|
||||
<button
|
||||
type="button"
|
||||
class="topic-item-header"
|
||||
[class.is-expanded]="expandedTopicId === topic.id"
|
||||
(click)="toggleTopic(topic.id)">
|
||||
<span class="topic-item-name">{{
|
||||
topic.display_name
|
||||
}}</span>
|
||||
<mat-icon>{{
|
||||
expandedTopicId === topic.id
|
||||
? 'expand_less'
|
||||
: 'expand_more'
|
||||
}}</mat-icon>
|
||||
</button>
|
||||
@if (expandedTopicId === topic.id) {
|
||||
<div class="topic-item-body">
|
||||
@if (topic.source_keyword) {
|
||||
<p class="kw-suggestion-label">
|
||||
Vorgeschlagen durch das Schlüsselwort im Text:
|
||||
</p>
|
||||
<button
|
||||
mat-icon-button
|
||||
class="analyse-btn"
|
||||
matTooltip="Suche nach dem Schlüsselwort"
|
||||
(click)="analyseKeyword(topic.source_keyword)">
|
||||
<mat-icon>search</mat-icon>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="kw-pill"
|
||||
(click)="scrollToKeyword(topic.source_keyword)">
|
||||
»{{ topic.source_keyword }}«
|
||||
</button>
|
||||
<p class="kw-hint">
|
||||
Im Artikel hervorgehoben · klicken zum Suche zu
|
||||
öffnen
|
||||
</p>
|
||||
} @else {
|
||||
<p class="placeholder">
|
||||
Kein Schlüsselwort verknüpft.
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
} @else {
|
||||
<p class="placeholder">
|
||||
Keine Themen oder Schlüsselwörter gefunden.
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -54,7 +54,7 @@
|
||||
|
||||
.detail-layout {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 280px;
|
||||
grid-template-columns: 1fr 288px;
|
||||
gap: 40px;
|
||||
align-items: start;
|
||||
}
|
||||
@@ -137,60 +137,121 @@ main {
|
||||
margin: 0;
|
||||
color: var(--sg-text-muted);
|
||||
font-style: italic;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.article-actions {
|
||||
margin-top: 32px;
|
||||
}
|
||||
|
||||
// ── Sidebar ──────────────────────────────────────────────────────────────────
|
||||
|
||||
.sidebar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
position: sticky;
|
||||
top: 24px;
|
||||
max-height: calc(100vh - 48px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.sidebar-card {
|
||||
padding: 20px;
|
||||
border: 1px solid #d7e4ff;
|
||||
border-radius: 16px;
|
||||
background: #ffffff;
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
h3 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0 0 14px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--sg-text);
|
||||
// ── Accordion ────────────────────────────────────────────────────────────────
|
||||
|
||||
mat-icon {
|
||||
font-size: 18px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
.accordion-panel {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.accordion-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 16px 20px;
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--sg-text);
|
||||
transition: background 0.12s;
|
||||
|
||||
&:hover {
|
||||
background: #f6f9ff;
|
||||
}
|
||||
|
||||
mat-icon {
|
||||
font-size: 18px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
color: var(--sg-text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.accordion-title {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.count-badge {
|
||||
padding: 2px 7px;
|
||||
border-radius: 999px;
|
||||
background: #e8effe;
|
||||
color: #3b5bd6;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.info-icon {
|
||||
flex-shrink: 0;
|
||||
font-size: 16px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
color: var(--sg-text-muted);
|
||||
opacity: 0.7;
|
||||
cursor: default;
|
||||
|
||||
&:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.chevron {
|
||||
transition: transform 0.2s ease;
|
||||
color: var(--sg-text-muted) !important;
|
||||
|
||||
&.rotated {
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
}
|
||||
|
||||
.accordion-body {
|
||||
padding: 0 20px 16px;
|
||||
}
|
||||
|
||||
// ── Persons ───────────────────────────────────────────────────────────────────
|
||||
|
||||
.person-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
max-height: 375px;
|
||||
overflow-y: auto;
|
||||
padding-right: 4px;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.person-item {
|
||||
display: grid;
|
||||
grid-template-columns: 38px minmax(0, 1fr) auto;
|
||||
gap: 11px;
|
||||
grid-template-columns: 36px minmax(0, 1fr) auto;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
padding: 12px;
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--sg-radius-sm);
|
||||
background: var(--sg-surface-muted);
|
||||
}
|
||||
@@ -232,32 +293,209 @@ main {
|
||||
.avatar {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 50%;
|
||||
background: #e5ecfb;
|
||||
color: var(--sg-text);
|
||||
font-size: 15px;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.person-name {
|
||||
color: var(--sg-text);
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
font-weight: 600;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
// ── Persons pagination ────────────────────────────────────────────────────────
|
||||
|
||||
.persons-pagination {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.page-btn {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border: 1px solid #d7e4ff;
|
||||
border-radius: 8px;
|
||||
background: none;
|
||||
cursor: pointer;
|
||||
color: var(--sg-text-muted);
|
||||
transition: background 0.12s;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: #f0f6ff;
|
||||
color: var(--sg-text);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.35;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
mat-icon {
|
||||
font-size: 18px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
.page-indicator {
|
||||
font-size: 12px;
|
||||
color: var(--sg-text-muted);
|
||||
min-width: 36px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
// ── Topic accordion items ─────────────────────────────────────────────────────
|
||||
|
||||
.topics-accordion {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.topic-item {
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
border: 1.5px solid color-mix(in srgb, var(--t) 38%, #ffffff);
|
||||
}
|
||||
|
||||
.topic-item-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 11px 14px;
|
||||
background: color-mix(in srgb, var(--t) 13%, #ffffff);
|
||||
color: color-mix(in srgb, var(--t) 90%, #0f172a);
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
line-height: 1.35;
|
||||
transition: background 0.15s;
|
||||
|
||||
&:hover {
|
||||
background: color-mix(in srgb, var(--t) 22%, #ffffff);
|
||||
}
|
||||
|
||||
&.is-expanded {
|
||||
background: var(--t);
|
||||
color: #ffffff;
|
||||
|
||||
mat-icon {
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
}
|
||||
}
|
||||
|
||||
mat-icon {
|
||||
font-size: 18px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
flex-shrink: 0;
|
||||
color: color-mix(in srgb, var(--t) 70%, #0f172a);
|
||||
}
|
||||
}
|
||||
|
||||
.topic-item-name {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.topic-item-body {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
padding: 14px 14px 14px;
|
||||
background: #ffffff;
|
||||
|
||||
.analyse-btn {
|
||||
position: absolute;
|
||||
color: color-mix(in srgb, var(--t) 90%, #0f172a);
|
||||
font-size: 18px;
|
||||
top: 0.1em;
|
||||
right: 0.1em;
|
||||
}
|
||||
}
|
||||
|
||||
.kw-suggestion-label {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
.kw-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
padding: 6px 14px;
|
||||
border-radius: 999px;
|
||||
border: 1.5px solid color-mix(in srgb, var(--t) 50%, #ffffff);
|
||||
background: color-mix(in srgb, var(--t) 10%, #ffffff);
|
||||
color: color-mix(in srgb, var(--t) 90%, #0f172a);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.12s;
|
||||
|
||||
&:hover {
|
||||
background: color-mix(in srgb, var(--t) 22%, #ffffff);
|
||||
}
|
||||
}
|
||||
|
||||
.kw-hint {
|
||||
margin: 0;
|
||||
font-size: 11px;
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
// ── Topics & Keywords ─────────────────────────────────────────────────────────
|
||||
|
||||
.chip-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
|
||||
& + .chip-group {
|
||||
margin-top: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
.chip-group-label {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
.chip-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.topic-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 6px 12px;
|
||||
padding: 5px 11px;
|
||||
border: 1px solid var(--topic-border);
|
||||
border-radius: 8px;
|
||||
background: var(--topic-bg);
|
||||
@@ -267,6 +505,22 @@ main {
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.kw-chip {
|
||||
cursor: pointer;
|
||||
transition:
|
||||
box-shadow 0.12s,
|
||||
background 0.12s;
|
||||
|
||||
&:hover {
|
||||
box-shadow: 0 0 0 2px var(--topic-border);
|
||||
}
|
||||
|
||||
&.is-active {
|
||||
box-shadow: 0 0 0 2px var(--topic-color);
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
|
||||
.purple {
|
||||
--topic-border: #d8cafe;
|
||||
--topic-bg: #f6f0ff;
|
||||
@@ -296,3 +550,39 @@ main {
|
||||
--topic-bg: #fff1f5;
|
||||
--topic-color: #d12f61;
|
||||
}
|
||||
|
||||
// ── Keyword highlights in article text ───────────────────────────────────────
|
||||
|
||||
@keyframes kw-flash {
|
||||
0% {
|
||||
background: color-mix(in srgb, var(--t) 45%, #ffffff);
|
||||
}
|
||||
40% {
|
||||
background: color-mix(in srgb, var(--t) 45%, #ffffff);
|
||||
}
|
||||
100% {
|
||||
background: transparent;
|
||||
}
|
||||
}
|
||||
|
||||
:host ::ng-deep .kw-mark {
|
||||
background: transparent;
|
||||
color: var(--t);
|
||||
text-decoration: underline;
|
||||
text-decoration-color: var(--t);
|
||||
text-decoration-style: solid;
|
||||
text-decoration-thickness: 2px;
|
||||
text-underline-offset: 2px;
|
||||
font-weight: inherit;
|
||||
border-radius: 2px;
|
||||
padding: 0 1px;
|
||||
transition: background 0.15s;
|
||||
|
||||
&:hover {
|
||||
background: color-mix(in srgb, var(--t) 15%, #ffffff);
|
||||
}
|
||||
|
||||
&.kw-flash {
|
||||
animation: kw-flash 2.4s ease-out forwards;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,23 @@
|
||||
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
|
||||
import { Location, NgClass } from '@angular/common';
|
||||
import {
|
||||
Component,
|
||||
DestroyRef,
|
||||
ElementRef,
|
||||
OnInit,
|
||||
ViewChild,
|
||||
inject,
|
||||
} from '@angular/core';
|
||||
import { Location } from '@angular/common';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { ActivatedRoute, RouterLink } from '@angular/router';
|
||||
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { Router } from '@angular/router';
|
||||
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
|
||||
|
||||
import { WorksService } from '../../api';
|
||||
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
|
||||
|
||||
interface MentionedPerson {
|
||||
name: string;
|
||||
@@ -15,6 +25,15 @@ interface MentionedPerson {
|
||||
person_id?: string | null;
|
||||
}
|
||||
|
||||
interface MatchedTopic {
|
||||
id?: string | null;
|
||||
display_name?: string | null;
|
||||
subfield_name?: string | null;
|
||||
field_name?: string | null;
|
||||
domain_name?: string | null;
|
||||
source_keyword?: string | null;
|
||||
}
|
||||
|
||||
interface NewsArticleDetail {
|
||||
id: string;
|
||||
date?: string | null;
|
||||
@@ -25,6 +44,7 @@ interface NewsArticleDetail {
|
||||
relevant?: boolean;
|
||||
authors?: MentionedPerson[];
|
||||
keywords?: string[];
|
||||
topics?: MatchedTopic[];
|
||||
}
|
||||
|
||||
@Component({
|
||||
@@ -33,28 +53,89 @@ interface NewsArticleDetail {
|
||||
MatButtonModule,
|
||||
MatIconModule,
|
||||
MatProgressSpinnerModule,
|
||||
MatTooltipModule,
|
||||
RouterLink,
|
||||
NgClass,
|
||||
],
|
||||
templateUrl: './news-detail.component.html',
|
||||
styleUrl: './news-detail.component.scss',
|
||||
})
|
||||
export class NewsDetailComponent implements OnInit {
|
||||
@ViewChild('articleBody') articleBodyRef?: ElementRef<HTMLElement>;
|
||||
private readonly router = inject(Router);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
private readonly httpClient = inject(HttpClient);
|
||||
private readonly worksService = inject(WorksService);
|
||||
private readonly location = inject(Location);
|
||||
private readonly router = inject(Router);
|
||||
private readonly sanitizer = inject(DomSanitizer);
|
||||
|
||||
article: NewsArticleDetail | null = null;
|
||||
highlightedContent: SafeHtml = this.sanitizer.bypassSecurityTrustHtml('');
|
||||
loading = false;
|
||||
notFound = false;
|
||||
|
||||
private readonly chipColors = ['purple', 'blue', 'green', 'orange', 'pink'];
|
||||
openPanel: 'persons' | 'topics' | null = 'persons';
|
||||
expandedTopicId: string | null = null;
|
||||
|
||||
chipColor(index: number): string {
|
||||
return this.chipColors[index % this.chipColors.length];
|
||||
personsPage = 0;
|
||||
readonly personsPageSize = 5;
|
||||
|
||||
get pagedPersons(): MentionedPerson[] {
|
||||
const authors = this.article?.authors ?? [];
|
||||
return authors.slice(
|
||||
this.personsPage * this.personsPageSize,
|
||||
(this.personsPage + 1) * this.personsPageSize,
|
||||
);
|
||||
}
|
||||
|
||||
get personsPageCount(): number {
|
||||
return Math.ceil(
|
||||
(this.article?.authors?.length ?? 0) / this.personsPageSize,
|
||||
);
|
||||
}
|
||||
|
||||
getTopicColor(topic: MatchedTopic): string {
|
||||
return topicHierarchyColor({
|
||||
id: topic.id,
|
||||
name: topic.display_name,
|
||||
field_name: topic.field_name,
|
||||
domain_name: topic.domain_name,
|
||||
});
|
||||
}
|
||||
|
||||
personInitials(name: string): string {
|
||||
const parts = name.trim().split(/\s+/);
|
||||
if (parts.length === 1) return parts[0].charAt(0).toUpperCase();
|
||||
return (
|
||||
parts[0].charAt(0) + parts[parts.length - 1].charAt(0)
|
||||
).toUpperCase();
|
||||
}
|
||||
|
||||
toggleTopic(id: string | null | undefined): void {
|
||||
this.expandedTopicId = this.expandedTopicId === id ? null : (id ?? null);
|
||||
}
|
||||
|
||||
scrollToKeyword(keyword: string): void {
|
||||
const body = this.articleBodyRef?.nativeElement;
|
||||
if (!body) return;
|
||||
body
|
||||
.querySelectorAll<HTMLElement>('.kw-flash')
|
||||
.forEach((el) => el.classList.remove('kw-flash'));
|
||||
const marks = body.querySelectorAll<HTMLElement>('[data-kw]');
|
||||
for (const mark of Array.from(marks)) {
|
||||
if (mark.dataset['kw']?.toLowerCase() === keyword.toLowerCase()) {
|
||||
mark.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
mark.classList.add('kw-flash');
|
||||
setTimeout(() => mark.classList.remove('kw-flash'), 2400);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
analyseKeyword(keyword: string | null | undefined): void {
|
||||
this.router.navigate(['/keywords'], {
|
||||
queryParams: { manual: keyword ?? '', selected: keyword ?? '' },
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -71,11 +152,7 @@ export class NewsDetailComponent implements OnInit {
|
||||
navigateBack(): void {
|
||||
this.location.back();
|
||||
}
|
||||
onKeywordClick(keyword: string): void {
|
||||
this.router.navigate(['/keywords'], {
|
||||
queryParams: { selected: keyword, manual: keyword },
|
||||
});
|
||||
}
|
||||
|
||||
formatDate(dateStr?: string | null): string {
|
||||
if (!dateStr) return '-';
|
||||
const date = new Date(dateStr);
|
||||
@@ -97,6 +174,9 @@ export class NewsDetailComponent implements OnInit {
|
||||
.subscribe({
|
||||
next: (article) => {
|
||||
this.article = article;
|
||||
this.highlightedContent = this.buildHighlightedContent(article);
|
||||
this.expandedTopicId = null;
|
||||
this.personsPage = 0;
|
||||
this.loading = false;
|
||||
},
|
||||
error: () => {
|
||||
@@ -105,4 +185,63 @@ export class NewsDetailComponent implements OnInit {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private buildHighlightedContent(article: NewsArticleDetail): SafeHtml {
|
||||
const text = article.full_content;
|
||||
if (!text) return this.sanitizer.bypassSecurityTrustHtml('');
|
||||
const keywords = article.keywords ?? [];
|
||||
|
||||
const keywordColorMap = new Map<string, string>();
|
||||
for (const topic of article.topics ?? []) {
|
||||
if (topic.source_keyword) {
|
||||
keywordColorMap.set(
|
||||
topic.source_keyword.toLowerCase(),
|
||||
this.getTopicColor(topic),
|
||||
);
|
||||
}
|
||||
}
|
||||
const orphanColors = [
|
||||
'#7255d9',
|
||||
'#0b63ce',
|
||||
'#24834f',
|
||||
'#c67500',
|
||||
'#d12f61',
|
||||
];
|
||||
let orphanIdx = 0;
|
||||
|
||||
let html = this.escapeHtml(text);
|
||||
if (keywords.length) {
|
||||
[...keywords]
|
||||
.sort((a, b) => b.length - a.length)
|
||||
.forEach((kw) => {
|
||||
let color = keywordColorMap.get(kw.toLowerCase());
|
||||
if (!color) {
|
||||
color = orphanColors[orphanIdx % orphanColors.length];
|
||||
orphanIdx++;
|
||||
}
|
||||
const kwHtml = this.escapeHtml(kw);
|
||||
const re = new RegExp(
|
||||
`(${this.escapeRegex(kwHtml)}[\\w\\u00C0-\\u024F]*)`,
|
||||
'gi',
|
||||
);
|
||||
html = html.replace(
|
||||
re,
|
||||
`<mark class="kw-mark" style="--t:${color}" data-kw="${kwHtml}">$1</mark>`,
|
||||
);
|
||||
});
|
||||
}
|
||||
return this.sanitizer.bypassSecurityTrustHtml(html);
|
||||
}
|
||||
|
||||
private escapeHtml(text: string): string {
|
||||
return text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
private escapeRegex(text: string): string {
|
||||
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<aside class="interest-card">
|
||||
<aside class="interest-card" [class.interest-card-loading]="loading()">
|
||||
<div class="interest-header">
|
||||
<h3>Interessant für</h3>
|
||||
@if (tags().length > 0) {
|
||||
@@ -23,7 +23,12 @@
|
||||
(expandedChange)="onLegendExpandedChange($event)">
|
||||
</app-topic-legend>
|
||||
<div class="interest-tags">
|
||||
@if (tags().length > 0) {
|
||||
@if (loading()) {
|
||||
<div class="interest-state interest-state-loading" aria-live="polite">
|
||||
<mat-spinner diameter="36"></mat-spinner>
|
||||
<span>Themen werden geladen ...</span>
|
||||
</div>
|
||||
} @else if (tags().length > 0) {
|
||||
@for (tag of tags(); track tag.label) {
|
||||
<app-topic-chip
|
||||
[label]="tag.label"
|
||||
|
||||
@@ -10,6 +10,11 @@
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.8);
|
||||
}
|
||||
|
||||
.interest-card-loading {
|
||||
padding-top: 14px;
|
||||
padding-bottom: 14px;
|
||||
}
|
||||
|
||||
.interest-header {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
@@ -54,3 +59,25 @@
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.interest-state {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
min-height: 90px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 20px;
|
||||
color: #68748f;
|
||||
font-size: 14px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.interest-card-loading .interest-state {
|
||||
min-height: 48px;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
.interest-state-loading {
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
} from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
|
||||
@@ -51,6 +52,7 @@ const MAX_TAGS = 5;
|
||||
imports: [
|
||||
CommonModule,
|
||||
MatIconModule,
|
||||
MatProgressSpinnerModule,
|
||||
TopicChipComponent,
|
||||
TopicLegendComponent,
|
||||
],
|
||||
@@ -66,11 +68,17 @@ export class PersonInterestingComponent implements OnInit {
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
readonly topics = input<TopicCount[] | null>(null);
|
||||
readonly loading = input<boolean>(false);
|
||||
readonly legendExpanded = signal(false);
|
||||
readonly activeLegendFieldIds = signal<ReadonlySet<string>>(new Set());
|
||||
readonly activeLegendSubfieldIds = signal<ReadonlySet<string>>(new Set());
|
||||
|
||||
readonly tagClick = output<{ id: string; name: string }>();
|
||||
readonly tagClick = output<{
|
||||
id: string;
|
||||
name: string;
|
||||
fieldName?: string;
|
||||
domainName?: string;
|
||||
}>();
|
||||
|
||||
readonly tags = computed<InterestTag[]>(() => {
|
||||
const topicsList = this.topics() ?? [];
|
||||
@@ -98,7 +106,7 @@ export class PersonInterestingComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
return tags.sort((a, b) => b.count - a.count).slice(0, MAX_TAGS);
|
||||
return tags.slice(0, MAX_TAGS).sort((a, b) => b.count - a.count);
|
||||
});
|
||||
|
||||
readonly legendGroups = computed(() =>
|
||||
@@ -136,7 +144,12 @@ export class PersonInterestingComponent implements OnInit {
|
||||
|
||||
onTagClick(tag: InterestTag): void {
|
||||
if (!tag.id) return;
|
||||
this.tagClick.emit({ id: tag.id, name: tag.label });
|
||||
this.tagClick.emit({
|
||||
id: tag.id,
|
||||
name: tag.label,
|
||||
fieldName: tag.fieldName || undefined,
|
||||
domainName: tag.domainName || undefined,
|
||||
});
|
||||
}
|
||||
|
||||
onLegendExpandedChange(expanded: boolean): void {
|
||||
|
||||
@@ -40,7 +40,10 @@
|
||||
<span [skText]="loading" class="active-topic-filter">
|
||||
<span
|
||||
class="filter-topic-chip"
|
||||
[style.--topic-color]="getFilterTopicColor(filter.value)">
|
||||
[style.--topic-color]="getFilterTopicColor(filter.value)"
|
||||
[matTooltip]="getFilterTopicTooltip(filter.value)"
|
||||
matTooltipClass="topic-chip-tooltip"
|
||||
[matTooltipDisabled]="!getFilterTopicTooltip(filter.value)">
|
||||
<mat-icon class="filter-topic-chip__icon">label</mat-icon>
|
||||
<span class="filter-topic-chip__label">{{
|
||||
filter.value
|
||||
|
||||
@@ -11,6 +11,7 @@ import { MatInputModule } from '@angular/material/input';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||
import { MatRadioModule } from '@angular/material/radio';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { ResolverStateService } from '../../shared/services/resolver-state.service';
|
||||
|
||||
import {
|
||||
@@ -24,6 +25,7 @@ import { TopicsService } from '../../api/api/topics.service';
|
||||
import { TopicHierarchyComponent } from '../topic-hierarchy/topic-hierarchy.component';
|
||||
import { PersonCardComponent } from '../person-card/person-card.component';
|
||||
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
|
||||
import { buildTopicHierarchyTooltip } from '../../resolvers/utils/topic-tooltip';
|
||||
import { SharedStateService } from '../../shared/services/shared-state.service';
|
||||
import { PaginationService } from '../../shared/services/pagination.service';
|
||||
import {
|
||||
@@ -54,6 +56,7 @@ import { SkTextDirective } from '../../custom-directives/sk-text.directive';
|
||||
MatButtonModule,
|
||||
MatCheckboxModule,
|
||||
MatRadioModule,
|
||||
MatTooltipModule,
|
||||
TopicHierarchyComponent,
|
||||
PersonCardComponent,
|
||||
SkTextDirective,
|
||||
@@ -397,6 +400,16 @@ export class PersonListComponent {
|
||||
return this.findPersonTopic(topicName)?.domain?.display_name;
|
||||
}
|
||||
|
||||
getFilterTopicTooltip(topicName: string): string {
|
||||
return buildTopicHierarchyTooltip({
|
||||
topicName,
|
||||
description: this.getFilterTopicDescription(topicName),
|
||||
subfieldName: this.getFilterTopicSubfieldName(topicName),
|
||||
fieldName: this.getFilterTopicFieldName(topicName),
|
||||
domainName: this.getFilterTopicDomainName(topicName),
|
||||
});
|
||||
}
|
||||
|
||||
clearAllFilters(): void {
|
||||
this.selectedTopics.set(new Set<string>());
|
||||
this.institutionControl.setValue('', { emitEvent: false });
|
||||
|
||||
@@ -22,6 +22,8 @@ export interface WordCloudWord {
|
||||
name: string;
|
||||
value: number;
|
||||
topicId: string | undefined;
|
||||
fieldName: string | undefined;
|
||||
domainName: string | undefined;
|
||||
color: string;
|
||||
fontSize: number;
|
||||
fontWeight: number;
|
||||
@@ -186,6 +188,8 @@ export class PersonOverviewComponent implements OnInit {
|
||||
publicationYear: selection.years,
|
||||
publicationTopicId: selection.topic.id,
|
||||
publicationTopicName: selection.topic.name,
|
||||
publicationTopicField: selection.topic.field_name ?? null,
|
||||
publicationTopicDomain: selection.topic.domain_name ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -225,6 +229,8 @@ export class PersonOverviewComponent implements OnInit {
|
||||
publicationPage: 1,
|
||||
publicationTopicId: word.topicId,
|
||||
publicationTopicName: word.name,
|
||||
publicationTopicField: word.fieldName ?? null,
|
||||
publicationTopicDomain: word.domainName ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -462,6 +468,8 @@ export class PersonOverviewComponent implements OnInit {
|
||||
name,
|
||||
value,
|
||||
topicId: nameToId.get(name),
|
||||
fieldName: colorInput?.field_name ?? undefined,
|
||||
domainName: colorInput?.domain_name ?? undefined,
|
||||
color: topicHierarchyColor(colorInput),
|
||||
fontSize: Math.round(12 + t * (32 - 12)),
|
||||
fontWeight: t > 0.66 ? 800 : t > 0.33 ? 600 : 400,
|
||||
|
||||
@@ -235,7 +235,10 @@
|
||||
<span class="active-meta-filter">
|
||||
<span
|
||||
class="filter-topic-chip"
|
||||
[style.--topic-color]="getSelectedTopicColor(topic)">
|
||||
[style.--topic-color]="getSelectedTopicColor(topic)"
|
||||
[matTooltip]="getSelectedTopicTooltip(topic)"
|
||||
matTooltipClass="topic-chip-tooltip"
|
||||
[matTooltipDisabled]="!getSelectedTopicTooltip(topic)">
|
||||
<mat-icon class="filter-topic-chip__icon">label</mat-icon>
|
||||
<span class="filter-topic-chip__label">{{
|
||||
topic.display_name
|
||||
|
||||
@@ -44,6 +44,7 @@ import { createLoadError } from '../../resolvers/utils/errorHandler';
|
||||
import { ChipComponent } from '../../shared/ui/chip/chip.component';
|
||||
import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component';
|
||||
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
|
||||
import { buildTopicHierarchyTooltip } from '../../resolvers/utils/topic-tooltip';
|
||||
|
||||
interface InstitutionAutocompleteOption {
|
||||
id?: string | null;
|
||||
@@ -485,6 +486,31 @@ export class PersonPublicationsComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
getSelectedTopicTooltip(topic: TopicAutocompleteOption): string {
|
||||
const workTopic = this.findPublicationTopic(topic.id);
|
||||
|
||||
return buildTopicHierarchyTooltip({
|
||||
topicName: topic.display_name,
|
||||
description: workTopic?.description,
|
||||
subfieldName: workTopic?.subfield?.display_name,
|
||||
fieldName: workTopic?.field?.display_name ?? topic.field_name,
|
||||
domainName: workTopic?.domain?.display_name ?? topic.domain_name,
|
||||
});
|
||||
}
|
||||
|
||||
private findPublicationTopic(
|
||||
topicId: string | null | undefined,
|
||||
): WorkTopic | undefined {
|
||||
if (!topicId) return undefined;
|
||||
|
||||
for (const publication of this.publications) {
|
||||
const topic = publication.topics?.find((item) => item.id === topicId);
|
||||
if (topic) return topic;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
getSelectedTopicColor(topic: TopicAutocompleteOption): string {
|
||||
return topicHierarchyColor({
|
||||
id: topic.id,
|
||||
|
||||
@@ -7,20 +7,46 @@
|
||||
<span>Person</span>
|
||||
<h1>{{ displayName() }}</h1>
|
||||
</div>
|
||||
<p>{{ institution() }}</p>
|
||||
@if (countryCode()) {
|
||||
<span>{{ countryCode() }}</span>
|
||||
}
|
||||
<div class="institution-line">
|
||||
<mat-icon class="institution-icon">apartment</mat-icon>
|
||||
@if (institutionId(); as institutionId) {
|
||||
<a
|
||||
class="institution-link"
|
||||
[routerLink]="['/institution', institutionId]">
|
||||
{{ institution() }}
|
||||
</a>
|
||||
} @else {
|
||||
<p class="institution-name">{{ institution() }}</p>
|
||||
}
|
||||
@if (countryCode(); as countryCode) {
|
||||
<span class="institution-country">
|
||||
<img
|
||||
alt=""
|
||||
class="flag-img"
|
||||
[src]="
|
||||
'https://flagcdn.io/' + countryCode.toLowerCase() + '.svg'
|
||||
"
|
||||
height="12" />
|
||||
{{ countryCode }}
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
@if (worksCount() !== null || citedByCount() !== null) {
|
||||
<span>
|
||||
<span class="stats-line">
|
||||
@if (worksCount() !== null) {
|
||||
{{ worksCount() }} Publikationen
|
||||
<span class="stat-item">
|
||||
<mat-icon class="stat-icon">menu_book</mat-icon>
|
||||
{{ worksCount() }} Publikationen
|
||||
</span>
|
||||
}
|
||||
@if (worksCount() !== null && citedByCount() !== null) {
|
||||
·
|
||||
}
|
||||
@if (citedByCount() !== null) {
|
||||
{{ citedByCount() }} Zitationen
|
||||
<span class="stat-item">
|
||||
<mat-icon class="stat-icon">format_quote</mat-icon>
|
||||
{{ citedByCount() }} Zitationen
|
||||
</span>
|
||||
}
|
||||
</span>
|
||||
<span>
|
||||
@@ -80,6 +106,7 @@
|
||||
</aside>
|
||||
<app-person-interesting
|
||||
[topics]="primaryTopicCounts()"
|
||||
[loading]="isTopicsLoading()"
|
||||
(tagClick)="onInterestingTagClick($event)"></app-person-interesting>
|
||||
</section>
|
||||
<nav class="person-tabs" mat-tab-nav-bar [tabPanel]="tabPanel">
|
||||
|
||||
@@ -73,18 +73,73 @@
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.profile-main p {
|
||||
.institution-line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin: 10px 0 0;
|
||||
}
|
||||
|
||||
.institution-icon {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
font-size: 16px;
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
.institution-name,
|
||||
.institution-link {
|
||||
margin: 0;
|
||||
color: var(--sg-text);
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.institution-link {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.institution-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.profile-main > span {
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.stats-line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.stat-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.stat-icon {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
font-size: 16px;
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
.institution-country {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.institution-country .flag-img {
|
||||
border: 1px solid var(--sg-border);
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.career-stage-line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -143,6 +143,9 @@ export class PersonComponent {
|
||||
readonly countryCode = computed(
|
||||
() => this.lastAffiliation()?.institution?.country_code ?? null,
|
||||
);
|
||||
readonly institutionId = computed(
|
||||
() => this.lastAffiliation()?.institution?.id?.split('/').pop() ?? null,
|
||||
);
|
||||
readonly worksCount = computed(() => this.person()?.works_count ?? null);
|
||||
readonly citedByCount = computed(() => this.person()?.cited_by_count ?? null);
|
||||
readonly h_index = computed(
|
||||
@@ -190,15 +193,19 @@ export class PersonComponent {
|
||||
);
|
||||
readonly worksApiUrl = computed(() => this.person()?.works_api_url ?? null);
|
||||
|
||||
readonly isTopicsLoading = signal(false);
|
||||
|
||||
readonly primaryTopicCounts = toSignal(
|
||||
toObservable(this.authorId).pipe(
|
||||
switchMap((id) => {
|
||||
if (!id) return of([]);
|
||||
this.isTopicsLoading.set(true);
|
||||
return this.worksApi.getPrimaryTopicCountsByAuthor(id).pipe(
|
||||
catchError((err) => {
|
||||
console.error('Failed to load primary topic counts:', err);
|
||||
return of([]);
|
||||
}),
|
||||
finalize(() => this.isTopicsLoading.set(false)),
|
||||
);
|
||||
}),
|
||||
),
|
||||
@@ -227,7 +234,12 @@ export class PersonComponent {
|
||||
{ label: 'Patente', path: 'patents', disabled: false },
|
||||
];
|
||||
|
||||
onInterestingTagClick(selection: { id: string; name: string }): void {
|
||||
onInterestingTagClick(selection: {
|
||||
id: string;
|
||||
name: string;
|
||||
fieldName?: string;
|
||||
domainName?: string;
|
||||
}): void {
|
||||
if (!selection.id) return;
|
||||
|
||||
void this.router.navigate(['publications'], {
|
||||
@@ -236,6 +248,8 @@ export class PersonComponent {
|
||||
publicationPage: 1,
|
||||
publicationTopicId: selection.id,
|
||||
publicationTopicName: selection.name,
|
||||
publicationTopicField: selection.fieldName ?? null,
|
||||
publicationTopicDomain: selection.domainName ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -168,14 +168,14 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@if (publication.topics?.length || publication.keywords?.length) {
|
||||
@if (publication.topics?.length) {
|
||||
<section class="card">
|
||||
<div class="section-title">
|
||||
<mat-icon>interests</mat-icon>
|
||||
<h2>Themen und Keywords</h2>
|
||||
<mat-icon>label</mat-icon>
|
||||
<h2>Themen</h2>
|
||||
</div>
|
||||
<div class="tags">
|
||||
@for (topic of publication.topics ?? []; track topic.id) {
|
||||
@for (topic of publication.topics; track topic.id) {
|
||||
<app-topic-chip
|
||||
[label]="topic.display_name || ''"
|
||||
[description]="topic.description"
|
||||
@@ -185,7 +185,18 @@
|
||||
[color]="getTopicColor(topic)">
|
||||
</app-topic-chip>
|
||||
}
|
||||
@for (keyword of publication.keywords ?? []; track keyword.id) {
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
|
||||
@if (publication.keywords?.length) {
|
||||
<section class="card">
|
||||
<div class="section-title">
|
||||
<mat-icon>interests</mat-icon>
|
||||
<h2>Keywords</h2>
|
||||
</div>
|
||||
<div class="tags">
|
||||
@for (keyword of publication.keywords; track keyword.id) {
|
||||
<span>{{ keyword.display_name }}</span>
|
||||
}
|
||||
</div>
|
||||
@@ -296,10 +307,30 @@
|
||||
<div class="compact-list">
|
||||
@for (institution of institutions(); track institution.id) {
|
||||
<div>
|
||||
<strong>{{ institution.name }}</strong>
|
||||
<span>{{
|
||||
institution.country || institution.type || ''
|
||||
}}</span>
|
||||
<a
|
||||
class="institution-link"
|
||||
[routerLink]="[
|
||||
'/institution',
|
||||
institution.id.split('/').pop() ?? '',
|
||||
]">
|
||||
{{ institution.name }}
|
||||
</a>
|
||||
@if (institution.country) {
|
||||
<span class="institution-country">
|
||||
<img
|
||||
alt=""
|
||||
class="flag-img"
|
||||
[src]="
|
||||
'https://flagcdn.io/' +
|
||||
institution.country.toLowerCase() +
|
||||
'.svg'
|
||||
"
|
||||
height="14" />
|
||||
{{ institution.country.toUpperCase() }}
|
||||
</span>
|
||||
} @else if (institution.type) {
|
||||
<span>{{ institution.type }}</span>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -355,11 +355,34 @@ dd {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.institution-link {
|
||||
color: var(--sg-text);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.institution-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.compact-list span {
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.institution-country {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.institution-country .flag-img {
|
||||
border: 1px solid var(--sg-border);
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.link-list a {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -22,12 +22,7 @@ export const accountViewerGuard: CanActivateFn = () => {
|
||||
return;
|
||||
}
|
||||
|
||||
const mayViewAccounts =
|
||||
credentialService.isEffectiveSuperAdmin() ||
|
||||
credentialService.isEffectiveAdmin() ||
|
||||
credentialService.isEffectiveManager();
|
||||
|
||||
if (!mayViewAccounts) {
|
||||
if (!credentialService.canReadAccounts()) {
|
||||
void router.navigate(['/dashboard']);
|
||||
resolve(false);
|
||||
return;
|
||||
@@ -38,4 +33,4 @@ export const accountViewerGuard: CanActivateFn = () => {
|
||||
{ injector },
|
||||
);
|
||||
});
|
||||
};
|
||||
};
|
||||
@@ -11,6 +11,8 @@ export class StatusPipe implements PipeTransform {
|
||||
return 'Aktiv';
|
||||
case 'INACTIVE':
|
||||
return 'Inaktiv';
|
||||
case 'DELETED':
|
||||
return 'Gelöscht';
|
||||
default:
|
||||
return value;
|
||||
}
|
||||
|
||||
@@ -94,6 +94,22 @@ export class CredentialService {
|
||||
() => this.accountProfile()?.organization_name ?? '',
|
||||
);
|
||||
|
||||
public readonly permissions = computed(
|
||||
() => this.accountProfile()?.permissions ?? [],
|
||||
);
|
||||
|
||||
public readonly canReadAccounts = computed(() =>
|
||||
this.permissions().includes('READ_ACCOUNTS'),
|
||||
);
|
||||
|
||||
public readonly canManageAccounts = computed(() =>
|
||||
this.permissions().includes('MANAGE_ACCOUNTS'),
|
||||
);
|
||||
|
||||
public readonly canManageOrganizations = computed(() =>
|
||||
this.permissions().includes('MANAGE_ORGANIZATIONS'),
|
||||
);
|
||||
|
||||
public readonly realAccountId = computed(
|
||||
() => this.accessToken()?.real_account_id ?? '',
|
||||
);
|
||||
|
||||
@@ -44,15 +44,8 @@
|
||||
@for (itemGroup of navItemGroups; track $index) {
|
||||
<div>
|
||||
@if (
|
||||
(!itemGroup.adminOnly ||
|
||||
credentialService.isEffectiveSuperAdmin() ||
|
||||
credentialService.isEffectiveAdmin()) &&
|
||||
(!itemGroup.superAdminOnly ||
|
||||
credentialService.isEffectiveSuperAdmin()) &&
|
||||
(!itemGroup.managerOrAdminOnly ||
|
||||
credentialService.isEffectiveSuperAdmin() ||
|
||||
credentialService.isEffectiveAdmin() ||
|
||||
credentialService.isEffectiveManager())
|
||||
!itemGroup.requiredPermission ||
|
||||
credentialService.permissions().includes(itemGroup.requiredPermission)
|
||||
) {
|
||||
<mat-divider></mat-divider>
|
||||
@if (!collapsed()) {
|
||||
@@ -149,4 +142,4 @@
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</aside>
|
||||
</aside>
|
||||
@@ -17,17 +17,13 @@ type NavItem = {
|
||||
route: string;
|
||||
disabled: boolean;
|
||||
queryParams?: Record<string, string | number | boolean>;
|
||||
adminOnly?: boolean;
|
||||
superAdminOnly?: boolean;
|
||||
managerOrAdminOnly?: boolean;
|
||||
requiredPermission?: string;
|
||||
};
|
||||
|
||||
type NavItemGroup = {
|
||||
label: string;
|
||||
items: NavItem[];
|
||||
adminOnly?: boolean;
|
||||
superAdminOnly?: boolean;
|
||||
managerOrAdminOnly?: boolean;
|
||||
requiredPermission?: string;
|
||||
};
|
||||
|
||||
@Component({
|
||||
@@ -127,36 +123,35 @@ export class AppMenuComponent {
|
||||
icon: 'manage_accounts',
|
||||
route: '/accounts',
|
||||
disabled: false,
|
||||
managerOrAdminOnly: true,
|
||||
requiredPermission: 'READ_ACCOUNTS',
|
||||
},
|
||||
{
|
||||
label: 'Organisationen',
|
||||
icon: 'domain',
|
||||
route: '/organizations',
|
||||
disabled: false,
|
||||
superAdminOnly: true,
|
||||
requiredPermission: 'MANAGE_ORGANIZATIONS',
|
||||
},
|
||||
];
|
||||
|
||||
navItemGroups: NavItemGroup[] = [
|
||||
{
|
||||
label: 'Navigation',
|
||||
items: this.navItems.filter(
|
||||
(item) =>
|
||||
!item.adminOnly && !item.superAdminOnly && !item.managerOrAdminOnly,
|
||||
),
|
||||
items: this.navItems.filter((item) => !item.requiredPermission),
|
||||
},
|
||||
{
|
||||
label: 'Administration',
|
||||
items: this.navItems.filter(
|
||||
(item) =>
|
||||
(item.adminOnly || item.managerOrAdminOnly) && !item.superAdminOnly,
|
||||
(item) => item.requiredPermission === 'READ_ACCOUNTS',
|
||||
),
|
||||
managerOrAdminOnly: true,
|
||||
requiredPermission: 'READ_ACCOUNTS',
|
||||
},
|
||||
{
|
||||
label: 'Super Administration',
|
||||
items: this.navItems.filter((item) => item.superAdminOnly),
|
||||
superAdminOnly: true,
|
||||
items: this.navItems.filter(
|
||||
(item) => item.requiredPermission === 'MANAGE_ORGANIZATIONS',
|
||||
),
|
||||
requiredPermission: 'MANAGE_ORGANIZATIONS',
|
||||
},
|
||||
];
|
||||
|
||||
@@ -182,4 +177,4 @@ export class AppMenuComponent {
|
||||
void this.credentialService.logoutAccount();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,9 +45,19 @@
|
||||
}
|
||||
|
||||
@for (topic of topics(); track topic) {
|
||||
<mat-option [value]="topic.display_name">{{
|
||||
topic.display_name
|
||||
}}</mat-option>
|
||||
<mat-option [value]="topic.display_name">
|
||||
<div class="topic-option">
|
||||
<div class="topic-main">
|
||||
{{ topic.display_name }}
|
||||
</div>
|
||||
|
||||
<div class="topic-path">
|
||||
{{ topic.domain?.display_name }} >
|
||||
{{ topic.field?.display_name }} >
|
||||
{{ topic.subfield?.display_name }}
|
||||
</div>
|
||||
</div></mat-option
|
||||
>
|
||||
}
|
||||
|
||||
@if (
|
||||
|
||||
@@ -13,3 +13,21 @@ mat-form-field {
|
||||
.topic-field {
|
||||
width: 100%;
|
||||
}
|
||||
.topic-option {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.topic-main {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.topic-path {
|
||||
font-size: 11px;
|
||||
color: rgba(0, 0, 0, 0.6);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
<!-- weights-sliders.component.html -->
|
||||
<mat-card class="weights-card">
|
||||
<mat-card-content>
|
||||
<!-- Header -->
|
||||
<div class="weights-header">
|
||||
<h2>{{ title }}</h2>
|
||||
@if (showResetButton) {
|
||||
<button mat-stroked-button color="primary" (click)="resetWeights()">
|
||||
<mat-icon>restart_alt</mat-icon>
|
||||
{{ resetLabel }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- Sliders -->
|
||||
<div class="weight-list">
|
||||
@for (option of options; track option.key) {
|
||||
<div class="weight-row">
|
||||
<div
|
||||
class="weight-label"
|
||||
[matTooltip]="option.description || option.label"
|
||||
[matTooltipPosition]="'above'"
|
||||
[matTooltipClass]="'tooltip-sm'">
|
||||
@if (option.icon) {
|
||||
<mat-icon class="icon-small">{{ option.icon }}</mat-icon>
|
||||
}
|
||||
<span>{{ option.label }}</span>
|
||||
</div>
|
||||
|
||||
<mat-slider
|
||||
class="weight-slider"
|
||||
[min]="min"
|
||||
[max]="max"
|
||||
[step]="step"
|
||||
[discrete]="true"
|
||||
[showTickMarks]="true"
|
||||
[displayWith]="formatRawWeightLabel"
|
||||
[attr.aria-label]="option.label + ' Gewichtung'">
|
||||
<input
|
||||
matSliderThumb
|
||||
[formControl]="weightControl(option.key)"
|
||||
[attr.aria-label]="option.label + ' Gewichtung'" />
|
||||
</mat-slider>
|
||||
|
||||
<div class="weight-value">
|
||||
{{ formatRawWeightLabel(weightControl(option.key).value) }}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- Validation Warning -->
|
||||
@if (!weightsState().valid) {
|
||||
<div class="weight-warning">
|
||||
<mat-icon>warning</mat-icon>
|
||||
Mindestens ein Gewicht > 0
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- Apply Button -->
|
||||
@if (showApplyButton) {
|
||||
<div class="weight-actions">
|
||||
<button
|
||||
mat-flat-button
|
||||
color="primary"
|
||||
[disabled]="!weightsState().valid"
|
||||
(click)="onApplyClick()">
|
||||
<mat-icon>tune</mat-icon>
|
||||
{{ applyLabel }}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
@@ -0,0 +1,215 @@
|
||||
/* weights-sliders.component.scss */
|
||||
|
||||
$phone: 599px;
|
||||
$tablet: 900px;
|
||||
$touch-target: 44px;
|
||||
|
||||
/* ============================================================
|
||||
CARD
|
||||
============================================================ */
|
||||
::ng-deep .weights-card {
|
||||
background: var(--sg-surface, #fff);
|
||||
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||
box-shadow: none;
|
||||
|
||||
mat-card-content.mat-mdc-card-content {
|
||||
padding: 0.5rem 0.5rem 0.25rem; /* compact bottom */
|
||||
border: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
HEADER
|
||||
============================================================ */
|
||||
.weights-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.4rem;
|
||||
margin-bottom: 0.3rem;
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 650;
|
||||
color: var(--sg-text-primary);
|
||||
}
|
||||
|
||||
button {
|
||||
min-height: $touch-target;
|
||||
padding: 0.2rem 0.4rem;
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.2;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
SLIDERS
|
||||
============================================================ */
|
||||
.weight-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
margin-top: 0.1rem;
|
||||
}
|
||||
|
||||
.weight-row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr 40px;
|
||||
align-items: center;
|
||||
gap: 0.2rem;
|
||||
min-height: 34px;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.weight-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.2rem;
|
||||
color: var(--sg-text-primary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
|
||||
.icon-small {
|
||||
font-size: 14px;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
color: var(--sg-text-secondary);
|
||||
}
|
||||
|
||||
span {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
|
||||
.weight-slider {
|
||||
width: 100%;
|
||||
height: 20px; /* reduced from 24px */
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.weight-value {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 650;
|
||||
color: var(--sg-text-secondary);
|
||||
text-align: right;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
WARNING
|
||||
============================================================ */
|
||||
.weight-warning {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.2rem;
|
||||
margin-top: 0.2rem;
|
||||
padding: 0.2rem 0.3rem;
|
||||
border-radius: 3px;
|
||||
background: color-mix(in srgb, #ff9800 12%, #ffffff);
|
||||
color: #8a5200;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 500;
|
||||
|
||||
mat-icon {
|
||||
font-size: 14px;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
ACTIONS
|
||||
============================================================ */
|
||||
.weight-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-top: 0.3rem;
|
||||
|
||||
button {
|
||||
min-height: $touch-target;
|
||||
padding: 0.2rem 0.6rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
TOOLTIP
|
||||
============================================================ */
|
||||
.tooltip-sm {
|
||||
font-size: 0.75rem;
|
||||
padding: 0.3rem 0.5rem;
|
||||
max-width: 200px;
|
||||
border-radius: 3px;
|
||||
background: var(--sg-surface, #fff);
|
||||
color: var(--sg-text-primary);
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
TABLET & PHONE
|
||||
============================================================ */
|
||||
@media (max-width: $tablet) {
|
||||
.weight-row {
|
||||
grid-template-columns: 1fr 40px;
|
||||
gap: 0.15rem;
|
||||
padding: 0.1rem 0;
|
||||
}
|
||||
|
||||
.weight-label {
|
||||
grid-column: 1 / -1;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.weight-slider {
|
||||
grid-column: 1 / 2;
|
||||
}
|
||||
|
||||
.weight-value {
|
||||
grid-column: 2 / 3;
|
||||
}
|
||||
|
||||
.weight-actions {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
z-index: 5;
|
||||
background: var(--sg-background, #fff);
|
||||
padding: 0.4rem;
|
||||
margin: 0.3rem -0.5rem -0.25rem -0.5rem;
|
||||
box-shadow: 0 -2px 6px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: $phone) {
|
||||
.weights-header {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 0.2rem;
|
||||
}
|
||||
|
||||
.weight-row {
|
||||
gap: 0.1rem;
|
||||
min-height: 30px;
|
||||
}
|
||||
|
||||
.weight-label {
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
|
||||
.weight-slider {
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
.weight-value {
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
|
||||
.weight-actions {
|
||||
padding: 0.3rem;
|
||||
margin: 0.2rem -0.4rem -0.2rem -0.4rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
import {
|
||||
Component,
|
||||
DestroyRef,
|
||||
EventEmitter,
|
||||
Input,
|
||||
OnChanges,
|
||||
OnInit,
|
||||
Output,
|
||||
SimpleChanges,
|
||||
inject,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { FormControl, FormRecord, ReactiveFormsModule } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { debounceTime, skip } from 'rxjs';
|
||||
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatDividerModule } from '@angular/material/divider';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatSliderModule } from '@angular/material/slider';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
|
||||
export interface WeightSliderOption {
|
||||
key: string;
|
||||
label: string;
|
||||
icon?: string;
|
||||
description?: string;
|
||||
|
||||
/**
|
||||
* Optional default raw weight.
|
||||
* Must be between 0 and 1.
|
||||
*/
|
||||
defaultValue?: number;
|
||||
|
||||
/**
|
||||
* Optional explicit query param name.
|
||||
* If not set, queryParamPrefix + key is used.
|
||||
*/
|
||||
queryParamName?: string;
|
||||
}
|
||||
|
||||
export type WeightMap = Record<string, number>;
|
||||
|
||||
export interface WeightsSlidersValue {
|
||||
raw: WeightMap;
|
||||
normalized: WeightMap;
|
||||
rawSum: number;
|
||||
normalizedSum: number;
|
||||
valid: boolean;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-weights-sliders',
|
||||
standalone: true,
|
||||
imports: [
|
||||
ReactiveFormsModule,
|
||||
MatButtonModule,
|
||||
MatCardModule,
|
||||
MatDividerModule,
|
||||
MatIconModule,
|
||||
MatSliderModule,
|
||||
MatTooltipModule,
|
||||
],
|
||||
templateUrl: './weights-sliders.component.html',
|
||||
styleUrl: './weights-sliders.component.scss',
|
||||
})
|
||||
export class WeightsSlidersComponent implements OnInit, OnChanges {
|
||||
private readonly router = inject(Router);
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
@Input({ required: true }) options: WeightSliderOption[] = [];
|
||||
|
||||
@Input() title = 'Suchgewichtung';
|
||||
|
||||
@Input() description =
|
||||
'Werte zwischen 0 und 1. Die normalisierte Gewichtung wird durch Sum-Normalisierung berechnet und ergibt zusammen 1.';
|
||||
|
||||
@Input() resetLabel = 'Ausgewogen';
|
||||
|
||||
@Input() applyLabel = 'Ergebnisse neu gewichten';
|
||||
|
||||
@Input() normalizedTitle = 'Normalisierte Gewichtung';
|
||||
|
||||
@Input() showApplyButton = true;
|
||||
|
||||
@Input() showResetButton = true;
|
||||
|
||||
@Input() showNormalizedPreview = true;
|
||||
|
||||
@Input() showDescriptions = true;
|
||||
|
||||
@Input() persistInQueryParams = true;
|
||||
|
||||
/**
|
||||
* If option.queryParamName is not set, the query param becomes:
|
||||
* queryParamPrefix + option.key
|
||||
*
|
||||
* Example:
|
||||
* queryParamPrefix = 'personW_'
|
||||
* key = 'publications'
|
||||
* query param = personW_publications
|
||||
*/
|
||||
@Input() queryParamPrefix = 'w_';
|
||||
|
||||
/**
|
||||
* Initial raw values from parent.
|
||||
* Example:
|
||||
* {
|
||||
* publications: 0.5,
|
||||
* citations: 0.2
|
||||
* }
|
||||
*/
|
||||
@Input() initialWeights: Partial<WeightMap> | null = null;
|
||||
|
||||
/**
|
||||
* If old values like 50 or 80 arrive, they can be converted to 0.5 / 0.8.
|
||||
*/
|
||||
@Input() convertPercentValues = true;
|
||||
|
||||
@Input() min = 0;
|
||||
|
||||
@Input() max = 1;
|
||||
|
||||
@Input() step = 0.05;
|
||||
|
||||
@Input() decimals = 2;
|
||||
|
||||
@Input() normalizedDecimals = 3;
|
||||
|
||||
@Output() weightsChange = new EventEmitter<WeightsSlidersValue>();
|
||||
|
||||
@Output() applyWeights = new EventEmitter<WeightsSlidersValue>();
|
||||
|
||||
readonly form = new FormRecord<FormControl<number>>({});
|
||||
|
||||
readonly weightsState = signal<WeightsSlidersValue>({
|
||||
raw: {},
|
||||
normalized: {},
|
||||
rawSum: 0,
|
||||
normalizedSum: 0,
|
||||
valid: false,
|
||||
});
|
||||
|
||||
private initialized = false;
|
||||
private isOwnNavigation = false;
|
||||
|
||||
constructor() {
|
||||
this.form.valueChanges
|
||||
.pipe(debounceTime(250), takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(() => {
|
||||
this.updateState({
|
||||
emit: true,
|
||||
persist: this.persistInQueryParams,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.rebuildForm();
|
||||
|
||||
if (this.persistInQueryParams) {
|
||||
this.patchWeightsFromQueryParams();
|
||||
}
|
||||
|
||||
this.updateState({
|
||||
emit: true,
|
||||
persist: false,
|
||||
});
|
||||
|
||||
this.initialized = true;
|
||||
|
||||
if (this.persistInQueryParams) {
|
||||
this.route.queryParamMap
|
||||
.pipe(skip(1), takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(() => {
|
||||
if (this.isOwnNavigation) {
|
||||
this.isOwnNavigation = false;
|
||||
return;
|
||||
}
|
||||
|
||||
this.patchWeightsFromQueryParams();
|
||||
|
||||
this.updateState({
|
||||
emit: true,
|
||||
persist: false,
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges): void {
|
||||
if (
|
||||
changes['options'] ||
|
||||
changes['initialWeights'] ||
|
||||
changes['min'] ||
|
||||
changes['max']
|
||||
) {
|
||||
this.rebuildForm();
|
||||
|
||||
if (this.initialized) {
|
||||
if (this.persistInQueryParams) {
|
||||
this.patchWeightsFromQueryParams();
|
||||
}
|
||||
|
||||
this.updateState({
|
||||
emit: true,
|
||||
persist: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
weightControl(key: string): FormControl<number> {
|
||||
const control = this.form.controls[key];
|
||||
|
||||
if (!control) {
|
||||
throw new Error(`Weight control "${key}" does not exist.`);
|
||||
}
|
||||
|
||||
return control;
|
||||
}
|
||||
|
||||
formatRawWeightLabel = (value: number): string => {
|
||||
return Number(value).toFixed(this.decimals);
|
||||
};
|
||||
|
||||
formatNormalizedWeight(value: number): string {
|
||||
return Number(value).toFixed(this.normalizedDecimals);
|
||||
}
|
||||
|
||||
resetWeights(): void {
|
||||
const nextValues: WeightMap = {};
|
||||
|
||||
for (const option of this.options) {
|
||||
nextValues[option.key] = this.sanitizeWeightValue(
|
||||
option.defaultValue ?? 0.5,
|
||||
);
|
||||
}
|
||||
|
||||
this.form.setValue(nextValues);
|
||||
}
|
||||
|
||||
onApplyClick(): void {
|
||||
const value = this.calculateValue();
|
||||
|
||||
this.updateState({
|
||||
emit: true,
|
||||
persist: this.persistInQueryParams,
|
||||
});
|
||||
|
||||
this.applyWeights.emit(value);
|
||||
}
|
||||
|
||||
normalizedEntries(): Array<{
|
||||
key: string;
|
||||
label: string;
|
||||
value: number;
|
||||
}> {
|
||||
const normalized = this.weightsState().normalized;
|
||||
|
||||
return this.options.map((option) => ({
|
||||
key: option.key,
|
||||
label: option.label,
|
||||
value: normalized[option.key] ?? 0,
|
||||
}));
|
||||
}
|
||||
|
||||
private rebuildForm(): void {
|
||||
const wantedKeys = new Set(this.options.map((option) => option.key));
|
||||
|
||||
for (const existingKey of Object.keys(this.form.controls)) {
|
||||
if (!wantedKeys.has(existingKey)) {
|
||||
this.form.removeControl(existingKey);
|
||||
}
|
||||
}
|
||||
|
||||
for (const option of this.options) {
|
||||
const initialValue = this.resolveInitialValue(option);
|
||||
|
||||
if (this.form.controls[option.key]) {
|
||||
this.form.controls[option.key].setValue(initialValue, {
|
||||
emitEvent: false,
|
||||
});
|
||||
} else {
|
||||
this.form.addControl(
|
||||
option.key,
|
||||
new FormControl(initialValue, { nonNullable: true }),
|
||||
{ emitEvent: false },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private resolveInitialValue(option: WeightSliderOption): number {
|
||||
const fromInput = this.initialWeights?.[option.key];
|
||||
|
||||
if (fromInput !== undefined && fromInput !== null) {
|
||||
return this.sanitizeWeightValue(fromInput);
|
||||
}
|
||||
|
||||
return this.sanitizeWeightValue(option.defaultValue ?? 0.5);
|
||||
}
|
||||
|
||||
private patchWeightsFromQueryParams(): void {
|
||||
const queryParams = this.route.snapshot.queryParamMap;
|
||||
const patch: Record<string, number> = {};
|
||||
|
||||
for (const option of this.options) {
|
||||
const queryParamName = this.getQueryParamName(option);
|
||||
const rawValue = queryParams.get(queryParamName);
|
||||
|
||||
if (rawValue === null) continue;
|
||||
|
||||
patch[option.key] = this.sanitizeWeightValue(rawValue);
|
||||
}
|
||||
|
||||
if (Object.keys(patch).length > 0) {
|
||||
this.form.patchValue(patch, { emitEvent: false });
|
||||
}
|
||||
}
|
||||
|
||||
private updateState(config: { emit: boolean; persist: boolean }): void {
|
||||
const value = this.calculateValue();
|
||||
|
||||
this.weightsState.set(value);
|
||||
|
||||
if (config.persist) {
|
||||
this.updateQueryParams(value.raw);
|
||||
}
|
||||
|
||||
if (config.emit) {
|
||||
this.weightsChange.emit(value);
|
||||
}
|
||||
}
|
||||
|
||||
private calculateValue(): WeightsSlidersValue {
|
||||
const raw = this.getRawWeights();
|
||||
const rawSum = this.sumWeights(raw);
|
||||
const normalized = this.sumNormalize(raw, rawSum);
|
||||
const normalizedSum = this.sumWeights(normalized);
|
||||
|
||||
return {
|
||||
raw,
|
||||
normalized,
|
||||
rawSum,
|
||||
normalizedSum,
|
||||
valid: rawSum > 0,
|
||||
};
|
||||
}
|
||||
|
||||
private getRawWeights(): WeightMap {
|
||||
const rawFormValue = this.form.getRawValue();
|
||||
const result: WeightMap = {};
|
||||
|
||||
for (const option of this.options) {
|
||||
result[option.key] = this.sanitizeWeightValue(rawFormValue[option.key]);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private sumNormalize(raw: WeightMap, rawSum: number): WeightMap {
|
||||
const normalized: WeightMap = {};
|
||||
|
||||
for (const option of this.options) {
|
||||
if (rawSum <= 0 || !Number.isFinite(rawSum)) {
|
||||
normalized[option.key] = 0;
|
||||
} else {
|
||||
normalized[option.key] = raw[option.key] / rawSum;
|
||||
}
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private sumWeights(weights: WeightMap): number {
|
||||
return Object.values(weights).reduce((sum, value) => sum + value, 0);
|
||||
}
|
||||
|
||||
private updateQueryParams(rawWeights: WeightMap): void {
|
||||
const queryParams: Record<string, number> = {};
|
||||
|
||||
for (const option of this.options) {
|
||||
const queryParamName = this.getQueryParamName(option);
|
||||
const value = rawWeights[option.key] ?? 0;
|
||||
|
||||
queryParams[queryParamName] = Number(value.toFixed(this.decimals));
|
||||
}
|
||||
|
||||
this.isOwnNavigation = true;
|
||||
|
||||
this.router
|
||||
.navigate([], {
|
||||
relativeTo: this.route,
|
||||
queryParams,
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true,
|
||||
})
|
||||
.then((navigated) => {
|
||||
if (!navigated) {
|
||||
this.isOwnNavigation = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private getQueryParamName(option: WeightSliderOption): string {
|
||||
return option.queryParamName ?? `${this.queryParamPrefix}${option.key}`;
|
||||
}
|
||||
|
||||
private sanitizeWeightValue(value: unknown): number {
|
||||
const parsed = Number(value);
|
||||
|
||||
if (!Number.isFinite(parsed)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let normalizedInput = parsed;
|
||||
|
||||
if (this.convertPercentValues && this.max === 1 && parsed > 1) {
|
||||
normalizedInput = parsed / 100;
|
||||
}
|
||||
|
||||
return Math.min(
|
||||
this.max,
|
||||
Math.max(this.min, Number(normalizedInput.toFixed(this.decimals))),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user