File size: 3,866 Bytes
3a006a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
from fastapi import APIRouter, Depends, Request, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, update
from datetime import datetime, timezone
from loguru import logger

from app.database import get_db
from app.models.system import WorkflowConfig, ActivityLog

router = APIRouter(prefix="/v1/admin", tags=["Admin"])


def _ensure_admin(request: Request):
    """Enforce admin role requirement."""
    role = getattr(request.state, "user_role", None)
    if role not in ("admin", "ADMIN"):
        raise HTTPException(status_code=403, detail="Admin role required")


async def _get_workflow_or_404(workflow_name: str, db: AsyncSession) -> WorkflowConfig:
    """Fetch a workflow by name or raise 404."""
    result = await db.execute(
        select(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name)
    )
    row = result.scalar_one_or_none()
    if row is None:
        raise HTTPException(status_code=404, detail=f"Workflow '{workflow_name}' not found")
    return row


async def _log_activity(db: AsyncSession, request: Request, action: str, metadata: str):
    """Record an activity log entry. Errors are logged but do not fail the request."""
    try:
        log = ActivityLog(
            actor=getattr(request.state, 'user_email', None) or 'system',
            action=action,
            log_metadata=metadata,
        )
        db.add(log)
        await db.commit()
    except Exception as e:
        logger.warning(f"Failed to log activity '{action}': {e}")
        try:
            await db.rollback()
        except Exception:
            pass


@router.get("/workflows")
async def list_workflows(request: Request, db: AsyncSession = Depends(get_db)):
    _ensure_admin(request)
    result = await db.execute(select(WorkflowConfig))
    rows = result.scalars().all()
    return [
        {
            "workflow_name": r.workflow_name,
            "is_active": r.is_active,
            "schedule_cron": r.schedule_cron,
            "last_run": r.last_run,
            "updated_at": r.updated_at,
        }
        for r in rows
    ]


@router.patch("/workflows/{workflow_name}")
async def update_workflow(workflow_name: str, payload: dict, request: Request, db: AsyncSession = Depends(get_db)):
    _ensure_admin(request)
    await _get_workflow_or_404(workflow_name, db)
    # Only allow specific fields
    allowed = {"is_active", "schedule_cron"}
    update_values = {k: v for k, v in payload.items() if k in allowed}
    if not update_values:
        raise HTTPException(status_code=400, detail="No valid fields to update. Allowed: is_active, schedule_cron")
    update_values["updated_at"] = datetime.now(timezone.utc)
    stmt = update(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name).values(**update_values)
    await db.execute(stmt)
    await db.commit()
    await _log_activity(db, request, f"workflow_update:{workflow_name}", str(update_values))
    return {"success": True, "updated": update_values}


@router.post("/workflows/{workflow_name}/run")
async def run_workflow(workflow_name: str, request: Request, db: AsyncSession = Depends(get_db)):
    _ensure_admin(request)
    await _get_workflow_or_404(workflow_name, db)
    # Manual trigger stub: update last_run and return accepted. Actual orchestrator should listen to this event.
    stmt = update(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name).values({"last_run": datetime.now(timezone.utc), "updated_at": datetime.now(timezone.utc)})
    await db.execute(stmt)
    await db.commit()
    await _log_activity(db, request, f"workflow_manual_trigger:{workflow_name}", "Manual trigger via admin panel")
    return {"success": True, "message": "Workflow run recorded (manual trigger)."}