Files
PROJECT-CONTORL/backend/app/api/triggers/router.py
beabigegg 95c281d8e1 feat: implement automation module
- Event-based triggers (Phase 1):
  - Trigger/TriggerLog models with field_change type
  - TriggerService for condition evaluation and action execution
  - Trigger CRUD API endpoints
  - Task integration (status, assignee, priority changes)
  - Frontend: TriggerList, TriggerForm components

- Weekly reports (Phase 2):
  - ScheduledReport/ReportHistory models
  - ReportService for stats generation
  - APScheduler for Friday 16:00 job
  - Report preview/generate/history API
  - Frontend: WeeklyReportPreview, ReportHistory components

- Tests: 23 new tests (14 triggers + 9 reports)
- OpenSpec: add-automation change archived

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-29 22:59:00 +08:00

277 lines
8.9 KiB
Python

import uuid
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import Optional
from app.core.database import get_db
from app.models import User, Project, Trigger, TriggerLog
from app.schemas.trigger import (
TriggerCreate, TriggerUpdate, TriggerResponse, TriggerListResponse,
TriggerLogResponse, TriggerLogListResponse, TriggerUserInfo
)
from app.middleware.auth import get_current_user, check_project_access, check_project_edit_access
router = APIRouter(tags=["triggers"])
def trigger_to_response(trigger: Trigger) -> TriggerResponse:
"""Convert Trigger model to TriggerResponse."""
return TriggerResponse(
id=trigger.id,
project_id=trigger.project_id,
name=trigger.name,
description=trigger.description,
trigger_type=trigger.trigger_type,
conditions=trigger.conditions,
actions=trigger.actions if isinstance(trigger.actions, list) else [trigger.actions],
is_active=trigger.is_active,
created_by=trigger.created_by,
created_at=trigger.created_at,
updated_at=trigger.updated_at,
creator=TriggerUserInfo(
id=trigger.creator.id,
name=trigger.creator.name,
email=trigger.creator.email,
) if trigger.creator else None,
)
@router.post("/api/projects/{project_id}/triggers", response_model=TriggerResponse, status_code=status.HTTP_201_CREATED)
async def create_trigger(
project_id: str,
trigger_data: TriggerCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""Create a new trigger for a project."""
project = db.query(Project).filter(Project.id == project_id).first()
if not project:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Project not found",
)
if not check_project_edit_access(current_user, project):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Permission denied - only project owner can manage triggers",
)
# Validate trigger type
if trigger_data.trigger_type not in ["field_change", "schedule"]:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid trigger type. Must be 'field_change' or 'schedule'",
)
# Validate conditions
if trigger_data.conditions.field not in ["status_id", "assignee_id", "priority"]:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid condition field. Must be 'status_id', 'assignee_id', or 'priority'",
)
if trigger_data.conditions.operator not in ["equals", "not_equals", "changed_to", "changed_from"]:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid operator. Must be 'equals', 'not_equals', 'changed_to', or 'changed_from'",
)
# Create trigger
trigger = Trigger(
id=str(uuid.uuid4()),
project_id=project_id,
name=trigger_data.name,
description=trigger_data.description,
trigger_type=trigger_data.trigger_type,
conditions=trigger_data.conditions.model_dump(),
actions=[a.model_dump() for a in trigger_data.actions],
is_active=trigger_data.is_active,
created_by=current_user.id,
)
db.add(trigger)
db.commit()
db.refresh(trigger)
return trigger_to_response(trigger)
@router.get("/api/projects/{project_id}/triggers", response_model=TriggerListResponse)
async def list_triggers(
project_id: str,
is_active: Optional[bool] = None,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""List all triggers for a project."""
project = db.query(Project).filter(Project.id == project_id).first()
if not project:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Project not found",
)
if not check_project_access(current_user, project):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Access denied",
)
query = db.query(Trigger).filter(Trigger.project_id == project_id)
if is_active is not None:
query = query.filter(Trigger.is_active == is_active)
triggers = query.order_by(Trigger.created_at.desc()).all()
return TriggerListResponse(
triggers=[trigger_to_response(t) for t in triggers],
total=len(triggers),
)
@router.get("/api/triggers/{trigger_id}", response_model=TriggerResponse)
async def get_trigger(
trigger_id: str,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""Get a specific trigger by ID."""
trigger = db.query(Trigger).filter(Trigger.id == trigger_id).first()
if not trigger:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Trigger not found",
)
project = trigger.project
if not check_project_access(current_user, project):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Access denied",
)
return trigger_to_response(trigger)
@router.put("/api/triggers/{trigger_id}", response_model=TriggerResponse)
async def update_trigger(
trigger_id: str,
trigger_data: TriggerUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""Update a trigger."""
trigger = db.query(Trigger).filter(Trigger.id == trigger_id).first()
if not trigger:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Trigger not found",
)
project = trigger.project
if not check_project_edit_access(current_user, project):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Permission denied",
)
# Update fields if provided
if trigger_data.name is not None:
trigger.name = trigger_data.name
if trigger_data.description is not None:
trigger.description = trigger_data.description
if trigger_data.conditions is not None:
# Validate conditions
if trigger_data.conditions.field not in ["status_id", "assignee_id", "priority"]:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid condition field",
)
trigger.conditions = trigger_data.conditions.model_dump()
if trigger_data.actions is not None:
trigger.actions = [a.model_dump() for a in trigger_data.actions]
if trigger_data.is_active is not None:
trigger.is_active = trigger_data.is_active
db.commit()
db.refresh(trigger)
return trigger_to_response(trigger)
@router.delete("/api/triggers/{trigger_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_trigger(
trigger_id: str,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""Delete a trigger."""
trigger = db.query(Trigger).filter(Trigger.id == trigger_id).first()
if not trigger:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Trigger not found",
)
project = trigger.project
if not check_project_edit_access(current_user, project):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Permission denied",
)
db.delete(trigger)
db.commit()
@router.get("/api/triggers/{trigger_id}/logs", response_model=TriggerLogListResponse)
async def list_trigger_logs(
trigger_id: str,
limit: int = 50,
offset: int = 0,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""Get execution logs for a trigger."""
trigger = db.query(Trigger).filter(Trigger.id == trigger_id).first()
if not trigger:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Trigger not found",
)
project = trigger.project
if not check_project_access(current_user, project):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Access denied",
)
total = db.query(TriggerLog).filter(TriggerLog.trigger_id == trigger_id).count()
logs = db.query(TriggerLog).filter(
TriggerLog.trigger_id == trigger_id,
).order_by(TriggerLog.executed_at.desc()).offset(offset).limit(limit).all()
return TriggerLogListResponse(
logs=[
TriggerLogResponse(
id=log.id,
trigger_id=log.trigger_id,
task_id=log.task_id,
executed_at=log.executed_at,
status=log.status,
details=log.details,
error_message=log.error_message,
) for log in logs
],
total=total,
)