added direct hierarchy editing by manager + accepting/rejecting hierarchy suggestions
This commit is contained in:
@@ -81,6 +81,17 @@ def _migrate_secret_table():
|
||||
def create_db_and_tables():
|
||||
"""Creates the database and tables based on the SQLModel metadata."""
|
||||
SQLModel.metadata.create_all(engine)
|
||||
hierarchy_edit_columns = {
|
||||
column["name"] for column in inspect(engine).get_columns("hierarchy_edits")
|
||||
}
|
||||
if "status" not in hierarchy_edit_columns:
|
||||
with engine.begin() as connection:
|
||||
connection.execute(
|
||||
text(
|
||||
"ALTER TABLE hierarchy_edits ADD COLUMN status "
|
||||
"VARCHAR NOT NULL DEFAULT 'new'"
|
||||
)
|
||||
)
|
||||
_migrate_secret_table()
|
||||
columns = {column["name"] for column in inspect(engine).get_columns("account")}
|
||||
if "activated" not in columns:
|
||||
|
||||
@@ -12,29 +12,31 @@ from starlette.responses import Response
|
||||
# organization must never be reused by the browser.
|
||||
NO_STORE_PATH_PREFIXES = (
|
||||
"/api/auth/v2",
|
||||
"/api/accounts",
|
||||
"/api/background-jobs",
|
||||
"/api/bookmarks",
|
||||
"/api/organizations",
|
||||
)
|
||||
|
||||
# Keep these responses in the server-side ETag cache, but require the browser
|
||||
# to revalidate them. A new access token (for example after impersonation)
|
||||
# automatically produces a different cache key.
|
||||
REVALIDATE_PATH_PREFIXES = (
|
||||
"/api/dashboard",
|
||||
"/api/rank/orientation-profiles",
|
||||
"/api/works/v2/classification/",
|
||||
)
|
||||
|
||||
REVALIDATE_PATH_FRAGMENTS = (
|
||||
"/company-connections",
|
||||
"/primary-category-aggregations",
|
||||
)
|
||||
|
||||
NO_STORE_PATH_FRAGMENTS = (
|
||||
"/collaboration-graph/",
|
||||
)
|
||||
"/api/accounts",
|
||||
"/api/background-jobs",
|
||||
"/api/bookmarks",
|
||||
"/api/organizations",
|
||||
"/api/orgminer/get-hierarchy",
|
||||
"api/orgminer/hierarchy-suggestions",
|
||||
)
|
||||
|
||||
# Keep these responses in the server-side ETag cache, but require the browser
|
||||
# to revalidate them. A new access token (for example after impersonation)
|
||||
# automatically produces a different cache key.
|
||||
REVALIDATE_PATH_PREFIXES = (
|
||||
"/api/dashboard",
|
||||
"/api/rank/orientation-profiles",
|
||||
"/api/works/v2/classification/",
|
||||
)
|
||||
|
||||
REVALIDATE_PATH_FRAGMENTS = (
|
||||
"/company-connections",
|
||||
"/primary-category-aggregations",
|
||||
)
|
||||
|
||||
NO_STORE_PATH_FRAGMENTS = (
|
||||
"/collaboration-graph/",
|
||||
)
|
||||
# POST is opt-out. Add any endpoint here that MUTATES state (create/update/delete/
|
||||
# trigger side effects), even if it "usually" returns 200.
|
||||
EXCLUDED_POST_PATHS = (
|
||||
@@ -104,17 +106,17 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
|
||||
def _content_type(self, response: Response) -> str | None:
|
||||
return response.headers.get("content-type")
|
||||
|
||||
def _requires_no_store(self, request: Request) -> bool:
|
||||
path = request.url.path
|
||||
return path.startswith(NO_STORE_PATH_PREFIXES) or any(
|
||||
fragment in path for fragment in NO_STORE_PATH_FRAGMENTS
|
||||
)
|
||||
|
||||
def _requires_revalidation(self, request: Request) -> bool:
|
||||
path = request.url.path
|
||||
return path.startswith(REVALIDATE_PATH_PREFIXES) or any(
|
||||
fragment in path for fragment in REVALIDATE_PATH_FRAGMENTS
|
||||
)
|
||||
def _requires_no_store(self, request: Request) -> bool:
|
||||
path = request.url.path
|
||||
return path.startswith(NO_STORE_PATH_PREFIXES) or any(
|
||||
fragment in path for fragment in NO_STORE_PATH_FRAGMENTS
|
||||
)
|
||||
|
||||
def _requires_revalidation(self, request: Request) -> bool:
|
||||
path = request.url.path
|
||||
return path.startswith(REVALIDATE_PATH_PREFIXES) or any(
|
||||
fragment in path for fragment in REVALIDATE_PATH_FRAGMENTS
|
||||
)
|
||||
|
||||
def _set_no_store_headers(self, response: Response) -> None:
|
||||
response.headers["Cache-Control"] = "private, no-store, max-age=0"
|
||||
@@ -133,14 +135,14 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
|
||||
vary_values.append("Authorization")
|
||||
headers["Vary"] = ", ".join(vary_values)
|
||||
|
||||
def _cache_response_headers(
|
||||
self, request: Request, etag: str, content_type: str | None
|
||||
) -> dict[str, str]:
|
||||
cache_control = (
|
||||
"no-cache, max-age=0"
|
||||
if self._requires_revalidation(request)
|
||||
else f"max-age={self.ttl}"
|
||||
)
|
||||
def _cache_response_headers(
|
||||
self, request: Request, etag: str, content_type: str | None
|
||||
) -> dict[str, str]:
|
||||
cache_control = (
|
||||
"no-cache, max-age=0"
|
||||
if self._requires_revalidation(request)
|
||||
else f"max-age={self.ttl}"
|
||||
)
|
||||
headers = {"ETag": etag, "Cache-Control": cache_control}
|
||||
if request.headers.get("authorization"):
|
||||
headers["Cache-Control"] = f"private, {cache_control}"
|
||||
|
||||
@@ -7,7 +7,7 @@ from inse.middleware.etag_cache import ETagCacheMiddleware
|
||||
|
||||
def _app_with_counter():
|
||||
app = FastAPI()
|
||||
calls = {"get": 0, "post": 0, "dashboard": 0, "read_only": 0}
|
||||
calls = {"get": 0, "post": 0, "dashboard": 0, "read_only": 0, "hierarchy": 0}
|
||||
|
||||
@app.get("/api/background-jobs/tasks")
|
||||
def get_tasks():
|
||||
@@ -24,6 +24,11 @@ def _app_with_counter():
|
||||
calls["dashboard"] += 1
|
||||
return {"call": calls["dashboard"]}
|
||||
|
||||
@app.get("/api/orgminer/get-hierarchy")
|
||||
def get_hierarchy():
|
||||
calls["hierarchy"] += 1
|
||||
return {"call": calls["hierarchy"]}
|
||||
|
||||
def read_only_response():
|
||||
calls["read_only"] += 1
|
||||
return {"call": calls["read_only"]}
|
||||
@@ -84,6 +89,23 @@ def test_background_job_post_side_effects_are_never_replayed_from_cache():
|
||||
assert calls["post"] == 2
|
||||
|
||||
|
||||
def test_hierarchy_gets_are_never_cached_after_updates():
|
||||
app, calls = _app_with_counter()
|
||||
|
||||
with TestClient(app) as client:
|
||||
first = client.get("/api/orgminer/get-hierarchy")
|
||||
second = client.get(
|
||||
"/api/orgminer/get-hierarchy",
|
||||
headers={"If-None-Match": first.headers.get("etag", "")},
|
||||
)
|
||||
|
||||
assert first.status_code == 200
|
||||
assert second.status_code == 200
|
||||
assert first.headers["cache-control"] == "private, no-store, max-age=0"
|
||||
assert second.json() == {"call": 2}
|
||||
assert calls["hierarchy"] == 2
|
||||
|
||||
|
||||
def test_dashboard_revalidates_and_uses_a_separate_cache_for_a_new_token():
|
||||
app, calls = _app_with_counter()
|
||||
|
||||
|
||||
@@ -7,9 +7,19 @@ from inse.integrations.elasticsearch import search
|
||||
from inse.utils import normalize_name
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.authors.v2.service import _build_collaboration_graph
|
||||
from .model import OrgminerContent, ClassifiedPage,ClassifiedPageResponse, CategoryBucket, HierarchyNode, SaveHierarchyResponse
|
||||
from .model import (
|
||||
OrgminerContent,
|
||||
ClassifiedPage,
|
||||
ClassifiedPageResponse,
|
||||
CategoryBucket,
|
||||
HierarchyNode,
|
||||
HierarchySuggestion,
|
||||
SaveHierarchyResponse,
|
||||
)
|
||||
import json
|
||||
import uuid
|
||||
import os
|
||||
import tempfile
|
||||
from inse.orgminer.model import EditHierarchySuggestion
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
@@ -211,17 +221,26 @@ async def find_org_for_person(
|
||||
|
||||
return best_org
|
||||
|
||||
async def get_hierarchy(institution_id: str) -> list[HierarchyNode]:
|
||||
HIERARCHIES_DIR = Path(__file__).resolve().parents[3] / "data" / "hierarchies"
|
||||
|
||||
|
||||
def _hierarchy_path(institution_id: str) -> Path:
|
||||
institution_short_id = institution_id.rstrip("/").rsplit("/", 1)[-1]
|
||||
return HIERARCHIES_DIR / institution_short_id / "hierarchy.json"
|
||||
|
||||
|
||||
async def get_hierarchy(institution_id: str) -> list[HierarchyNode]:
|
||||
"""
|
||||
Returns the hierarchy of organizations.
|
||||
"""
|
||||
faculties = json.load(open(f'../../data/hierarchies/{institution_id}/hierarchy.json', 'r'))
|
||||
with _hierarchy_path(institution_id).open(encoding="utf-8") as hierarchy_file:
|
||||
faculties = json.load(hierarchy_file)
|
||||
return [HierarchyNode(**node) for node in faculties]
|
||||
|
||||
|
||||
|
||||
MAX_PER_DAY = 3
|
||||
SUGGESTIONS_DIR = Path("../../data/hierarchies/suggestions")
|
||||
SUGGESTIONS_DIR = HIERARCHIES_DIR / "suggestions"
|
||||
|
||||
|
||||
class DailyLimitExceeded(Exception):
|
||||
@@ -300,6 +319,139 @@ def save_hierarchy(
|
||||
remaining_today=remaining_today,
|
||||
)
|
||||
|
||||
|
||||
def update_hierarchy(
|
||||
hierarchy_data: list[HierarchyNode | dict[str, Any]],
|
||||
openalex_id: str,
|
||||
) -> SaveHierarchyResponse:
|
||||
"""Replace the active hierarchy with a manager-approved edit."""
|
||||
hierarchy_path = _hierarchy_path(openalex_id)
|
||||
hierarchy_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def normalize_node(
|
||||
node: HierarchyNode | dict[str, Any],
|
||||
) -> dict[str, Any] | None:
|
||||
normalized = (
|
||||
node.model_dump(mode="json") if isinstance(node, HierarchyNode) else dict(node)
|
||||
)
|
||||
if normalized.get("modified") == "deleted":
|
||||
return None
|
||||
|
||||
if normalized.get("modified") in {"created", "updated", "changed"}:
|
||||
normalized.pop("modified")
|
||||
|
||||
children = normalized.get("children")
|
||||
if children is not None:
|
||||
normalized["children"] = [
|
||||
child
|
||||
for raw_child in children
|
||||
if (child := normalize_node(raw_child)) is not None
|
||||
]
|
||||
return normalized
|
||||
|
||||
normalized_hierarchy = [
|
||||
node
|
||||
for raw_node in hierarchy_data
|
||||
if (node := normalize_node(raw_node)) is not None
|
||||
]
|
||||
|
||||
temporary_path: str | None = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(
|
||||
mode="w",
|
||||
encoding="utf-8",
|
||||
dir=hierarchy_path.parent,
|
||||
prefix=".hierarchy-",
|
||||
suffix=".json.tmp",
|
||||
delete=False,
|
||||
) as hierarchy_file:
|
||||
temporary_path = hierarchy_file.name
|
||||
json.dump(normalized_hierarchy, hierarchy_file)
|
||||
hierarchy_file.flush()
|
||||
os.fsync(hierarchy_file.fileno())
|
||||
os.replace(temporary_path, hierarchy_path)
|
||||
except Exception:
|
||||
if temporary_path:
|
||||
Path(temporary_path).unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
return SaveHierarchyResponse(
|
||||
message="Hierarchy updated successfully.",
|
||||
remaining_today=0,
|
||||
)
|
||||
|
||||
|
||||
def get_hierarchy_suggestions(
|
||||
session: Session,
|
||||
openalex_id: str,
|
||||
) -> list[HierarchySuggestion]:
|
||||
"""Return saved user suggestions for the manager's institution."""
|
||||
suggestions = session.exec(
|
||||
select(EditHierarchySuggestion)
|
||||
.where(
|
||||
EditHierarchySuggestion.organization_openalex_id == openalex_id,
|
||||
EditHierarchySuggestion.status == "new",
|
||||
)
|
||||
.order_by(EditHierarchySuggestion.created_at.desc())
|
||||
).all()
|
||||
|
||||
result: list[HierarchySuggestion] = []
|
||||
for suggestion in suggestions:
|
||||
with open(suggestion.file_path, encoding="utf-8") as suggestion_file:
|
||||
hierarchy = json.load(suggestion_file)
|
||||
result.append(
|
||||
HierarchySuggestion(
|
||||
id=suggestion.id,
|
||||
created_at=suggestion.created_at,
|
||||
status=suggestion.status,
|
||||
hierarchy=[HierarchyNode(**node) for node in hierarchy],
|
||||
)
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def accept_hierarchy_suggestion(
|
||||
session: Session,
|
||||
suggestion_id: uuid.UUID,
|
||||
openalex_id: str,
|
||||
hierarchy_data: list[HierarchyNode | dict[str, Any]] | None = None,
|
||||
) -> SaveHierarchyResponse:
|
||||
suggestion = session.get(EditHierarchySuggestion, suggestion_id)
|
||||
if (
|
||||
suggestion is None
|
||||
or suggestion.organization_openalex_id != openalex_id
|
||||
or suggestion.status != "new"
|
||||
):
|
||||
raise ValueError("Hierarchy suggestion is not available.")
|
||||
|
||||
if hierarchy_data is None:
|
||||
with open(suggestion.file_path, encoding="utf-8") as suggestion_file:
|
||||
hierarchy_data = json.load(suggestion_file)
|
||||
|
||||
response = update_hierarchy(hierarchy_data, openalex_id)
|
||||
suggestion.status = "accepted"
|
||||
session.add(suggestion)
|
||||
session.commit()
|
||||
return response
|
||||
|
||||
|
||||
def reject_hierarchy_suggestion(
|
||||
session: Session,
|
||||
suggestion_id: uuid.UUID,
|
||||
openalex_id: str,
|
||||
) -> None:
|
||||
suggestion = session.get(EditHierarchySuggestion, suggestion_id)
|
||||
if (
|
||||
suggestion is None
|
||||
or suggestion.organization_openalex_id != openalex_id
|
||||
or suggestion.status != "new"
|
||||
):
|
||||
raise ValueError("Hierarchy suggestion is not available.")
|
||||
suggestion.status = "rejected"
|
||||
session.add(suggestion)
|
||||
session.commit()
|
||||
|
||||
|
||||
def get_number_of_suggestion_slots_today(session: Session, effective_account_id: uuid.UUID) -> int:
|
||||
today = datetime.now(timezone.utc).date()
|
||||
return MAX_PER_DAY -session.exec(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from typing import Any, List, Optional
|
||||
from typing import Any, List, Optional, Literal
|
||||
from enum import StrEnum
|
||||
import uuid
|
||||
from pydantic import BaseModel, Field, ConfigDict
|
||||
@@ -6,6 +6,8 @@ from datetime import datetime, timezone, date
|
||||
from sqlalchemy import UniqueConstraint, DateTime, CheckConstraint
|
||||
from sqlmodel import Field, SQLModel
|
||||
# Orgminer content models
|
||||
ModifiedOption = Literal["created", "updated", "deleted", ""]
|
||||
HierarchySuggestionStatus = Literal["new", "accepted", "rejected"]
|
||||
|
||||
class HierarchyNode(BaseModel):
|
||||
name_de: str
|
||||
@@ -15,6 +17,7 @@ class HierarchyNode(BaseModel):
|
||||
faculty_de: str | None = None
|
||||
faculty_en: str | None = None
|
||||
type:str
|
||||
modified: ModifiedOption | None = None
|
||||
value: int | None = None
|
||||
children: list["HierarchyNode"] | None = None
|
||||
model_config = {"extra": "allow"}
|
||||
@@ -22,11 +25,19 @@ class HierarchyNode(BaseModel):
|
||||
class HierarchyResponse(BaseModel):
|
||||
hierarchy: list[HierarchyNode]
|
||||
can_edit: bool = False
|
||||
can_suggest: bool = True
|
||||
number_of_suggestion_slots: int = 0
|
||||
|
||||
class SaveHierarchyResponse(BaseModel):
|
||||
message:str
|
||||
remaining_today:int
|
||||
|
||||
|
||||
class HierarchySuggestion(BaseModel):
|
||||
id: uuid.UUID
|
||||
created_at: datetime
|
||||
status: HierarchySuggestionStatus
|
||||
hierarchy: list[HierarchyNode]
|
||||
|
||||
class OrgminerKeyword(BaseModel):
|
||||
score: Optional[float] = None
|
||||
@@ -202,6 +213,7 @@ class EditHierarchySuggestion(SQLModel, table=True):
|
||||
day: date = Field(nullable=False)
|
||||
slot: int = Field(nullable=False)
|
||||
file_path: str = Field(nullable=False)
|
||||
status: str = Field(default="new", nullable=False, index=True)
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("account_id", "day", "slot", name="uq_suggestion_account_day_slot"),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from typing import Annotated
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
from inse.database import SessionDep
|
||||
@@ -6,7 +7,14 @@ from inse.tags import Tags
|
||||
from inse.auth.model import AccessTokenMetadata, Organization, UserRole
|
||||
from inse.auth.service import CurrentUserAccessTokenPayloadDep, _get_account_institution_id, _get_account_organization, _get_account_roles
|
||||
from . import logic
|
||||
from .model import OrgminerContent, ClassifiedPageResponse, CategoryBucket, HierarchyResponse, SaveHierarchyResponse
|
||||
from .model import (
|
||||
OrgminerContent,
|
||||
ClassifiedPageResponse,
|
||||
CategoryBucket,
|
||||
HierarchyResponse,
|
||||
HierarchySuggestion,
|
||||
SaveHierarchyResponse,
|
||||
)
|
||||
from inse.orgminer.institutions_helper import DEFAULT_INSTITUTION_ID, full_institution_url
|
||||
import logging
|
||||
from fastapi import HTTPException
|
||||
@@ -71,16 +79,103 @@ async def get_hierarchy(
|
||||
status_code=400,
|
||||
detail="Account does not have an associated organization with a valid OpenAlex institution ID.",
|
||||
)
|
||||
can_edit = UserRole.MANAGER in _get_account_roles(session, access_token_metadata.effective_account_id)
|
||||
number_of_suggestion_slots = logic.get_number_of_suggestion_slots_today(session, access_token_metadata.effective_account_id)
|
||||
is_manager = UserRole.MANAGER in _get_account_roles(
|
||||
session, access_token_metadata.effective_account_id
|
||||
)
|
||||
number_of_suggestion_slots = logic.get_number_of_suggestion_slots_today(
|
||||
session, access_token_metadata.effective_account_id
|
||||
)
|
||||
hierarchy = await logic.get_hierarchy(institution_id)
|
||||
return HierarchyResponse(hierarchy=hierarchy, can_edit=can_edit, number_of_suggestion_slots=number_of_suggestion_slots)
|
||||
return HierarchyResponse(
|
||||
hierarchy=hierarchy,
|
||||
can_edit=is_manager,
|
||||
can_suggest=not is_manager,
|
||||
number_of_suggestion_slots=number_of_suggestion_slots,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/hierarchy-suggestions",
|
||||
operation_id="getHierarchySuggestions",
|
||||
response_model=list[HierarchySuggestion],
|
||||
summary="Returns hierarchy suggestions for managers.",
|
||||
tags=[Tags.ORGMINER],
|
||||
)
|
||||
def get_hierarchy_suggestions(
|
||||
session: SessionDep,
|
||||
access_token_metadata: Annotated[
|
||||
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
|
||||
],
|
||||
) -> list[HierarchySuggestion]:
|
||||
account_id = access_token_metadata.effective_account_id
|
||||
if UserRole.MANAGER not in _get_account_roles(session, account_id):
|
||||
raise HTTPException(status_code=403, detail="Only managers can review hierarchy suggestions.")
|
||||
|
||||
institution_id = _get_account_institution_id(session, account_id)
|
||||
if not institution_id:
|
||||
raise HTTPException(status_code=400, detail="Account has no associated institution.")
|
||||
return logic.get_hierarchy_suggestions(session, institution_id)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/hierarchy-suggestions/{suggestion_id}/accept",
|
||||
operation_id="acceptHierarchySuggestion",
|
||||
response_model=SaveHierarchyResponse,
|
||||
tags=[Tags.ORGMINER],
|
||||
)
|
||||
def accept_hierarchy_suggestion(
|
||||
suggestion_id: uuid.UUID,
|
||||
hierarchy_data: list[dict],
|
||||
session: SessionDep,
|
||||
access_token_metadata: Annotated[
|
||||
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
|
||||
],
|
||||
) -> SaveHierarchyResponse:
|
||||
account_id = access_token_metadata.effective_account_id
|
||||
if UserRole.MANAGER not in _get_account_roles(session, account_id):
|
||||
raise HTTPException(status_code=403, detail="Only managers can accept hierarchy suggestions.")
|
||||
institution_id = _get_account_institution_id(session, account_id)
|
||||
if not institution_id:
|
||||
raise HTTPException(status_code=400, detail="Account has no associated institution.")
|
||||
try:
|
||||
return logic.accept_hierarchy_suggestion(
|
||||
session, suggestion_id, institution_id, hierarchy_data
|
||||
)
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=404, detail=str(error)) from error
|
||||
|
||||
|
||||
@router.post(
|
||||
"/hierarchy-suggestions/{suggestion_id}/reject",
|
||||
operation_id="rejectHierarchySuggestion",
|
||||
response_model=dict,
|
||||
tags=[Tags.ORGMINER],
|
||||
)
|
||||
def reject_hierarchy_suggestion(
|
||||
suggestion_id: uuid.UUID,
|
||||
session: SessionDep,
|
||||
access_token_metadata: Annotated[
|
||||
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
|
||||
],
|
||||
) -> dict[str, str]:
|
||||
account_id = access_token_metadata.effective_account_id
|
||||
if UserRole.MANAGER not in _get_account_roles(session, account_id):
|
||||
raise HTTPException(status_code=403, detail="Only managers can reject hierarchy suggestions.")
|
||||
institution_id = _get_account_institution_id(session, account_id)
|
||||
if not institution_id:
|
||||
raise HTTPException(status_code=400, detail="Account has no associated institution.")
|
||||
try:
|
||||
logic.reject_hierarchy_suggestion(session, suggestion_id, institution_id)
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=404, detail=str(error)) from error
|
||||
return {"message": "Hierarchy suggestion rejected."}
|
||||
|
||||
|
||||
@router.post(
|
||||
"/save-hierarchy",
|
||||
operation_id="saveHierarchy",
|
||||
response_model=SaveHierarchyResponse,
|
||||
summary="Saves the hierarchy of organizations.",
|
||||
summary="Submits a suggestion or, for managers, updates the active hierarchy.",
|
||||
tags=[Tags.ORGMINER],
|
||||
responses={429: {"description": "Daily suggestion limit reached"}, 400: {"description": "Account does not have an associated organization with a valid OpenAlex institution ID."}},
|
||||
)
|
||||
@@ -92,7 +187,8 @@ def save_hierarchy(
|
||||
],
|
||||
) -> SaveHierarchyResponse:
|
||||
"""
|
||||
Saves the hierarchy of organizations (max. 3 suggestions per account and day).
|
||||
Users submit suggestions (max. 3 per account and day); managers update the
|
||||
active hierarchy.
|
||||
"""
|
||||
account_id = access_token_metadata.effective_account_id
|
||||
|
||||
@@ -107,6 +203,12 @@ def save_hierarchy(
|
||||
)
|
||||
|
||||
try:
|
||||
is_manager = UserRole.MANAGER in _get_account_roles(session, account_id)
|
||||
if is_manager:
|
||||
return logic.update_hierarchy(
|
||||
hierarchy_data,
|
||||
openalex_id=organization.openalex_institution_id,
|
||||
)
|
||||
return logic.save_hierarchy(
|
||||
session,
|
||||
hierarchy_data,
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import json
|
||||
|
||||
from inse.orgminer import logic
|
||||
|
||||
|
||||
def test_update_hierarchy_removes_deleted_nodes_and_edit_markers(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(logic, "HIERARCHIES_DIR", tmp_path)
|
||||
|
||||
logic.update_hierarchy(
|
||||
[
|
||||
{
|
||||
"name_de": "Keep",
|
||||
"type": "faculty",
|
||||
"modified": "updated",
|
||||
"children": [
|
||||
{
|
||||
"name_de": "Created",
|
||||
"type": "leaf",
|
||||
"modified": "created",
|
||||
},
|
||||
{
|
||||
"name_de": "Changed",
|
||||
"type": "leaf",
|
||||
"modified": "changed",
|
||||
},
|
||||
{
|
||||
"name_de": "Deleted",
|
||||
"type": "leaf",
|
||||
"modified": "deleted",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
"name_de": "Deleted parent",
|
||||
"type": "faculty",
|
||||
"modified": "deleted",
|
||||
"children": [
|
||||
{
|
||||
"name_de": "Also deleted",
|
||||
"type": "leaf",
|
||||
}
|
||||
],
|
||||
},
|
||||
],
|
||||
openalex_id="I123",
|
||||
)
|
||||
|
||||
with (tmp_path / "I123" / "hierarchy.json").open(encoding="utf-8") as hierarchy_file:
|
||||
saved_hierarchy = json.load(hierarchy_file)
|
||||
|
||||
assert saved_hierarchy == [
|
||||
{
|
||||
"name_de": "Keep",
|
||||
"type": "faculty",
|
||||
"children": [
|
||||
{"name_de": "Created", "type": "leaf"},
|
||||
{"name_de": "Changed", "type": "leaf"},
|
||||
],
|
||||
}
|
||||
]
|
||||
@@ -6,6 +6,7 @@ from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from inse.auth.service import _get_current_user_access_token_payload
|
||||
from inse.auth.model import UserRole
|
||||
from inse.database import get_session
|
||||
from inse.orgminer import service
|
||||
|
||||
@@ -89,6 +90,7 @@ def test_get_hierarchy_returns_logic_result(orgminer_client, institution_lookup,
|
||||
"link_en": None,
|
||||
"faculty_de": None,
|
||||
"faculty_en": None,
|
||||
"modified": None,
|
||||
"type": "faculty",
|
||||
"value": None,
|
||||
"children": None,
|
||||
@@ -115,6 +117,7 @@ def test_save_hierarchy_forwards_hierarchy_and_organization(
|
||||
"_get_account_organization",
|
||||
lambda session, account_id: organization_id,
|
||||
)
|
||||
monkeypatch.setattr(service, "_get_account_roles", lambda session, account_id: [UserRole.USER])
|
||||
calls = []
|
||||
|
||||
def save_hierarchy(session, hierarchy_data, **kwargs):
|
||||
@@ -174,6 +177,7 @@ def test_save_hierarchy_returns_too_many_requests_when_daily_limit_is_reached(
|
||||
"_get_account_organization",
|
||||
lambda session, account_id: organization_id,
|
||||
)
|
||||
monkeypatch.setattr(service, "_get_account_roles", lambda session, account_id: [UserRole.USER])
|
||||
def save_hierarchy(*args, **kwargs):
|
||||
raise service.logic.DailyLimitExceeded()
|
||||
|
||||
@@ -190,6 +194,48 @@ def test_save_hierarchy_returns_too_many_requests_when_daily_limit_is_reached(
|
||||
}
|
||||
|
||||
|
||||
def test_manager_save_hierarchy_updates_active_hierarchy(
|
||||
orgminer_client, monkeypatch
|
||||
):
|
||||
organization_id = UUID("00000000-0000-0000-0000-000000000002")
|
||||
organization = SimpleNamespace(
|
||||
id=organization_id,
|
||||
openalex_institution_id=INSTITUTION_ID,
|
||||
)
|
||||
session = SimpleNamespace(get=lambda model, identifier: organization)
|
||||
orgminer_client.app.dependency_overrides[get_session] = lambda: session
|
||||
monkeypatch.setattr(
|
||||
service,
|
||||
"_get_account_organization",
|
||||
lambda session, account_id: organization_id,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
service, "_get_account_roles", lambda session, account_id: [UserRole.MANAGER]
|
||||
)
|
||||
calls = []
|
||||
|
||||
def update_hierarchy(hierarchy_data, **kwargs):
|
||||
calls.append((hierarchy_data, kwargs))
|
||||
return {"message": "Hierarchy updated successfully.", "remaining_today": 0}
|
||||
|
||||
monkeypatch.setattr(service.logic, "update_hierarchy", update_hierarchy)
|
||||
hierarchy = [{"name_de": "Faculty of Science", "type": "faculty"}]
|
||||
|
||||
response = orgminer_client.post("/api/orgminer/save-hierarchy", json=hierarchy)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {
|
||||
"message": "Hierarchy updated successfully.",
|
||||
"remaining_today": 0,
|
||||
}
|
||||
assert calls == [
|
||||
(
|
||||
hierarchy,
|
||||
{"openalex_id": INSTITUTION_ID},
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def test_orgminer_content_forwards_org_and_institution(
|
||||
orgminer_client, institution_lookup, monkeypatch
|
||||
):
|
||||
|
||||
Reference in New Issue
Block a user