diff --git a/Jenkinsfile b/Jenkinsfile index 4af1befe..c0715dad 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -28,6 +28,9 @@ pipeline { } stage('Save Docker image') { + when { + branch 'main' + } steps { sh 'docker save ${IMAGE_PREFIX}-app:${IMAGE_VERSION} | gzip > app-image.tar.gz' } diff --git a/service/sentence_transformer/index_topics.py b/service/sentence_transformer/index_topics.py index 35cea0cb..7b506427 100644 --- a/service/sentence_transformer/index_topics.py +++ b/service/sentence_transformer/index_topics.py @@ -35,15 +35,6 @@ headers = { "Content-Type": "application/json" } -def float_array_to_base64(vector): - """ - Convert a float vector into a Base64 string representing 32-bit big-endian float bytes. - Elasticsearch expects big-endian floats for binary/Base64 dense_vector encoding. - """ - arr = np.asarray(vector, dtype=np.float32) - big_endian_bytes = arr.astype('>f4').tobytes() - return base64.b64encode(big_endian_bytes).decode('utf-8') - def split_into_sentences(text): if not text: return [] @@ -52,77 +43,6 @@ def split_into_sentences(text): # Filter out empty or extremely short sentences return [s for s in sentences if len(s.strip()) > 3] -def check_and_update_mapping(): - print("Checking 'topicvectors' index...") - - with httpx.Client(timeout=30.0) as client: - exists_resp = client.head(f"{ELASTIC_URL}topicvectors", headers=headers) - if exists_resp.status_code == 404: - print("Index 'topicvectors' does not exist. Creating index with mapping...") - create_payload = { - "mappings": { - "properties": { - "id": {"type": "keyword"}, - "display_name": { - "type": "text", - "fields": { - "keyword": {"type": "keyword", "ignore_above": 256} - } - }, - "display_name_vector": { - "type": "dense_vector", - "dims": 768, - "index": True, - "similarity": "cosine", - "index_options": { - "type": "int8_hnsw", - "m": 16, - "ef_construction": 100 - } - }, - "description": {"type": "text"}, - "description_vectors": { - "type": "nested", - "properties": { - "vector": { - "type": "dense_vector", - "dims": 768, - "index": True, - "similarity": "cosine", - "index_options": { - "type": "int8_hnsw", - "m": 16, - "ef_construction": 100 - } - } - } - }, - "keywords": { - "type": "text", - "fields": { - "keyword": {"type": "keyword"} - } - }, - "cited_by_count": {"type": "long"}, - "works_count": {"type": "long"}, - "updated_date": {"type": "date"}, - "created_date": {"type": "date"} - } - } - } - resp = client.put( - f"{ELASTIC_URL}topicvectors", - json=create_payload, - headers=headers - ) - if resp.status_code == 200: - print("Successfully created 'topicvectors' index.") - else: - print(f"Failed to create index: {resp.status_code} - {resp.text}") - resp.raise_for_status() - else: - print("Index 'topicvectors' already exists.") - def fetch_all_topics(): print("Fetching topics from 'openalex-topics'...") topics = [] @@ -204,8 +124,6 @@ def bulk_index_topics(topics, display_name_vectors, nested_description_vectors): print(f"Indexed batch {i} to {i + len(batch_topics)}") def main(): - check_and_update_mapping() - topics = fetch_all_topics() if not topics: print("No topics found. Exiting.") diff --git a/service/src/data/users.json b/service/src/data/users.json index 6d5b0836..450db22c 100644 --- a/service/src/data/users.json +++ b/service/src/data/users.json @@ -1,17 +1,21 @@ { "users": [ { - "account": 0, - "organization": 0, "username": "superadmin", "password": "superadmin", + "email": "some_email@uni-due.de", + "account": 0, + "organization": 0, + "organization_name": "University of Duisburg-Essen", "superadmin": true }, { - "account": 1, - "organization": 1, "username": "user", "password": "user", + "email": "user_email@uni-due.de", + "account": 1, + "organization": 1, + "organization_name": "University of Duisburg-Essen", "superadmin": false } ] diff --git a/service/src/main/inse/account/logic.py b/service/src/main/inse/account/logic.py index 96257b7e..b443254c 100644 --- a/service/src/main/inse/account/logic.py +++ b/service/src/main/inse/account/logic.py @@ -33,3 +33,34 @@ def validate_user(username: str, password: str) -> typing.Optional[model.User]: if user and user.password == password: return user return None + +def create_user(username, password, email, institution, superadmin) -> typing.Optional[model.User]: + ''' Adds a new user to the user configuration file. ''' + users = _get_users() + if any(u.username == username for u in users): + logger.warning("Attempt to create duplicate user: %s", username) + return None + + # Determine new IDs + next_account = max((u.account for u in users), default=0) + 1 + next_org = max((u.organization for u in users), default=0) + 1 + + new_user = model.User( + username=username, + password=password, + email=email, + account=next_account, + organization=next_org, + organization_name=institution, + superadmin=superadmin + ) + + users.append(new_user) + user_file = model.UserFile(users=users) + try: + with open('../data/users.json', 'w') as file: + file.write(user_file.model_dump_json(indent=4)) + return new_user + except Exception as e: + logger.error('Could not write user configuration file.', exc_info=e) + return None diff --git a/service/src/main/inse/account/model.py b/service/src/main/inse/account/model.py index dd409091..6a2cca19 100644 --- a/service/src/main/inse/account/model.py +++ b/service/src/main/inse/account/model.py @@ -13,8 +13,10 @@ class User(BaseModel): ''' An entry in the user configuration file. ''' username: str = Field(description="The username of the user.") password: str = Field(description="The password of the user.") + email: str = Field(description="The email of the user.") account: StrictInt = Field(description="The account id of the user.") organization: StrictInt = Field(description="The organization id of the user.") + organization_name: str = Field(description="The organization name of the user.") superadmin: bool = Field(default=False, description="Indicates whether the user is a superadmin.") @@ -27,6 +29,8 @@ class AuthAccount(BaseModel): i: int l: str o: int + e: str + on: str class AuthScope(BaseModel): diff --git a/service/src/main/inse/account/service.py b/service/src/main/inse/account/service.py index 7e67bb19..ae99cd7b 100644 --- a/service/src/main/inse/account/service.py +++ b/service/src/main/inse/account/service.py @@ -27,6 +27,7 @@ router = fastapi.APIRouter( @router.post( "/auth/id", + operation_id="getIdentityGrant", responses={ HTTP_200_OK: {"model": model.IdentityGrant}, HTTP_400_BAD_REQUEST: { @@ -55,7 +56,11 @@ async def get_identity_grant( exp = 12 * 60 * 60 token = security.id_token(user, exp=exp) account = model.AuthAccount( - i=user.account, l=user.username, o=user.organization + i=user.account, + l=user.username, + o=user.organization, + e=user.email, + on=user.organization_name, ) scope = model.AuthScope(t="ID", a=account, d=None, r=[]) grant = model.IdentityGrant( @@ -70,6 +75,7 @@ async def get_identity_grant( @router.post( "/auth/access", + operation_id="getAccessGrant", responses={ HTTP_200_OK: {"model": model.AccessGrant}, HTTP_400_BAD_REQUEST: { @@ -104,7 +110,11 @@ async def get_access_grant( token = security.access_token(user, exp=exp) refresh = security.refresh_token(user, exp=exp) auth_account = model.AuthAccount( - i=user.account, l=user.username, o=user.organization + i=user.account, + l=user.username, + o=user.organization, + e=user.email, + on=user.organization_name, ) scope = model.AuthScope( t="ACCESS", @@ -124,3 +134,36 @@ async def get_access_grant( except Exception as e: logger.error("Token generation failed (%s).", user.username, exc_info=e) raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR) + + +@router.post( + "/create", + operation_id="createUser", + responses={ + HTTP_200_OK: {"model": model.User}, + HTTP_400_BAD_REQUEST: { + "model": None, + "description": "User creation failed (e.g. duplicate username).", + }, + HTTP_500_INTERNAL_SERVER_ERROR: { + "model": None, + "description": "Internal server error.", + }, + }, +) +async def create_user( + username: typing.Annotated[str, fastapi.Body()], + password: typing.Annotated[str, fastapi.Body()], + email: typing.Annotated[str, fastapi.Body()], + institution: typing.Annotated[str, fastapi.Body()], + superadmin: typing.Annotated[bool, fastapi.Body()] = False, +): + user = logic.create_user(username, password, email, institution, superadmin) + if user is None: + logger.info("User creation failed for (%s).", username) + raise fastapi.HTTPException( + status_code=HTTP_400_BAD_REQUEST, + detail="User creation failed. Username might already exist." + ) + logger.info("User created successfully (%s).", username) + return user diff --git a/service/src/main/inse/institutions/institutions_search_client.py b/service/src/main/inse/institutions/institutions_search_client.py index 23a736af..dd895930 100644 --- a/service/src/main/inse/institutions/institutions_search_client.py +++ b/service/src/main/inse/institutions/institutions_search_client.py @@ -1,79 +1,73 @@ import logging from typing import List, Set -import httpx - from inse.models.openalex.institution import Institution from inse.exceptions import NotFoundException +from inse.integrations import elasticsearch logger = logging.getLogger(__name__) class InstitutionsSearchClient: - def __init__( - self, - base_url: str, - api_key: str, - ): - self.base_url = base_url - self.api_key = api_key - self.headers = { - "Content-Type": "application/json", - "Authorization": f"ApiKey {self.api_key}", - } + def __init__(self): + """ + Initializes the client. Credentials and URLs are handled by the + centralized elasticsearch integration. + """ + pass async def get_institution_by_id(self, raw_institution_id: str) -> Institution: + """ + Retrieves a single institution by its OpenAlex ID from the local Elasticsearch cluster. + """ query = { - "query": { - "match": { - "id": f"https://openalex.org/{raw_institution_id.upper()}", - } - }, - "size": 1, + "match": { + "id": f"https://openalex.org/{raw_institution_id.upper()}", + } } + + res = elasticsearch.search( + index="openalex-institutions", + query=query, + size=1 + ) + + hits = res.get("hits", {}).get("hits", []) + if not hits: + raise NotFoundException(f"Institution with ID '{raw_institution_id}' not found.") + authors = await self.get_authors_by_institution_id(raw_institution_id) logger.debug( "Retrieved authors for institution_id=%s: %s", raw_institution_id, authors ) - - async with httpx.AsyncClient() as client: - response = await client.post( - f"{self.base_url}/openalex-institutions/_search", - json=query, - headers=self.headers, - ) - response.raise_for_status() - hits = response.json().get("hits", {}).get("hits", []) - if not hits: - raise NotFoundException( - f"Institution with ID '{raw_institution_id}' not found." - ) - - return Institution.from_dict(hits[0]["_source"]) + + return Institution.from_dict(hits[0]["_source"]) async def get_authors_by_institution_id(self, raw_institution_id: str) -> List[str]: + """ + Fetches authors associated with an institution. + Note: This query is specifically looking for current affiliations (2026). + """ query = { - "query": { - "nested": { - "path": "affiliations", - "query": { - "bool": { - "must": [ - { - "term": { - "affiliations.institution.id": f"https://openalex.org/{raw_institution_id.upper()}" - } - }, - { - "range": { - "affiliations.years": {"gte": 2026, "lte": 2026} - } - }, - ] - } - }, - } + "nested": { + "path": "affiliations", + "query": { + "bool": { + "must": [ + { + "term": { + "affiliations.institution.id": f"https://openalex.org/{raw_institution_id.upper()}" + } + }, + { + "range": { + "affiliations.years": {"gte": 2026, "lte": 2026} + } + }, + ] + } + }, } } logger.debug( @@ -81,30 +75,103 @@ class InstitutionsSearchClient: raw_institution_id, query, ) - async with httpx.AsyncClient() as client: - response = await client.post( - "https://project.nes.uni-due.de/elastic/openalex-authors/_search", - json=query, - headers=self.headers, - ) - try: - response.raise_for_status() - except httpx.HTTPStatusError as e: - logger.exception( - "Error fetching authors for institution_id=%s: %s, response content: %s", - raw_institution_id, - str(e), - response.text, - ) - return [] - hits = response.json().get("hits", {}).get("hits", []) - authors = set() - for hit in hits: - authors.update( - auth["author"]["display_name"] - for auth in hit["_source"].get("authorships", []) - ) - return list(authors) + + res = elasticsearch.search(index="openalex-authors", query=query) + hits = res.get("hits", {}).get("hits", []) + + # Extracting display_name directly from the author document source + authors = {hit["_source"].get("display_name") for hit in hits if hit["_source"].get("display_name")} + return list(authors) + async def search_institutions( + self, + query_text: str, + country_code: str | None = None, + institution_type: str | None = None, + limit: int = 10, + ) -> list[Institution]: + """ + Autocomplete search for institutions using multi_match on search_as_you_type fields. + Falls back to fuzzy match for typo tolerance on longer queries. + """ + must = [] + + if query_text: + stripped = query_text.strip() + + must.append({ + "bool": { + "should": [ + # Fast prefix matching via search_as_you_type shingles + { + "multi_match": { + "query": stripped, + "type": "bool_prefix", + "fields": [ + "display_name.search", + "display_name.search._2gram", + "display_name.search._3gram", + "display_name_alternatives.search", + "display_name_alternatives.search._2gram", + ], + "boost": 2, + } + }, + # Exact acronym match — high confidence signal + { + "term": { + "display_name_acronyms.keyword": { + "value": stripped.upper(), + "boost": 10, + } + } + }, + # Fuzzy fallback for typos (only worth it for longer input) + *( + [{ + "match": { + "display_name": { + "query": stripped, + "fuzziness": "AUTO", + "boost": 1, + } + } + }] + if len(stripped) >= 4 else [] + ), + ], + "minimum_should_match": 1, + } + }) + + filter_queries = [] + + if country_code: + filter_queries.append({"term": {"country_code": country_code.upper()}}) + + if institution_type: + filter_queries.append({"term": {"type": institution_type}}) + + query = { + "bool": { + "must": must, + "filter": filter_queries, + } + } + + res = elasticsearch.search( + index="openalex-institutions", + query=query, + size=limit, + # Blend relevance score with works_count popularity signal + sort=[ + {"works_count": {"order": "desc"}}, + ], + source=["id", "display_name", "country_code", "type", "works_count", "cited_by_count", "geo"], + ) + + hits = res.get("hits", {}).get("hits", []) + + return [Institution.from_dict(hit["_source"]) for hit in hits] async def get_institution_aliases_by_id(self, raw_institution_id: str) -> List[str]: """Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases. diff --git a/service/src/main/inse/institutions/logic.py b/service/src/main/inse/institutions/logic.py index a4f834ee..7562672e 100644 --- a/service/src/main/inse/institutions/logic.py +++ b/service/src/main/inse/institutions/logic.py @@ -114,34 +114,29 @@ async def autocomplete_institutions( country_code: str | None = None, institution_type: str | None = None, limit: int = 10, - client: OpenAlexInstitutionsClient | None = None, + client: InstitutionsSearchClient, ) -> AutocompleteResponse: - filters = [] - if country_code: - filters.append(f"country_code:{country_code}") - if institution_type: - filters.append(f"type:{institution_type}") - - response = await list_institutions( - search=query, - filter=",".join(filters) if filters else None, - sort="works_count:desc", - per_page=limit, - page=1, - select=("id,ror,display_name,country_code,type,works_count,cited_by_count,geo"), - client=client, + """ + Returns institution options for autocomplete inputs using the local + Elasticsearch cluster via the provided client. + """ + institutions = await client.search_institutions( + query_text=query, + country_code=country_code, + institution_type=institution_type, + limit=limit, ) results = [] - for institution in response.results or []: + for institution in institutions: if not institution.id or not institution.display_name: continue hint_parts = [] - if institution.geo: - if institution.geo.city: + if hasattr(institution, "geo") and institution.geo: + if hasattr(institution.geo, "city") and institution.geo.city: hint_parts.append(institution.geo.city) - if institution.geo.country: + if hasattr(institution.geo, "country") and institution.geo.country: hint_parts.append(institution.geo.country) elif institution.country_code: hint_parts.append(institution.country_code) @@ -161,12 +156,7 @@ async def autocomplete_institutions( ) return AutocompleteResponse( - meta=AutocompleteResponseMeta( - count=response.meta.count if response.meta else len(results), - db_response_time_ms=( - response.meta.db_response_time_ms if response.meta else None - ), - ), + meta=AutocompleteResponseMeta(count=len(results)), results=results, ) diff --git a/service/src/main/inse/institutions/service.py b/service/src/main/inse/institutions/service.py index dd13b718..5c08bbdf 100644 --- a/service/src/main/inse/institutions/service.py +++ b/service/src/main/inse/institutions/service.py @@ -18,44 +18,12 @@ from . import logic from inse.institutions.institutions_search_client import InstitutionsSearchClient -router = APIRouter(prefix="/api/institutions", tags=[Tags.INSTITUTIONS]) +router = APIRouter(prefix="/api/inse-service/institutions", tags=[Tags.INSTITUTIONS]) @lru_cache def get_institutions_search_client() -> InstitutionsSearchClient: - settings = get_settings() - if not settings.elasticsearch_url: - raise ValueError("Elasticsearch URL is missing in settings.") - if not settings.elasticsearch_api_key: - raise ValueError("Elasticsearch API key is missing in settings.") - - return InstitutionsSearchClient( - api_key=settings.elasticsearch_api_key, - base_url=settings.elasticsearch_url, - ) - - -@router.get( - "/{id}", - summary="Returns a single institution by ID.", - description="Returns a single institution by its OpenAlex ID.", - operation_id="getInstitutionById", - responses={ - status.HTTP_200_OK: { - "description": "Successful Response", - "model": Institution, - }, - status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, - }, -) -async def get_institution( - id: str, - client: Annotated[ - InstitutionsSearchClient, Depends(get_institutions_search_client) - ], -) -> Institution: - return await logic.get_institution_by_id(raw_institution_id=id, client=client) - + return InstitutionsSearchClient() @router.get( "/autocomplete", @@ -84,12 +52,14 @@ async def autocomplete_institutions( int, Query(description="Maximum number of autocomplete options.", ge=1, le=25), ] = 10, + client: Annotated[InstitutionsSearchClient, Depends(get_institutions_search_client)] = None, ): return await logic.autocomplete_institutions( query=query, country_code=country_code, institution_type=institution_type, limit=limit, + client=client, ) @@ -155,3 +125,25 @@ async def list_institutions( sample=sample, select=select, ) + + +@router.get( + "/{id}", + summary="Returns a single institution by ID.", + description="Returns a single institution by its OpenAlex ID.", + operation_id="getInstitutionById", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": Institution, + }, + status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, + }, +) +async def get_institution( + id: str, + client: Annotated[ + InstitutionsSearchClient, Depends(get_institutions_search_client) + ], +) -> Institution: + return await logic.get_institution_by_id(raw_institution_id=id, client=client) diff --git a/service/src/main/inse/institutions/test_logic.py b/service/src/main/inse/institutions/test_logic.py index e079ff8e..bebf52c0 100644 --- a/service/src/main/inse/institutions/test_logic.py +++ b/service/src/main/inse/institutions/test_logic.py @@ -176,61 +176,3 @@ async def test_list_institutions_accepts_practical_openalex_type_variants(): assert result.results[0].counts_by_year[0].cited_by_count is None assert result.group_by[0].key == "true" - -@pytest.mark.anyio -async def test_autocomplete_institutions_returns_frontend_options(): - def handler(request: httpx.Request) -> httpx.Response: - assert request.url.params["search"] == "Duisburg Essen" - assert request.url.params["filter"] == "country_code:DE,type:education" - assert request.url.params["sort"] == "works_count:desc" - assert request.url.params["per_page"] == "5" - assert request.url.params["select"] == ( - "id,ror,display_name,country_code,type,works_count," - "cited_by_count,geo" - ) - return httpx.Response( - 200, - json={ - "meta": {"count": 1, "db_response_time_ms": 12}, - "results": [ - { - "id": "https://openalex.org/I123", - "ror": "https://ror.org/04mz5ra38", - "display_name": "University of Duisburg-Essen", - "country_code": "DE", - "type": "education", - "works_count": 123, - "cited_by_count": 456, - "geo": { - "city": "Duisburg", - "country": "Germany", - }, - } - ], - }, - ) - - client = OpenAlexInstitutionsClient( - api_key="test-key", - transport=httpx.MockTransport(handler), - ) - - result = await logic.autocomplete_institutions( - query="Duisburg Essen", - country_code="DE", - institution_type="education", - limit=5, - client=client, - ) - - 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/I123" - assert option.display_name == "University of Duisburg-Essen" - assert option.hint == "Duisburg · Germany · education" - assert option.works_count == 123 - assert option.cited_by_count == 456 - assert option.entity_type == "institution" - assert option.external_id == "https://ror.org/04mz5ra38" diff --git a/service/src/main/inse/models/openalex/institution.py b/service/src/main/inse/models/openalex/institution.py index a81ae678..6121af94 100644 --- a/service/src/main/inse/models/openalex/institution.py +++ b/service/src/main/inse/models/openalex/institution.py @@ -55,13 +55,20 @@ class Institution(BaseModel): updated_date: Optional[datetime] = Field(default=None, description="When this institution was last updated (ISO 8601 datetime).") __properties: ClassVar[List[str]] = ["id", "ror", "display_name", "country_code", "type", "homepage_url", "image_url", "image_thumbnail_url", "display_name_acronyms", "display_name_alternatives", "works_count", "cited_by_count", "summary_stats", "geo", "lineage", "ids", "counts_by_year", "works_api_url", "created_date", "updated_date"] + @field_validator('created_date', mode='before') + @classmethod + def normalize_created_date(cls, v: Any) -> Any: + if isinstance(v, str) and len(v) > 10: + return v[:10] + return v + @field_validator('type') def type_validate_enum(cls, value): """Validates the enum""" if value is None: return value - if value not in set(['education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other']): + if value not in set(['education','funder', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other']): raise ValueError("must be one of enum values ('education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other')") return value @@ -154,5 +161,3 @@ class Institution(BaseModel): "updated_date": obj.get("updated_date") }) return _obj - - diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 88b36788..76db43c7 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -7,7 +7,9 @@ Business logic for persons / authors. import json import logging import time +from datetime import datetime from typing import Optional, Callable, Any, List +from elasticsearch import ApiError, NotFoundError import hashlib import httpx from fastapi import HTTPException @@ -24,8 +26,8 @@ from inse.persons.model import ( CustomAuthor, CustomAuthorsListResponse, PersonSearchRequest, + CareerMetrics, ) - logger = logging.getLogger(__name__) INDEX_NAME = "openalex-authors" @@ -186,6 +188,120 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: return works, topics +def _get_publication_years_for_author(author_id: str) -> list[int]: + author_url = f"https://openalex.org/{author_id.strip()}" + + body = { + "size": 0, + "query": { + "nested": { + "path": "authorships", + "query": { + "bool": { + "filter": [ + {"term": {"authorships.author.id": author_url}}, + ], + }, + }, + }, + }, + "aggs": { + "publication_years": { + "terms": { + "field": "publication_year", + "size": 1000, + }, + }, + }, + } + + response = elasticsearch.search( + index=config.settings.openalex_works_search_index, + body=body, + ) + + buckets = ( + response.get("aggregations", {}) + .get("publication_years", {}) + .get("buckets", []) + ) + + publication_years: list[int] = [] + + for bucket in buckets: + year = bucket.get("key") + count = bucket.get("doc_count", 0) + + if isinstance(year, int): + publication_years.extend([year] * count) + + return publication_years + +def _classify_career_stage(active_years: int) -> str: + if active_years <= 0: + return "unknown" + + if active_years <= 4: + return "Early Researcher" + + if active_years <= 10: + return "Emerging Researcher" + + if active_years <= 20: + return "Established Researcher" + + return "Senior Researcher" + + +def _compute_career_metrics(publication_years: list[int]) -> CareerMetrics: + current_year = datetime.now().year + + if not publication_years: + return CareerMetrics() + + sorted_years = sorted(publication_years) + unique_years = sorted(set(publication_years)) + + first_year = sorted_years[0] + last_year = sorted_years[-1] + + publication_count = len(sorted_years) + active_years = len(unique_years) + career_stage = _classify_career_stage(active_years) + career_age = last_year - first_year + career_span = last_year - first_year + 1 + + publications_per_active_year = ( + publication_count / active_years if active_years > 0 else None + ) + + publications_per_career_year = ( + publication_count / career_span if career_span > 0 else None + ) + + years_since_last_publication = current_year - last_year + has_suspicious_publication_years = first_year < 1970 or career_span > 60 + + return CareerMetrics( + first_publication_year=first_year, + last_publication_year=last_year, + career_age=career_age, + career_span=career_span, + career_stage=career_stage, + active_years=active_years, + publication_count=publication_count, + publications_per_active_year=publications_per_active_year, + publications_per_career_year=publications_per_career_year, + years_since_last_publication=years_since_last_publication, + has_suspicious_publication_years=has_suspicious_publication_years, + ) + + +def get_career_metrics_for_author(author_id: str) -> CareerMetrics: + publication_years = _get_publication_years_for_author(author_id) + return _compute_career_metrics(publication_years) + + def _build_papers(works: list) -> list: papers = [] @@ -254,23 +370,34 @@ def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> s def get_person_by_id( author_id: str, include: Optional[str] = None -) -> AuthorsListResponse: +) -> CustomAuthorsListResponse: body = { "_source": include.split(",") if include else True, } try: - hit = elasticsearch.get(index="openalex-authors", body=body, doc_id=author_id) + hit = elasticsearch.get( + index="openalex-authors", + body=body, + doc_id=author_id, + ) except NotFoundError: raise HTTPException( status_code=404, detail=f"Person with id {author_id} not found" ) - except ApiError as e: raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}") - persons = [util.get_persons_data(hit)] - return AuthorsListResponse(results=persons) + author = util.get_persons_data(hit) + career_metrics = get_career_metrics_for_author(author_id) + + custom_author = CustomAuthor( + **author.model_dump(), + career_metrics=career_metrics, + ) + + return CustomAuthorsListResponse(results=[custom_author]) + def search_persons_by_name( diff --git a/service/src/main/inse/persons/model.py b/service/src/main/inse/persons/model.py index 1973c763..300ec2d9 100644 --- a/service/src/main/inse/persons/model.py +++ b/service/src/main/inse/persons/model.py @@ -13,20 +13,59 @@ from inse.models.openalex.authors_list_response import AuthorsListResponse from inse.models.openalex.group_by_result import GroupByResult +class CareerMetrics(BaseModel): + first_publication_year: Optional[int] = Field( + default=None, description="First publication year of the author." + ) + last_publication_year: Optional[int] = Field( + default=None, description="Last publication year of the author." + ) + career_age: Optional[int] = Field( + default=None, description="Difference between last and first publication year." + ) + career_span: Optional[int] = Field( + default=None, description="Inclusive span from first to last publication year." + ) + career_stage: Optional[str] = Field( + default=None, + description="Threshold-based career stage derived from active publication years.", + ) + active_years: int = Field( + default=0, description="Number of distinct years with at least one publication." + ) + publication_count: int = Field( + default=0, description="Number of publications used for career metrics." + ) + publications_per_active_year: Optional[float] = Field( + default=None, description="Average publications per active publication year." + ) + publications_per_career_year: Optional[float] = Field( + default=None, description="Average publications per year over the full career span." + ) + years_since_last_publication: Optional[int] = Field( + default=None, description="Years since the last publication." + ) + has_suspicious_publication_years: bool = Field( + default=False, description="True if publication years look suspicious." + ) + class CustomAuthor(Author): relevance_rating: Optional[str] = Field( default=None, description="The relevance suitability rating." ) + career_metrics: Optional[CareerMetrics] = Field( + default=None, description="Publication-history-based career metrics." + ) class CustomAuthorsListResponse(AuthorsListResponse): placeholder: Optional[CustomAuthor] = Field( default=None, description="A placeholder field for generation." ) - # meta: Optional[Meta] = None - # results: Optional[List[CustomAuthor]] = None - # group_by: Optional[List[GroupByResult]] = None + results: Optional[List[CustomAuthor]] = None + meta: Optional[Meta] = None + group_by: Optional[List[GroupByResult]] = None class PersonBio(BaseModel): diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py index 35034d82..c6cae176 100644 --- a/service/src/main/inse/persons/service.py +++ b/service/src/main/inse/persons/service.py @@ -85,7 +85,7 @@ def generate_person_bio( @router.get( "/person/{id}", operation_id="getPersonByID", - response_model=AuthorsListResponse, + response_model=model.CustomAuthorsListResponse, summary="Searches for person by ID.", tags=["Persons"], ) @@ -102,7 +102,7 @@ def get_person_by_id( ), example="topics_full,topic_share", ), - ], + ] = None, ): return logic.get_person_by_id(author_id=id, include=include) diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 8e08ac07..707098fd 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -1,5 +1,4 @@ .gitignore -.openapi-generator-ignore README.md api.base.service.ts api.module.ts @@ -36,6 +35,7 @@ model/autocompleteResponse.ts model/autocompleteResponseMeta.ts model/autocompleteResponseResultsInner.ts model/award.ts +model/bodyCreateUser.ts model/bundProject.ts model/bundProjectPage.ts model/categoryNested.ts @@ -95,6 +95,7 @@ model/topicSubfield.ts model/topicsByTime.ts model/topicsByYear.ts model/topicsListResponse.ts +model/user.ts model/validationError.ts model/validationErrorLocInner.ts model/value.ts diff --git a/webapp/src/app/api/api/iNSEAccountService.service.ts b/webapp/src/app/api/api/iNSEAccountService.service.ts index 116f1dd4..4874a0a8 100644 --- a/webapp/src/app/api/api/iNSEAccountService.service.ts +++ b/webapp/src/app/api/api/iNSEAccountService.service.ts @@ -25,9 +25,13 @@ import { Observable } from 'rxjs'; // @ts-ignore import { AccessGrant } from '../model/accessGrant'; // @ts-ignore +import { BodyCreateUser } from '../model/bodyCreateUser'; +// @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore import { IdentityGrant } from '../model/identityGrant'; +// @ts-ignore +import { User } from '../model/user'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; @@ -46,6 +50,116 @@ export class INSEAccountServiceService extends BaseService { super(basePath, configuration); } + /** + * Create User + * @endpoint post /inse-account/create + * @param bodyCreateUser + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUser( + bodyCreateUser: BodyCreateUser, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public createUser( + bodyCreateUser: BodyCreateUser, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public createUser( + bodyCreateUser: BodyCreateUser, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public createUser( + bodyCreateUser: BodyCreateUser, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (bodyCreateUser === null || bodyCreateUser === undefined) { + throw new Error( + 'Required parameter bodyCreateUser was null or undefined when calling createUser.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/inse-account/create`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, { + context: localVarHttpContext, + body: bodyCreateUser, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }); + } + /** * Get Access Grant * @endpoint post /inse-account/auth/access @@ -55,7 +169,7 @@ export class INSEAccountServiceService extends BaseService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getAccessGrantInseAccountAuthAccessPost( + public getAccessGrant( secret: string, account: number, organization: number, @@ -67,7 +181,7 @@ export class INSEAccountServiceService extends BaseService { transferCache?: boolean; }, ): Observable; - public getAccessGrantInseAccountAuthAccessPost( + public getAccessGrant( secret: string, account: number, organization: number, @@ -79,7 +193,7 @@ export class INSEAccountServiceService extends BaseService { transferCache?: boolean; }, ): Observable>; - public getAccessGrantInseAccountAuthAccessPost( + public getAccessGrant( secret: string, account: number, organization: number, @@ -91,7 +205,7 @@ export class INSEAccountServiceService extends BaseService { transferCache?: boolean; }, ): Observable>; - public getAccessGrantInseAccountAuthAccessPost( + public getAccessGrant( secret: string, account: number, organization: number, @@ -105,17 +219,17 @@ export class INSEAccountServiceService extends BaseService { ): Observable { if (secret === null || secret === undefined) { throw new Error( - 'Required parameter secret was null or undefined when calling getAccessGrantInseAccountAuthAccessPost.', + 'Required parameter secret was null or undefined when calling getAccessGrant.', ); } if (account === null || account === undefined) { throw new Error( - 'Required parameter account was null or undefined when calling getAccessGrantInseAccountAuthAccessPost.', + 'Required parameter account was null or undefined when calling getAccessGrant.', ); } if (organization === null || organization === undefined) { throw new Error( - 'Required parameter organization was null or undefined when calling getAccessGrantInseAccountAuthAccessPost.', + 'Required parameter organization was null or undefined when calling getAccessGrant.', ); } @@ -209,7 +323,7 @@ export class INSEAccountServiceService extends BaseService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getIdentityGrantInseAccountAuthIdPost( + public getIdentityGrant( username: string, password: string, observe?: 'body', @@ -220,7 +334,7 @@ export class INSEAccountServiceService extends BaseService { transferCache?: boolean; }, ): Observable; - public getIdentityGrantInseAccountAuthIdPost( + public getIdentityGrant( username: string, password: string, observe?: 'response', @@ -231,7 +345,7 @@ export class INSEAccountServiceService extends BaseService { transferCache?: boolean; }, ): Observable>; - public getIdentityGrantInseAccountAuthIdPost( + public getIdentityGrant( username: string, password: string, observe?: 'events', @@ -242,7 +356,7 @@ export class INSEAccountServiceService extends BaseService { transferCache?: boolean; }, ): Observable>; - public getIdentityGrantInseAccountAuthIdPost( + public getIdentityGrant( username: string, password: string, observe: any = 'body', @@ -255,12 +369,12 @@ export class INSEAccountServiceService extends BaseService { ): Observable { if (username === null || username === undefined) { throw new Error( - 'Required parameter username was null or undefined when calling getIdentityGrantInseAccountAuthIdPost.', + 'Required parameter username was null or undefined when calling getIdentityGrant.', ); } if (password === null || password === undefined) { throw new Error( - 'Required parameter password was null or undefined when calling getIdentityGrantInseAccountAuthIdPost.', + 'Required parameter password was null or undefined when calling getIdentityGrant.', ); } diff --git a/webapp/src/app/api/api/institutions.service.ts b/webapp/src/app/api/api/institutions.service.ts index e365240f..138c4dd5 100644 --- a/webapp/src/app/api/api/institutions.service.ts +++ b/webapp/src/app/api/api/institutions.service.ts @@ -50,7 +50,7 @@ export class InstitutionsService extends BaseService { /** * Returns institution options for autocomplete inputs. - * @endpoint get /api/institutions/autocomplete + * @endpoint get /api/inse-service/institutions/autocomplete * @param query Institution search text, for example \'Duisburg Essen\'. * @param countryCode Optional ISO country code filter. * @param type Optional institution type filter. @@ -168,7 +168,7 @@ export class InstitutionsService extends BaseService { } } - let localVarPath = `/api/institutions/autocomplete`; + let localVarPath = `/api/inse-service/institutions/autocomplete`; const { basePath, withCredentials } = this.configuration; return this.httpClient.request( 'get', @@ -191,7 +191,7 @@ export class InstitutionsService extends BaseService { /** * Returns a single institution by ID. * Returns a single institution by its OpenAlex ID. - * @endpoint get /api/institutions/{id} + * @endpoint get /api/inse-service/institutions/{id} * @param id * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. @@ -272,7 +272,7 @@ export class InstitutionsService extends BaseService { } } - let localVarPath = `/api/institutions/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; const { basePath, withCredentials } = this.configuration; return this.httpClient.request( 'get', @@ -293,7 +293,7 @@ export class InstitutionsService extends BaseService { /** * Returns a list of OpenAlex institutions. - * @endpoint get /api/institutions + * @endpoint get /api/inse-service/institutions * @param search Full-text search, for example \'Duisburg Essen\'. * @param filter OpenAlex filter, for example \'country_code:DE,type:education\'. * @param sort Sort field, for example \'works_count:desc\'. @@ -455,7 +455,7 @@ export class InstitutionsService extends BaseService { } } - let localVarPath = `/api/institutions`; + let localVarPath = `/api/inse-service/institutions`; const { basePath, withCredentials } = this.configuration; return this.httpClient.request( 'get', diff --git a/webapp/src/app/api/model/authAccount.ts b/webapp/src/app/api/model/authAccount.ts index 179a3e67..7a672b04 100644 --- a/webapp/src/app/api/model/authAccount.ts +++ b/webapp/src/app/api/model/authAccount.ts @@ -12,4 +12,6 @@ export interface AuthAccount { i: number; l: string; o: number; + e: string; + on: string; } diff --git a/webapp/src/app/api/model/bodyCreateUser.ts b/webapp/src/app/api/model/bodyCreateUser.ts new file mode 100644 index 00000000..6a0778be --- /dev/null +++ b/webapp/src/app/api/model/bodyCreateUser.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export interface BodyCreateUser { + username: string; + password: string; + email: string; + institution: string; + superadmin?: boolean; +} diff --git a/webapp/src/app/api/model/collaborationNetworkNodeType.ts b/webapp/src/app/api/model/collaborationNetworkNodeType.ts index 3e673f35..20d462bd 100644 --- a/webapp/src/app/api/model/collaborationNetworkNodeType.ts +++ b/webapp/src/app/api/model/collaborationNetworkNodeType.ts @@ -9,9 +9,9 @@ */ export const CollaborationNetworkNodeType = { - Author: 'author', - Institution: 'institution', - Work: 'work', + author: 'author', + institution: 'institution', + work: 'work', } as const; export type CollaborationNetworkNodeType = (typeof CollaborationNetworkNodeType)[keyof typeof CollaborationNetworkNodeType]; diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 8caaecfd..7b37e6c3 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -16,6 +16,7 @@ export * from './autocompleteResponse'; export * from './autocompleteResponseMeta'; export * from './autocompleteResponseResultsInner'; export * from './award'; +export * from './bodyCreateUser'; export * from './bundProject'; export * from './bundProjectPage'; export * from './categoryNested'; @@ -74,6 +75,7 @@ export * from './topicSubfield'; export * from './topicsByTime'; export * from './topicsByYear'; export * from './topicsListResponse'; +export * from './user'; export * from './validationError'; export * from './validationErrorLocInner'; export * from './value'; diff --git a/webapp/src/app/api/model/user.ts b/webapp/src/app/api/model/user.ts new file mode 100644 index 00000000..7e82821c --- /dev/null +++ b/webapp/src/app/api/model/user.ts @@ -0,0 +1,43 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * An entry in the user configuration file. + */ +export interface User { + /** + * The username of the user. + */ + username: string; + /** + * The password of the user. + */ + password: string; + /** + * The email of the user. + */ + email: string; + /** + * The account id of the user. + */ + account: number; + /** + * The organization id of the user. + */ + organization: number; + /** + * The organization name of the user. + */ + organization_name: string; + /** + * Indicates whether the user is a superadmin. + */ + superadmin?: boolean; +} diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 0dd9d706..068e2080 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -8,8 +8,12 @@ import { institutionResolver } from './resolvers/institution.resolver'; import { bundProjectsResolver } from './resolvers/bund-projects.resolver'; import { euProjectsResolver } from './resolvers/eu-projects.resolver'; import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver'; - export const routes: Routes = [ + { + path: '', + pathMatch: 'full', + redirectTo: 'dashboard', + }, { path: 'login', loadComponent: () => @@ -17,6 +21,13 @@ export const routes: Routes = [ (mod) => mod.AppLoginComponent, ), }, + { + path: 'register', + loadComponent: () => + import('./modules/app-register/app-register.component').then( + (mod) => mod.AppRegisterComponent, + ), + }, { path: 'dashboard', canActivate: [userGuard], @@ -250,5 +261,6 @@ export const routes: Routes = [ routeMessage: 'Die gesuchte Seite existiert leider nicht oder wurde verschoben.', }, + canActivate: [userGuard], }, ]; diff --git a/webapp/src/app/modules/app-login/app-login.component.html b/webapp/src/app/modules/app-login/app-login.component.html index 4ebfd0be..e7cb87a6 100644 --- a/webapp/src/app/modules/app-login/app-login.component.html +++ b/webapp/src/app/modules/app-login/app-login.component.html @@ -42,6 +42,12 @@ [disabled]="!loginForm.valid || (credentialService.validating | async)"> Anmelden + +
+ +

@if (credentialService.validating | async) { diff --git a/webapp/src/app/modules/app-login/app-login.component.scss b/webapp/src/app/modules/app-login/app-login.component.scss index 56b7c05a..034b92ac 100644 --- a/webapp/src/app/modules/app-login/app-login.component.scss +++ b/webapp/src/app/modules/app-login/app-login.component.scss @@ -37,7 +37,7 @@ } .field { - width: 300px; + width: 400px; } .progress { diff --git a/webapp/src/app/modules/app-login/app-login.component.ts b/webapp/src/app/modules/app-login/app-login.component.ts index 17353a00..24fd129f 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -13,7 +13,7 @@ import { MatIconModule } from '@angular/material/icon'; import { CommonModule } from '@angular/common'; import { Subscription } from 'rxjs'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; -import { Router } from '@angular/router'; +import { Router, RouterLink } from '@angular/router'; @Component({ selector: 'app-app-login', @@ -25,6 +25,7 @@ import { Router } from '@angular/router'; MatButtonModule, MatIconModule, MatSnackBarModule, + RouterLink, ], templateUrl: './app-login.component.html', styleUrl: './app-login.component.scss', diff --git a/webapp/src/app/modules/app-register/app-register.component.html b/webapp/src/app/modules/app-register/app-register.component.html new file mode 100644 index 00000000..e6349bc5 --- /dev/null +++ b/webapp/src/app/modules/app-register/app-register.component.html @@ -0,0 +1,102 @@ +

+
+

Konto erstellen

+

Bitte gib Deine Daten ein, um Dich zu registrieren.

+ + + Benutzername + + @if (registerForm.controls['username'].hasError('required')) { + Fehler: Benutzername erforderlich. + } @else if (registerForm.controls['username'].hasError('minlength')) { + Fehler: Benutzername ist unvollständig. + } + + + + E-Mail + + @if (registerForm.controls['email'].hasError('required')) { + Fehler: E-Mail erforderlich. + } @else if (registerForm.controls['email'].hasError('email')) { + Fehler: Ungültige E-Mail Adresse. + } + + + + Passwort + + @if (showPassword) { + visibility + } @else { + visibility_off + } + @if (registerForm.controls['password'].hasError('required')) { + Fehler: Passwort erforderlich. + } @else if (registerForm.controls['password'].hasError('minlength')) { + Fehler: Passwort ist unvollständig. + } + + + + Institution + + apartment + + @if (registerForm.controls['institution'].hasError('required')) { + Fehler: Institution erforderlich. + } + + @for (institution of institutionOptions(); track institution.id) { + +
+ {{ institution.display_name }} +
+ @if (institution.hint) { + {{ institution.hint }} + } +
+ } +
+
+ +
+ Superadmin Rechte +
+ + + +
+ +
+
+

+ +

+
diff --git a/webapp/src/app/modules/app-register/app-register.component.scss b/webapp/src/app/modules/app-register/app-register.component.scss new file mode 100644 index 00000000..d1585259 --- /dev/null +++ b/webapp/src/app/modules/app-register/app-register.component.scss @@ -0,0 +1,56 @@ +.container { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; + background: linear-gradient(160deg, #f4f6fb, #e8ecf7); +} + +.form { + display: flex; + flex-direction: column; + align-items: center; + background: #fff; + border: none; + border-radius: 12px; + box-shadow: + 0 2px 12px #1a3a6e1a, + 0 1px 4px #0000000f; + gap: 20px; + padding: 36px 32px 28px; + + h3 { + margin: 0 0 4px; + font-weight: 600; + color: #1a3a6e; + } +} + +.button { + min-height: 48px; + min-width: 140px; + border-radius: 8px; + font-weight: 500; + letter-spacing: 0.02em; +} + +.field { + width: 400px; +} + +.checkbox-container { + display: flex; + align-items: center; + justify-content: flex-start; +} + +.progress { + padding-top: 5px; + width: 300px; + height: 2em; + text-align: center; + font-size: small; + color: #585f71; +} diff --git a/webapp/src/app/modules/app-register/app-register.component.ts b/webapp/src/app/modules/app-register/app-register.component.ts new file mode 100644 index 00000000..42d53887 --- /dev/null +++ b/webapp/src/app/modules/app-register/app-register.component.ts @@ -0,0 +1,173 @@ +import { + Component, + inject, + OnDestroy, + signal, + DestroyRef, + OnInit, +} from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { Router, RouterLink } from '@angular/router'; +import { + FormBuilder, + FormGroup, + ReactiveFormsModule, + Validators, +} from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { MatIconModule } from '@angular/material/icon'; +import { MatCheckboxModule } from '@angular/material/checkbox'; +import { CredentialService } from '../../shared/services/credential.service'; +import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; +import { + Subscription, + map, + switchMap, + debounceTime, + distinctUntilChanged, + catchError, + of, +} from 'rxjs'; +import { + MatAutocompleteModule, + MatAutocompleteSelectedEvent, +} from '@angular/material/autocomplete'; +import { InstitutionsService } from '../../api'; +@Component({ + selector: 'app-register', + standalone: true, + imports: [ + CommonModule, + ReactiveFormsModule, + MatButtonModule, + MatFormFieldModule, + MatInputModule, + MatIconModule, + MatCheckboxModule, + RouterLink, + MatSnackBarModule, + MatAutocompleteModule, + ], + templateUrl: './app-register.component.html', + styleUrl: './app-register.component.scss', +}) +export class AppRegisterComponent implements OnDestroy, OnInit { + private readonly fb = inject(FormBuilder); + protected readonly credentialService = inject(CredentialService); + private readonly router = inject(Router); + private readonly snackBar = inject(MatSnackBar); + private readonly destroyRef = inject(DestroyRef); + private subscription?: Subscription; + private institutionsService = inject(InstitutionsService); + registerForm: FormGroup = this.fb.group({ + username: ['', [Validators.required, Validators.minLength(4)]], + email: ['', [Validators.required, Validators.email]], + password: ['', [Validators.required, Validators.minLength(8)]], + institution: ['', [Validators.required]], + superadmin: [false], + }); + readonly institutionOptions = signal([]); + showPassword = false; + + constructor() { + this.setupInstitutionAutocomplete(); + } + ngOnInit(): void { + this.subscription = this.credentialService.validating.subscribe( + (validating) => { + if (validating) { + this.registerForm.disable(); + } else { + this.registerForm.enable(); + this.checkEnter(); + } + }, + ); + if (!this.credentialService.validating) { + this.checkEnter(); + } + } + ngOnDestroy(): void { + this.subscription?.unsubscribe(); + } + + checkEnter(): void { + if (this.credentialService.authenticated.value) { + this.router.navigate(['/dashboard']); + } + } + submit() { + if (this.registerForm.valid) { + this.credentialService.validating.next(true); + this.registerForm.disable(); + + this.subscription = this.credentialService + .registerAccount(this.registerForm.value) + .subscribe({ + next: () => { + this.credentialService.validating.next(false); + this.snackBar.open( + 'Konto erfolgreich erstellt! Du kannst Dich jetzt anmelden.', + 'OK', + { duration: 5000 }, + ); + this.router.navigate(['/login']); + }, + error: (err) => { + this.credentialService.validating.next(false); + this.registerForm.enable(); + const message = + err.error?.message || + 'Fehler bei der Registrierung. Bitte versuche es später erneut.'; + this.snackBar.open(message, 'Schließen', { + panelClass: ['error-snackbar'], + duration: 5000, + }); + }, + }); + } + } + + private setupInstitutionAutocomplete(): void { + this.registerForm.controls['institution'].valueChanges + .pipe( + debounceTime(250), + map((value) => (typeof value === 'string' ? value.trim() : '')), + distinctUntilChanged(), + switchMap((query) => { + if (query.length < 2) { + this.institutionOptions.set([]); + return of([]); + } + + return this.searchInstitutions(query).pipe( + catchError((ev) => { + console.log(ev); + return of([]); + }), + ); + }), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((options) => { + this.institutionOptions.set(options); + }); + } + + private searchInstitutions(query: string) { + return this.institutionsService + .autocompleteInstitutions(query, undefined, undefined, 10) + .pipe(map((response) => response.results ?? [])); + } + + onInstitutionSelected(event: MatAutocompleteSelectedEvent): void { + const val = event.option.value; + this.registerForm.controls['institution'].setValue(val, { + emitEvent: false, + }); + this.institutionOptions.set([]); + } +} diff --git a/webapp/src/app/modules/person-card/person-card.component.html b/webapp/src/app/modules/person-card/person-card.component.html index 303bd906..43698f60 100644 --- a/webapp/src/app/modules/person-card/person-card.component.html +++ b/webapp/src/app/modules/person-card/person-card.component.html @@ -5,15 +5,7 @@ {{ getInitials(person.display_name) }}
-
- @if (person.relevance_rating) { - - {{ person.relevance_rating }} - - } +
@@ -60,9 +56,12 @@ " >apartment - {{ - inst.display_name ?? '' | truncate: 30 - }} + {{ inst.display_name ?? '' }} @if (inst.country_code && !loading) { {{ inst.country_code.toUpperCase() }} diff --git a/webapp/src/app/modules/person-card/person-card.component.scss b/webapp/src/app/modules/person-card/person-card.component.scss index 02be7ac6..f3a53722 100644 --- a/webapp/src/app/modules/person-card/person-card.component.scss +++ b/webapp/src/app/modules/person-card/person-card.component.scss @@ -108,6 +108,11 @@ font-size: 16px; font-weight: 600; color: var(--sg-text); + min-height: 24px; + line-height: 24px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; } .institution { display: flex; @@ -133,6 +138,26 @@ display: inline-flex; align-items: center; transition: all 0.2s ease; + max-width: 100%; + box-sizing: border-box; + + .institution-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; + flex: 1; + } + + .flag-img { + flex-shrink: 0; + } + + .country-code { + display: inline-block; + flex-shrink: 0; + white-space: nowrap; + } &:hover { background: var(--sg-primary); @@ -143,13 +168,15 @@ .flag-img { border: 1px solid; - vertical-align: -10px; + vertical-align: middle; } .person-id { margin: 2px 0 0; font-size: 10px; color: var(--sg-text-soft); + min-height: 15px; + line-height: 15px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; @@ -159,6 +186,11 @@ margin: 4px 0 0; font-size: 10px; color: var(--sg-text-muted); + min-height: 15px; + line-height: 15px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .card-body { @@ -186,6 +218,11 @@ border-radius: 4px; cursor: pointer; transition: all 0.2s ease; + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + box-sizing: border-box; &:hover { background: var(--sg-primary-soft); diff --git a/webapp/src/app/modules/person-card/person-card.component.ts b/webapp/src/app/modules/person-card/person-card.component.ts index 13e889bd..89f0440c 100644 --- a/webapp/src/app/modules/person-card/person-card.component.ts +++ b/webapp/src/app/modules/person-card/person-card.component.ts @@ -3,18 +3,11 @@ import { CommonModule } from '@angular/common'; import { RouterLink } from '@angular/router'; import { MatIconModule } from '@angular/material/icon'; import { CustomAuthor, DehydratedInstitution, WorkTopic } from '../../api'; -import { TruncatePipe } from '../../shared/pipes/truncate.pipe'; import { SkTextDirective } from '../../custom-directives/sk-text.directive'; @Component({ selector: 'app-person-card', standalone: true, - imports: [ - CommonModule, - RouterLink, - MatIconModule, - TruncatePipe, - SkTextDirective, - ], + imports: [CommonModule, RouterLink, MatIconModule, SkTextDirective], templateUrl: './person-card.component.html', styleUrl: './person-card.component.scss', }) @@ -62,8 +55,11 @@ export class PersonCardComponent { if (topic.field?.display_name) parts.push(topic.field.display_name); if (topic.subfield?.display_name) parts.push(topic.subfield.display_name); - if (parts.length === 0) return topic.display_name || ''; - return parts.join(' - '); + const path = parts.join(' - '); + if (topic.display_name) { + return path ? `${topic.display_name}\n(${path})` : topic.display_name; + } + return path; } getDistinguishingId(person: CustomAuthor): string { @@ -74,6 +70,30 @@ export class PersonCardComponent { return ''; } + getStatsString(): string { + const works = this.person.works_count; + const citations = this.person.cited_by_count; + const hasWorks = works !== undefined && works !== null; + const hasCitations = citations !== undefined && citations !== null; + + if (hasWorks && hasCitations) { + return `Publikationen: ${works} · Zitationen: ${citations}`; + } else if (hasWorks) { + return `Publikationen: ${works}`; + } else if (hasCitations) { + return `Zitationen: ${citations}`; + } + return ''; + } + + getHIndexString(): string { + const hIndex = this.person.summary_stats?.h_index; + if (hIndex !== undefined && hIndex !== null) { + return `h_index: ${hIndex}`; + } + return ''; + } + toggleBookmark(): void { this.bookmarkToggle.emit(this.person); } diff --git a/webapp/src/app/modules/person-funding/person-funding.component.html b/webapp/src/app/modules/person-funding/person-funding.component.html index 8c579e5f..119b3a5a 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.html +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -303,17 +303,6 @@ } } @else {
-
-

- {{ getUniquePublicationCount() }} - Einzigartige Publikationen -

-

- {{ filteredFunders.length }} - Förderer -

-
-
@@ -321,22 +310,30 @@
Filter nach Position: @@ -466,7 +463,44 @@
} @else {
-

Klicke auf einen Förderer für Details.

+
+ @if (activeFilter !== 'all') { + + Filter: {{ getPositionLabel(activeFilter) }} + + } +

Förderübersicht

+

+ @if (activeFilter === 'all') { + Alle geförderten Publikationen dieser Person im Überblick. + } @else { + Nur Publikationen mit der gewählten Autorenposition. + } +

+
+
+ {{ + getUniquePublicationCount() + }} + Einzigartige Publikationen +
+
+ {{ + filteredFunders.length + }} + Förderer +
+
+
+ +

+ Wähle links einen Förderer aus, um die zugehörigen Publikationen + anzuzeigen. +

+
+
}
diff --git a/webapp/src/app/modules/person-funding/person-funding.component.scss b/webapp/src/app/modules/person-funding/person-funding.component.scss index 949d838c..c9bd848e 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.scss +++ b/webapp/src/app/modules/person-funding/person-funding.component.scss @@ -23,38 +23,58 @@ button { padding: 6px 14px; - border: 1px solid #ccc; + border: 1px solid transparent; border-radius: 20px; - background: white; + background: #fff; cursor: pointer; font-size: 14px; + font-weight: 500; - &:hover { - background: #f0f0f0; + &.active { + font-weight: 600; + border-width: 2px; + padding: 5px 13px; } } + button:nth-child(2) { - background: #f0f6ff; - color: #0b63ce; - border-color: #bdd4ff; + color: #3b82c4; + border-color: #c7dcfa; + &.active { + color: #0b4f9e; + background: #e8f2ff; + border-color: #3b82c4; + } } button:nth-child(3) { - background: #effaf3; - color: #24834f; - border-color: #bdebcf; + color: #3d9a66; + border-color: #b8e6cb; + &.active { + color: #1a6b3f; + background: #e8f7ee; + border-color: #3d9a66; + } } button:nth-child(4) { - background: #f6f0ff; - color: #7255d9; - border-color: #d8cafe; + color: #7c65d9; + border-color: #d5c8f8; + &.active { + color: #5b3fc9; + background: #f0ebff; + border-color: #7c65d9; + } } button:nth-child(5) { - background: #fff7e8; - color: #c67500; - border-color: #ffd796; + color: #d1435f; + border-color: #f8c4ce; + &.active { + color: #a61e3a; + background: #ffe8ec; + border-color: #d1435f; + } } } @@ -119,11 +139,6 @@ tr { cursor: pointer; - - &:hover { - background: #f5f5f5; - } - &.selected { background: #f0f0f0; } @@ -152,18 +167,26 @@ display: flex; align-items: center; justify-content: center; - color: #999; - min-height: 200px; + min-height: 280px; + padding: 24px; + background: + radial-gradient( + circle at 100% 0%, + rgba(200, 217, 255, 0.35), + transparent 45% + ), + linear-gradient(160deg, #fff 0%, #f8faff 100%); + border-color: #dbe3f2; } h3 { - margin: 0 0 16px 0; + margin: 0 0 16px; font-size: 16px; color: #333; } h4 { - margin: 16px 0 8px 0; + margin: 16px 0 8px; font-size: 14px; color: #555; } @@ -172,16 +195,13 @@ .position-stats { display: flex; gap: 12px; - margin-bottom: 16px; + margin: 0 auto 16px; width: fit-content; - margin-left: auto; - margin-right: auto; .stat { - flex: 0 auto; min-width: 100px; text-align: center; - background: white; + background: #fff; border: 1px solid #e0e0e0; border-radius: 8px; padding: 10px; @@ -200,20 +220,50 @@ color: #333; } } - .stat-first { - background: #effaf3; - border-color: #bdebcf; - } +} - .stat-middle { - background: #f6f0ff; - border-color: #d8cafe; - } +.stat-first, +.position-badge--first, +.hero-highlight--open, +.publication-detail-grid .access-badge--open { + background: #effaf3; +} - .stat-last { - background: #fff7e8; - border-color: #ffd796; - } +.stat-first { + border-color: #bdebcf; +} + +.position-badge--first { + color: #24834f; + border: 1px solid #bdebcf; +} + +.hero-highlight--open, +.publication-detail-grid .access-badge--open { + border-color: #bdebcf; + color: #24834f; +} + +.stat-middle, +.position-badge--middle { + background: #f6f0ff; + border-color: #d8cafe; +} + +.position-badge--middle { + color: #7255d9; + border: 1px solid #d8cafe; +} + +.stat-last, +.position-badge--last { + background: #fff1f2; + border-color: #fda4af; +} + +.position-badge--last { + color: #be123c; + border: 1px solid #fda4af; } .publication-list { @@ -241,7 +291,7 @@ padding: 4px 10px; border: 1px solid #d0d0d0; border-radius: 6px; - background: white; + background: #fff; cursor: pointer; font-size: 12px; @@ -257,22 +307,87 @@ } } -.funding-summary { - margin-bottom: 16px; +.empty-overview { + width: 100%; + text-align: center; - .summary-line { - margin: 0 0 4px 0; - font-size: 14px; - color: #333; - } - - .summary-label { - color: #333; - } - - .summary-value { + &__filter { + display: inline-block; + margin-bottom: 12px; + padding: 4px 12px; + border: 1px solid #dbe3f2; + border-radius: 999px; + background: rgba(255, 255, 255, 0.9); + color: #475569; + font-size: 0.75rem; font-weight: 600; - color: #333; + text-transform: uppercase; + } + + &__title { + margin: 0 0 8px; + font-size: 1.125rem; + color: #1e3a5f; + } + + &__subtitle { + margin: 0 0 20px; + color: #64748b; + font-size: 0.875rem; + line-height: 1.5; + } + + &__stats { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; + margin-bottom: 20px; + } + + &__stat { + display: flex; + flex-direction: column; + gap: 6px; + padding: 16px 12px; + border: 1px solid #e0e6f0; + border-radius: 10px; + background: rgba(255, 255, 255, 0.85); + } + + &__stat-value { + font-size: 1.75rem; + font-weight: 700; + line-height: 1.1; + color: #1e3a5f; + } + + &__stat-label { + font-size: 0.8rem; + line-height: 1.35; + color: #64748b; + } + + &__hint { + display: flex; + align-items: flex-start; + gap: 10px; + padding: 12px 14px; + border: 1px dashed #c7d5ea; + border-radius: 10px; + background: rgba(255, 255, 255, 0.7); + text-align: left; + + .material-icons { + font-size: 20px; + color: #3b82c4; + } + + p { + margin: 0; + color: #475569; + font-size: 0.875rem; + line-height: 1.45; + } } } @@ -280,15 +395,25 @@ padding: 16px; } -.publication-detail-back { +.publication-detail-back, +.publication-more-info { display: inline-flex; align-items: center; - gap: 6px; border: 0; background: transparent; cursor: pointer; } +.publication-detail-back { + gap: 6px; +} + +.publication-more-info { + gap: 4px; + margin-top: 6px; + padding: 0; +} + .publication-detail-hero { display: flex; justify-content: space-between; @@ -326,7 +451,6 @@ font-size: 0.75rem; font-weight: 700; text-transform: uppercase; - letter-spacing: 0.02em; } } @@ -362,7 +486,6 @@ display: inline-flex; align-items: center; gap: 6px; - flex-shrink: 0; padding: 10px 16px; border: 1px solid #bdd4ff; border-radius: 8px; @@ -371,11 +494,6 @@ font-weight: 600; font-size: 0.875rem; text-decoration: none; - white-space: nowrap; - - &:hover { - background: #e3efff; - } .material-icons { font-size: 18px; @@ -383,21 +501,9 @@ } } -@media (max-width: 720px) { - .publication-detail-hero { - flex-direction: column; - align-items: stretch; - - &__action { - justify-content: center; - } - } -} - .hero-highlight { display: inline-flex; flex-direction: column; - min-width: 72px; padding: 8px 12px; border: 1px solid #e0e6f0; border-radius: 8px; @@ -414,7 +520,6 @@ font-size: 0.7rem; color: #64748b; text-transform: uppercase; - letter-spacing: 0.03em; } &--badge { @@ -426,12 +531,6 @@ color: #475569; } - &--open { - border-color: #bdebcf; - background: #effaf3; - color: #24834f; - } - &--closed { border-color: #e0e6f0; background: #f8fafc; @@ -447,24 +546,6 @@ font-size: 0.8rem; font-weight: 700; - &--first { - background: #effaf3; - color: #24834f; - border: 1px solid #bdebcf; - } - - &--middle { - background: #f6f0ff; - color: #7255d9; - border: 1px solid #d8cafe; - } - - &--last { - background: #fff7e8; - color: #c67500; - border: 1px solid #ffd796; - } - &--unknown { background: #f1f5f9; color: #64748b; @@ -472,179 +553,125 @@ } } -.publication-detail-grid { +$g: '.publication-detail-grid'; + +#{$g} { display: grid; grid-template-columns: minmax(0, 1fr) minmax(280px, 360px); gap: 12px; +} - .publication-detail-main, - .publication-detail-side { - display: grid; - gap: 12px; - min-width: 0; - } +#{$g} .publication-detail-main, +#{$g} .publication-detail-side { + display: grid; + gap: 12px; + min-width: 0; +} - .publication-detail-section { - border: 1px solid #e0e6f0; - border-radius: 10px; - padding: 18px; - background: #fff; +#{$g} .publication-detail-section { + border: 1px solid #e0e6f0; + border-radius: 10px; + padding: 18px; + background: #fff; - h3 { - margin: 0 0 14px; - font-size: 1rem; - color: #1e3a5f; - } - - &--funding { - background: #fafbfd; - } - } - - .publication-overview, - .publication-abstract { - margin: 0; - color: #334155; - line-height: 1.65; - } - - .publication-detail-facts { - display: grid; - gap: 12px; - margin: 0; - - div { - display: grid; - grid-template-columns: 130px minmax(0, 1fr); - gap: 12px; - } - - dt { - color: #64748b; - font-size: 0.875rem; - } - - dd { - margin: 0; - word-break: break-word; - color: #1e293b; - } - } - - .tag-list { - display: flex; - flex-wrap: wrap; - gap: 6px; - margin: 0; - padding: 0; - list-style: none; - - &--compact .tag { - font-size: 0.75rem; - padding: 3px 8px; - } - } - - .tag { - padding: 4px 10px; - border-radius: 999px; - background: #f0f6ff; - border: 1px solid #dbeafe; - color: #1e40af; - font-size: 0.8rem; - line-height: 1.3; - } - - .access-badge { - display: inline-flex; - padding: 4px 10px; - border-radius: 999px; - font-size: 0.8rem; - font-weight: 600; - background: #f1f5f9; - color: #64748b; - - &--open { - background: #effaf3; - color: #24834f; - } - - &--closed { - background: #f8fafc; - color: #475569; - } - } - - .access-actions { - display: flex; - flex-wrap: wrap; - gap: 10px; - align-items: center; - } - - .inline-action { - display: inline-flex; - align-items: center; - gap: 4px; - color: #0b63ce; - font-weight: 600; - font-size: 0.875rem; - text-decoration: none; - - .material-icons { - font-size: 16px; - } - } - - .warning-badge { - display: inline-flex; - padding: 4px 10px; - border-radius: 999px; - background: #fef2f2; - border: 1px solid #fecaca; - color: #b91c1c; - font-size: 0.8rem; - font-weight: 600; - } - - .citation-year-table { - border-collapse: collapse; - - th, - td { - padding: 2px 0; - font-weight: normal; - text-align: left; - vertical-align: top; - } - - th { - padding-right: 20px; - font-weight: 600; - color: #334155; - white-space: nowrap; - } - - td { - color: #1e293b; - } + h3 { + margin: 0 0 14px; + font-size: 1rem; + color: #1e3a5f; } } -@media (max-width: 960px) { - .publication-detail-grid { - grid-template-columns: 1fr; +#{$g} .publication-overview, +#{$g} .publication-abstract { + margin: 0; + color: #334155; + line-height: 1.65; +} + +#{$g} .publication-detail-facts { + display: grid; + gap: 12px; + margin: 0; +} + +#{$g} .publication-detail-facts div { + display: grid; + grid-template-columns: 130px minmax(0, 1fr); + gap: 12px; +} + +#{$g} .publication-detail-facts dt { + color: #64748b; + font-size: 0.875rem; +} + +#{$g} .publication-detail-facts dd { + margin: 0; + word-break: break-word; + color: #1e293b; +} + +#{$g} .tag-list { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin: 0; + padding: 0; + list-style: none; +} + +#{$g} .tag, +#{$g} .access-badge, +#{$g} .warning-badge { + display: inline-flex; + padding: 4px 10px; + border-radius: 999px; + font-size: 0.8rem; +} + +#{$g} .tag { + background: #f0f6ff; + border: 1px solid #dbeafe; + color: #1e40af; + line-height: 1.3; +} + +#{$g} .access-badge { + font-weight: 600; + background: #f1f5f9; + color: #64748b; +} + +#{$g} .access-badge--closed { + background: #f8fafc; + color: #475569; +} + +#{$g} .inline-action { + display: inline-flex; + align-items: center; + gap: 4px; + color: #0b63ce; + font-weight: 600; + font-size: 0.875rem; + text-decoration: none; + + .material-icons { + font-size: 16px; } } +#{$g} .warning-badge { + background: #fef2f2; + border: 1px solid #fecaca; + color: #b91c1c; + font-weight: 600; +} + .publication-item { padding: 8px 0; border-bottom: 2px solid #5b5555; cursor: pointer; - - &:hover { - background: #f9f9f9; - } } .publication-title { @@ -654,30 +681,39 @@ word-break: break-word; display: block; } -.publication-more-info { - display: flex; - align-items: center; - gap: 4px; - margin-top: 6px; - border: 0; - background: transparent; - padding: 0; - cursor: pointer; + +.mehr-infos-label, +.publication-link-icon { + color: #1976d2; } .mehr-infos-label { font-size: 0.8rem; - color: #1976d2; font-weight: 500; } .publication-link-icon { display: flex; align-items: center; - color: #1976d2; - flex-shrink: 0; .material-icons { font-size: 16px; } } + +@media (max-width: 720px) { + .publication-detail-hero { + flex-direction: column; + align-items: stretch; + + &__action { + justify-content: center; + } + } +} + +@media (max-width: 960px) { + #{$g} { + grid-template-columns: 1fr; + } +} diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html index 5376284b..65bf5eae 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html @@ -225,6 +225,10 @@ type="button" class="main-topic-button" [disabled]="!getMainTopicItem(item)?.id" + [matTooltip]="getTopicDescription(getMainTopicItem(item))" + [matTooltipDisabled]=" + !hasTopicDescription(getMainTopicItem(item)) + " (click)=" selectTopic(getMainTopicItem(item), [item.year]) "> @@ -261,8 +265,17 @@ [ngClass]="getColorClass(index)" [disabled]="!topic.id" (click)="selectTopic(topic, [item.year])"> - {{ topic.name }} - {{ topic.count }} + + {{ topic.name }} + + + {{ topic.count }} + @@ -322,6 +335,10 @@ type="button" class="main-topic-button" [disabled]="!phase.primaryTopic.id" + [matTooltip]="getTopicDescription(phase.primaryTopic)" + [matTooltipDisabled]=" + !hasTopicDescription(phase.primaryTopic) + " (click)=" selectTopic(phase.primaryTopic, getPhaseYears(phase)) "> @@ -341,8 +358,17 @@ [ngClass]="getColorClass(index)" [disabled]="!topic.id" (click)="selectTopic(topic, getPhaseYears(phase))"> - {{ topic.name }} - {{ topic.count }} + + {{ topic.name }} + + + {{ topic.count }} + @@ -413,8 +439,15 @@ class="mini-topic-chip" [disabled]="!topic.id" (click)="selectTopic(topic, [year.year])"> - {{ topic.name }} - {{ topic.count }} + + {{ topic.name }} + + + {{ topic.count }} + diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss index 0535e874..e1b43d09 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss @@ -409,7 +409,6 @@ .topic-count { display: inline-flex; - flex: 0 0 auto; align-items: center; justify-content: center; min-width: 18px; @@ -453,7 +452,6 @@ } .phase-marker { - flex: 0 0 auto; width: 11px; height: 11px; margin-top: 5px; @@ -493,7 +491,6 @@ .phase-publications-button { display: inline-flex; - flex: 0 0 auto; width: fit-content; color: #68748f; font-size: 12px; @@ -602,6 +599,9 @@ } strong { + display: inline-flex; + align-items: center; + gap: 2px; color: var(--accent); font-size: 10px; } diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts index 90dfbe9f..43c99ff3 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts @@ -17,6 +17,7 @@ export interface TopicTimelineTopic { id?: string; name: string; count: number; + description?: string; } export interface TopicTimelineElement { @@ -330,6 +331,31 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { ); } + getTopicDescription(topic: TopicTimelineTopic | undefined): string { + return (topic?.description ?? '').trim(); + } + + hasTopicDescription(topic: TopicTimelineTopic | undefined): boolean { + return this.getTopicDescription(topic).length > 0; + } + + getYearTopicCountTooltip( + topic: TopicTimelineTopic, + item: TopicTimelineElement, + ): string { + return this.getTopicCountTooltip(topic, `im Jahr ${item.year}`); + } + + getPhaseTopicCountTooltip( + topic: TopicTimelineTopic, + phase: ResearchTimelinePhase, + ): string { + return this.getTopicCountTooltip( + topic, + this.getPhasePublicationTooltipPeriod(phase), + ); + } + togglePhase(phase: ResearchTimelinePhase): void { if (this.expandedPhaseIds.has(phase.id)) { this.expandedPhaseIds.delete(phase.id); @@ -462,6 +488,17 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { return `Insgesamt ${count} ${publicationLabel} ${period} veröffentlicht.`; } + private getTopicCountTooltip( + topic: TopicTimelineTopic, + period: string, + ): string { + const publicationLabel = + topic.count === 1 ? 'Publikation' : 'Publikationen'; + const verb = topic.count === 1 ? 'hat' : 'haben'; + + return `${topic.count} ${publicationLabel} ${period} ${verb} das Topic ${topic.name}.`; + } + private getPhasePublicationTooltipPeriod( phase: ResearchTimelinePhase, ): string { @@ -608,6 +645,7 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { const primaryTopicName = primaryTopic.name; let count = 0; let id = primaryTopic.id; + let description = primaryTopic.description; for (const year of years) { for (const topic of year.primary_topics ?? []) { @@ -620,6 +658,10 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { if (!id && topic.id) { id = topic.id; } + + if (!description && topic.description) { + description = topic.description; + } } } @@ -627,6 +669,7 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { id, name: primaryTopicName, count: count > 0 ? count : primaryTopic.count, + description, }; } @@ -637,6 +680,7 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { const counts = new Map(); const originalNames = new Map(); const ids = new Map(); + const descriptions = new Map(); for (const year of years) { for (const topic of year.topics ?? []) { @@ -652,6 +696,10 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { ids.set(normalizedName, topic.id); } + if (topic.description) { + descriptions.set(normalizedName, topic.description); + } + counts.set( normalizedName, (counts.get(normalizedName) ?? 0) + topic.count, @@ -664,6 +712,7 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { id: ids.get(normalizedName), name: originalNames.get(normalizedName) ?? normalizedName, count, + description: descriptions.get(normalizedName), })) .sort((left, right) => { if (right.count !== left.count) { diff --git a/webapp/src/app/modules/person-overview/person-overview.component.ts b/webapp/src/app/modules/person-overview/person-overview.component.ts index 5291c82a..57d2275c 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.ts +++ b/webapp/src/app/modules/person-overview/person-overview.component.ts @@ -453,6 +453,7 @@ export class PersonOverviewComponent implements OnInit { id: topic.id ?? undefined, name: topic.name, count: topic.count ?? 0, + description: topic.description ?? undefined, })); } diff --git a/webapp/src/app/shared/interceptors/authentication.interceptor.ts b/webapp/src/app/shared/interceptors/authentication.interceptor.ts index 788ed84a..ac649afd 100644 --- a/webapp/src/app/shared/interceptors/authentication.interceptor.ts +++ b/webapp/src/app/shared/interceptors/authentication.interceptor.ts @@ -5,8 +5,11 @@ import { switchMap, throwError } from 'rxjs'; export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { if ( - req.method == 'POST' && - (req.url.endsWith('/auth/id') || req.url.endsWith('/auth/access')) + (req.method == 'POST' && + (req.url.endsWith('/auth/id') || + req.url.endsWith('/auth/access') || + req.url.endsWith('/inse-account/create'))) || + req.url.endsWith('/institutions/autocomplete') ) { return next(req); } else { diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index 13bf6ad5..a6963764 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -1,14 +1,19 @@ -import { Injectable } from '@angular/core'; -import { HttpClient } from '@angular/common/http'; -//import { BehaviorSubject, Observable, takeWhile } from 'rxjs'; +import { Injectable, inject } from '@angular/core'; import { filter, take, map } from 'rxjs/operators'; //TODO: review by arman import { Observable, of } from 'rxjs'; // review import { BehaviorSubject } from 'rxjs'; //review +import { + INSEAccountServiceService, + IdentityGrant as ApiIdentityGrant, + AccessGrant as ApiAccessGrant, +} from '../../api'; export interface AuthAccount { i: number; l: string; o: number; + e: string; + on: string; } export interface AuthScope { @@ -47,6 +52,8 @@ interface TimedAccessGrant { providedIn: 'root', }) export class CredentialService { + private accountService = inject(INSEAccountServiceService); + private static readonly KEY_GRANT = 'grant'; public readonly validating = new BehaviorSubject(false); @@ -57,6 +64,8 @@ export class CredentialService { undefined, ); public readonly login = new BehaviorSubject(''); + public readonly email = new BehaviorSubject(''); + public readonly organizationName = new BehaviorSubject(''); private readonly identityToken = new BehaviorSubject< TimedIdentityGrant | undefined @@ -67,17 +76,21 @@ export class CredentialService { private request = 0; - constructor(private http: HttpClient) { + constructor() { this.accessToken.subscribe((token) => { if (token) { const r = token.grant.scope.r as string[]; this.superadmin.next(r.includes('SUPER_ADMIN')); this.universityadmin.next(r.includes('UNI_ADMIN')); this.login.next(token.grant.scope.a?.l ?? ''); + this.email.next(token.grant.scope.a?.e ?? ''); + this.organizationName.next(token.grant.scope.a?.on ?? ''); } else { this.superadmin.next(false); this.universityadmin.next(false); this.login.next(''); + this.email.next(''); + this.organizationName.next(''); } }); const data = localStorage.getItem(CredentialService.KEY_GRANT); @@ -104,29 +117,25 @@ export class CredentialService { body.set('username', login); body.set('password', password); - this.http - .post('/inse-account/auth/id', body.toString(), { - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - }) - .subscribe({ - next: (result) => { - if (this.request != request) return; - const token = { - grant: result, - expiration: result.expires_in * 1000 + now, - }; - this.identityToken.next(token); - localStorage.setItem( - CredentialService.KEY_GRANT, - JSON.stringify(token), - ); - this.refreshAccessToken(token); - }, - error: () => { - if (this.request != request) return; - this.validating.next(false); - }, - }); + this.accountService.getIdentityGrant(login, password).subscribe({ + next: (result) => { + if (this.request != request) return; + const token: TimedIdentityGrant = { + grant: result as any as IdentityGrant, + expiration: result.expires_in * 1000 + now, + }; + this.identityToken.next(token); + localStorage.setItem( + CredentialService.KEY_GRANT, + JSON.stringify(token), + ); + this.refreshAccessToken(token); + }, + error: () => { + if (this.request != request) return; + this.validating.next(false); + }, + }); } public refreshAccessToken(identityToken: TimedIdentityGrant) { @@ -137,20 +146,13 @@ export class CredentialService { const uid = identityToken.grant.scope.a!.i; const org = identityToken.grant.scope.a!.o; - const body = new URLSearchParams(); - body.set('secret', identityToken.grant.access_token); - body.set('account', uid.toString()); - body.set('organization', org.toString()); - - this.http - .post('/inse-account/auth/access', body.toString(), { - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - }) + this.accountService + .getAccessGrant(identityToken.grant.access_token, uid, org) .subscribe({ next: (result) => { if (this.request != request) return; - const token = { - grant: result, + const token: TimedAccessGrant = { + grant: result as any as AccessGrant, expiration: result.expires_in * 1000 + now, }; this.accessToken.next(token); @@ -182,6 +184,10 @@ export class CredentialService { this.validating.next(false); } + public registerAccount(data: any): Observable { + return this.accountService.createUser(data); + } + //review: arman (generated fix) public getBearerToken(): Observable { // 1. If we have a valid access token, return it immediately and complete. diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.html b/webapp/src/app/shared/ui/app-layout/app-layout.component.html index 1c3a8d9b..6de5f1f4 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.html +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.html @@ -15,45 +15,51 @@ } - -
- @if ( - mediaQuery.matches && (credentialService.authenticated | async) - ) { - + } + - } - -
- -
- -
-
+
+ +
+ +
+ + }
- @if (resolverState.isResolvingFromOutside('/persons')) { - - } @else if (resolverState.isResolvingFromOutside('/person/')) { - - } @else { - - } +
+ @if (resolverState.isResolvingFromOutside('/persons')) { + + } @else if (resolverState.isResolvingFromOutside('/person/')) { + + } @else { + + } +
+ +
+ +
diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.scss b/webapp/src/app/shared/ui/app-layout/app-layout.component.scss index 8311f123..6556c59f 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.scss +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.scss @@ -18,7 +18,10 @@ } .content-shell { - min-height: 100%; + display: flex; + flex-direction: column; + height: 100%; + overflow: hidden; background: var(--sg-background); } @@ -34,10 +37,9 @@ mat-toolbar.main { gap: 24px; height: 76px; padding: 0 32px; - background: rgba(255, 255, 255, 0.92); + background: var(--sg-surface-soft); border-bottom: 1px solid var(--sg-border); color: var(--sg-text); - backdrop-filter: blur(16px); box-shadow: none; } @@ -82,10 +84,30 @@ mat-toolbar.main { } .content { - min-height: calc(100svh - 76px); + display: flex; + flex-direction: column; + flex: 1; + overflow-y: auto; background: var(--sg-background); } +.main-content-body { + flex: 1; +} + +.footer-container { + flex-shrink: 0; + padding: 12px 32px; + background: var(--sg-surface-soft); + border-top: 1px solid var(--sg-border); +} + +.footer { + font-size: 12px; + color: var(--sg-text-muted); + text-align: center; +} + @media (max-width: 900px) { mat-toolbar.main { grid-template-columns: auto 1fr auto; @@ -115,7 +137,7 @@ mat-toolbar.main { } .content { - min-height: calc(100svh - 124px); + min-height: 0; } } .search-wrapper { diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.html b/webapp/src/app/shared/ui/app-menu/app-menu.component.html index 942b7cbd..5c43bd85 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.html +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.html @@ -37,21 +37,19 @@