Sync GovOPlaN module state
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
|
||||
from sqlalchemy import and_, func, or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -8,7 +8,12 @@ from govoplan_core.admin.common import AdminValidationError, slugify
|
||||
from govoplan_core.admin.settings import get_system_settings
|
||||
from govoplan_core.auth import ApiPrincipal, get_api_principal, has_scope, require_scope
|
||||
from govoplan_core.audit.logging import audit_event
|
||||
from govoplan_core.core.access import CAPABILITY_ACCESS_TENANT_PROVISIONER, TenantAccessProvisioner
|
||||
from govoplan_core.core.access import (
|
||||
CAPABILITY_ACCESS_TENANT_PROVISIONER,
|
||||
CAPABILITY_AUTH_TENANT_CONTEXT_SWITCHER,
|
||||
TenantAccessProvisioner,
|
||||
TenantContextSwitcher,
|
||||
)
|
||||
from govoplan_core.core.change_sequence import ChangeSequenceEntry, decode_sequence_watermark, encode_sequence_watermark, record_change, sequence_watermark_is_expired
|
||||
from govoplan_core.core.runtime import get_registry
|
||||
from govoplan_core.db.session import get_session
|
||||
@@ -20,6 +25,7 @@ from govoplan_core.i18n import (
|
||||
tenant_enabled_language_codes,
|
||||
update_i18n_settings,
|
||||
)
|
||||
from govoplan_core.security.time import utc_now
|
||||
from govoplan_core.tenancy.service import (
|
||||
assert_tenant_governance_override_allowed,
|
||||
effective_tenant_governance,
|
||||
@@ -29,7 +35,13 @@ from govoplan_tenancy.backend.db.models import Tenant
|
||||
|
||||
from .schemas import (
|
||||
TenantAdminItem,
|
||||
TenantContextSwitchRequest,
|
||||
TenantContextSwitchResponse,
|
||||
TenantCreateRequest,
|
||||
TenantDeleteRequest,
|
||||
TenantDeletionPlanResponse,
|
||||
TenantLifecycleIssue,
|
||||
TenantLifecycleResponse,
|
||||
TenantListDeltaResponse,
|
||||
TenantListResponse,
|
||||
TenantOwnerCandidate,
|
||||
@@ -41,6 +53,7 @@ from .schemas import (
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/admin", tags=["admin"])
|
||||
tenant_router = APIRouter(prefix="/tenancy", tags=["tenancy"])
|
||||
|
||||
TENANCY_MODULE_ID = "tenancy"
|
||||
TENANT_LIST_COLLECTION = "tenancy.tenants"
|
||||
@@ -62,6 +75,16 @@ def _tenant_access_provisioner() -> TenantAccessProvisioner:
|
||||
return capability
|
||||
|
||||
|
||||
def _tenant_context_switcher() -> TenantContextSwitcher:
|
||||
registry = get_registry()
|
||||
if registry is None or not hasattr(registry, "has_capability") or not registry.has_capability(CAPABILITY_AUTH_TENANT_CONTEXT_SWITCHER):
|
||||
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Tenant context switcher capability is not configured")
|
||||
capability = registry.require_capability(CAPABILITY_AUTH_TENANT_CONTEXT_SWITCHER)
|
||||
if not isinstance(capability, TenantContextSwitcher):
|
||||
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Tenant context switcher capability is invalid")
|
||||
return capability
|
||||
|
||||
|
||||
def _require_permission(principal: ApiPrincipal, scope: str) -> None:
|
||||
if not has_scope(principal, scope):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f"Missing scope: {scope}")
|
||||
@@ -91,6 +114,61 @@ def _tenant_item(session: Session, tenant: Tenant) -> TenantAdminItem:
|
||||
)
|
||||
|
||||
|
||||
def _tenant_deletion_plan(session: Session, tenant: Tenant, principal: ApiPrincipal, *, mode: str = "retire") -> TenantDeletionPlanResponse:
|
||||
issues: list[TenantLifecycleIssue] = []
|
||||
counts = tenant_counts(session, tenant.id)
|
||||
destructive = mode == "destroy"
|
||||
if tenant.id == principal.tenant_id:
|
||||
issues.append(TenantLifecycleIssue(
|
||||
severity="blocker",
|
||||
code="active_tenant",
|
||||
message=f"Switch to another tenant before {'deleting' if destructive else 'retiring'} the active tenant.",
|
||||
module_id=TENANCY_MODULE_ID,
|
||||
))
|
||||
if not tenant.is_active:
|
||||
issues.append(TenantLifecycleIssue(
|
||||
severity="info",
|
||||
code="already_inactive",
|
||||
message="Tenant is already inactive; retiring it again will only refresh lifecycle metadata.",
|
||||
module_id=TENANCY_MODULE_ID,
|
||||
))
|
||||
has_tenant_data = any(value for value in counts.values())
|
||||
if destructive and has_tenant_data:
|
||||
issues.append(TenantLifecycleIssue(
|
||||
severity="blocker",
|
||||
code="tenant_data_present",
|
||||
message="Tenant-owned data exists; retire the tenant or remove its data before destructive deletion.",
|
||||
module_id=TENANCY_MODULE_ID,
|
||||
))
|
||||
elif has_tenant_data:
|
||||
issues.append(TenantLifecycleIssue(
|
||||
severity="warning",
|
||||
code="tenant_data_retained",
|
||||
message="Tenant-owned data will be retained. This operation is non-destructive.",
|
||||
module_id=TENANCY_MODULE_ID,
|
||||
))
|
||||
|
||||
registry = get_registry()
|
||||
if registry is not None and hasattr(registry, "delete_veto_providers"):
|
||||
for provider in registry.delete_veto_providers("tenant"):
|
||||
try:
|
||||
provider(session, tenant.id, tenant.id)
|
||||
except Exception as exc:
|
||||
issues.append(TenantLifecycleIssue(
|
||||
severity="blocker",
|
||||
code="module_veto",
|
||||
message=str(exc),
|
||||
))
|
||||
return TenantDeletionPlanResponse(
|
||||
tenant_id=tenant.id,
|
||||
action="destroy" if destructive else "retire",
|
||||
allowed=not any(issue.severity == "blocker" for issue in issues),
|
||||
destructive_supported=destructive and not has_tenant_data,
|
||||
issues=issues,
|
||||
counts=counts,
|
||||
)
|
||||
|
||||
|
||||
def _tenant_settings_item(session: Session, tenant: Tenant) -> TenantSettingsItem:
|
||||
system_settings = get_system_settings(session)
|
||||
system_payload = system_i18n_payload(system_settings)
|
||||
@@ -254,6 +332,27 @@ def _tenant_settings_response_watermark(session: Session, *, tenant_id: str, ent
|
||||
return encode_sequence_watermark(entries[-1].id) if has_more and entries else _tenant_settings_watermark(session, tenant_id=tenant_id)
|
||||
|
||||
|
||||
@tenant_router.post("/switch-tenant", response_model=TenantContextSwitchResponse)
|
||||
def switch_tenant_context(
|
||||
payload: TenantContextSwitchRequest,
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
):
|
||||
try:
|
||||
switched = _tenant_context_switcher().switch_tenant_context(session, principal=principal, tenant_id=payload.tenant_id)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
|
||||
except LookupError as exc:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
|
||||
session.commit()
|
||||
return TenantContextSwitchResponse(
|
||||
account_id=switched.account_id,
|
||||
membership_id=switched.membership_id,
|
||||
tenant_id=switched.tenant_id,
|
||||
session_id=switched.session_id,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/tenants", response_model=TenantListResponse)
|
||||
def list_tenants(
|
||||
session: Session = Depends(get_session),
|
||||
@@ -430,6 +529,82 @@ def update_tenant(
|
||||
return _tenant_item(session, tenant)
|
||||
|
||||
|
||||
@router.get("/tenants/{tenant_id}/deletion-plan", response_model=TenantDeletionPlanResponse)
|
||||
def tenant_deletion_plan(
|
||||
tenant_id: str,
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(require_scope("system:tenants:suspend")),
|
||||
):
|
||||
tenant = session.get(Tenant, tenant_id)
|
||||
if tenant is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Tenant not found")
|
||||
return _tenant_deletion_plan(session, tenant, principal)
|
||||
|
||||
|
||||
@router.delete("/tenants/{tenant_id}", response_model=TenantLifecycleResponse)
|
||||
def retire_tenant(
|
||||
tenant_id: str,
|
||||
payload: TenantDeleteRequest | None = Body(default=None),
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(require_scope("system:tenants:suspend")),
|
||||
):
|
||||
request = payload or TenantDeleteRequest()
|
||||
tenant = session.get(Tenant, tenant_id)
|
||||
if tenant is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Tenant not found")
|
||||
plan = _tenant_deletion_plan(session, tenant, principal, mode=request.mode)
|
||||
if not plan.allowed:
|
||||
action_label = "destroyed" if request.mode == "destroy" else "retired"
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail={"message": f"Tenant cannot be {action_label}.", "plan": plan.model_dump(mode="json")},
|
||||
)
|
||||
|
||||
if request.mode == "destroy":
|
||||
deleted_item = _tenant_item(session, tenant)
|
||||
audit_event(
|
||||
session,
|
||||
tenant_id=tenant.id,
|
||||
user_id=principal.user.id,
|
||||
action="tenant.destroyed",
|
||||
scope="system",
|
||||
object_type="tenant",
|
||||
object_id=tenant.id,
|
||||
details={"reason": request.reason, "counts": plan.counts},
|
||||
)
|
||||
_record_tenant_list_change(session, tenant=tenant, operation="deleted", principal=principal)
|
||||
session.delete(tenant)
|
||||
session.commit()
|
||||
return TenantLifecycleResponse(item=deleted_item, plan=plan)
|
||||
|
||||
settings_payload = dict(tenant.settings or {})
|
||||
lifecycle_payload = dict(settings_payload.get("lifecycle") or {})
|
||||
lifecycle_payload.update({
|
||||
"state": "retired",
|
||||
"retired_at": utc_now().isoformat(),
|
||||
"retired_by_user_id": principal.user.id,
|
||||
})
|
||||
if request.reason:
|
||||
lifecycle_payload["reason"] = request.reason.strip()
|
||||
settings_payload["lifecycle"] = lifecycle_payload
|
||||
tenant.settings = settings_payload
|
||||
tenant.is_active = False
|
||||
session.add(tenant)
|
||||
audit_event(
|
||||
session,
|
||||
tenant_id=tenant.id,
|
||||
user_id=principal.user.id,
|
||||
action="tenant.retired",
|
||||
scope="system",
|
||||
object_type="tenant",
|
||||
object_id=tenant.id,
|
||||
details={"reason": request.reason, "counts": plan.counts},
|
||||
)
|
||||
_record_tenant_list_change(session, tenant=tenant, operation="updated", principal=principal)
|
||||
session.commit()
|
||||
return TenantLifecycleResponse(item=_tenant_item(session, tenant), plan=plan)
|
||||
|
||||
|
||||
@router.get("/tenant/settings", response_model=TenantSettingsItem)
|
||||
def get_tenant_settings(
|
||||
session: Session = Depends(get_session),
|
||||
|
||||
Reference in New Issue
Block a user