Files
PROJECT-CONTORL/backend/app/services/trigger_service.py
beabigegg 4b5a9c1d0a feat: complete LOW priority code quality improvements
Backend:
- LOW-002: Add Query validation with max page size limits (100)
- LOW-003: Replace magic strings with TaskStatus.is_done flag
- LOW-004: Add 'creation' trigger type validation
- Add action_executor.py with UpdateFieldAction and AutoAssignAction

Frontend:
- LOW-005: Replace TypeScript 'any' with 'unknown' + type guards
- LOW-006: Add ConfirmModal component with A11Y support
- LOW-007: Add ToastContext for user feedback notifications
- LOW-009: Add Skeleton components (17 loading states replaced)
- LOW-010: Setup Vitest with 21 tests for ConfirmModal and Skeleton

Components updated:
- App.tsx, ProtectedRoute.tsx, Spaces.tsx, Projects.tsx, Tasks.tsx
- ProjectSettings.tsx, AuditPage.tsx, WorkloadPage.tsx, ProjectHealthPage.tsx
- Comments.tsx, AttachmentList.tsx, TriggerList.tsx, TaskDetailModal.tsx
- NotificationBell.tsx, BlockerDialog.tsx, CalendarView.tsx, WorkloadUserDetail.tsx

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 21:24:36 +08:00

297 lines
10 KiB
Python

import uuid
import logging
from typing import List, Dict, Any, Optional
from sqlalchemy.orm import Session
from app.models import Trigger, TriggerLog, Task, User, Project
from app.services.notification_service import NotificationService
from app.services.action_executor import (
ActionExecutor,
ActionExecutionError,
ActionValidationError,
)
logger = logging.getLogger(__name__)
class TriggerService:
"""Service for evaluating and executing triggers."""
SUPPORTED_FIELDS = ["status_id", "assignee_id", "priority"]
SUPPORTED_OPERATORS = ["equals", "not_equals", "changed_to", "changed_from"]
@staticmethod
def evaluate_triggers(
db: Session,
task: Task,
old_values: Dict[str, Any],
new_values: Dict[str, Any],
current_user: User,
) -> List[TriggerLog]:
"""Evaluate all active triggers for a project when task values change."""
logs = []
# Get active field_change triggers for the project
triggers = db.query(Trigger).filter(
Trigger.project_id == task.project_id,
Trigger.is_active == True,
Trigger.trigger_type == "field_change",
).all()
for trigger in triggers:
if TriggerService._check_conditions(trigger.conditions, old_values, new_values):
log = TriggerService._execute_actions(db, trigger, task, current_user, old_values, new_values)
logs.append(log)
return logs
@staticmethod
def _check_conditions(
conditions: Dict[str, Any],
old_values: Dict[str, Any],
new_values: Dict[str, Any],
) -> bool:
"""Check if trigger conditions are met."""
field = conditions.get("field")
operator = conditions.get("operator")
value = conditions.get("value")
if field not in TriggerService.SUPPORTED_FIELDS:
return False
old_value = old_values.get(field)
new_value = new_values.get(field)
if operator == "equals":
return new_value == value
elif operator == "not_equals":
return new_value != value
elif operator == "changed_to":
return old_value != value and new_value == value
elif operator == "changed_from":
return old_value == value and new_value != value
return False
@staticmethod
def _execute_actions(
db: Session,
trigger: Trigger,
task: Task,
current_user: User,
old_values: Dict[str, Any],
new_values: Dict[str, Any],
) -> TriggerLog:
"""Execute trigger actions and log the result.
Uses a database savepoint to ensure atomicity - if any action fails,
all previously executed actions within this trigger are rolled back.
"""
actions = trigger.actions if isinstance(trigger.actions, list) else [trigger.actions]
executed_actions = []
error_message = None
# Build execution context
context = {
"old_values": old_values,
"new_values": new_values,
"current_user": current_user,
"trigger": trigger,
}
# Use savepoint for transaction atomicity - if any action fails,
# all changes made by previous actions will be rolled back
savepoint = db.begin_nested()
try:
for action in actions:
action_type = action.get("type")
# Handle built-in notify action
if action_type == "notify":
TriggerService._execute_notify_action(db, action, task, current_user, old_values, new_values)
executed_actions.append({"type": action_type, "status": "success"})
# Handle update_field action (FEAT-014)
elif action_type == "update_field":
result = ActionExecutor.execute_action(db, task, action, context)
if result:
executed_actions.append(result)
logger.info(
f"Trigger '{trigger.name}' executed update_field: "
f"field={result.get('field')}, new_value={result.get('new_value')}"
)
# Handle auto_assign action (FEAT-015)
elif action_type == "auto_assign":
result = ActionExecutor.execute_action(db, task, action, context)
if result:
executed_actions.append(result)
logger.info(
f"Trigger '{trigger.name}' executed auto_assign: "
f"strategy={result.get('strategy')}, assignee={result.get('new_assignee_id')}"
)
# Try to execute via ActionExecutor for extensibility
else:
result = ActionExecutor.execute_action(db, task, action, context)
if result:
executed_actions.append(result)
# All actions succeeded, commit the savepoint
savepoint.commit()
status = "success"
except ActionExecutionError as e:
# Rollback all changes made by previously executed actions
savepoint.rollback()
status = "failed"
error_message = str(e)
executed_actions.append({"type": "error", "message": str(e)})
logger.error(f"Trigger '{trigger.name}' action execution failed, rolling back: {e}")
except Exception as e:
# Rollback all changes made by previously executed actions
savepoint.rollback()
status = "failed"
error_message = str(e)
executed_actions.append({"type": "error", "message": str(e)})
logger.exception(f"Trigger '{trigger.name}' unexpected error, rolling back: {e}")
log = TriggerLog(
id=str(uuid.uuid4()),
trigger_id=trigger.id,
task_id=task.id,
status=status,
details={
"trigger_name": trigger.name,
"old_values": old_values,
"new_values": new_values,
"actions_executed": executed_actions,
},
error_message=error_message,
)
db.add(log)
return log
@staticmethod
def _execute_notify_action(
db: Session,
action: Dict[str, Any],
task: Task,
current_user: User,
old_values: Dict[str, Any],
new_values: Dict[str, Any],
) -> None:
"""Execute a notify action."""
target = action.get("target", "assignee")
template = action.get("template", "任務 {task_title} 已觸發自動化規則")
# Resolve target user
target_user_id = TriggerService._resolve_target(task, target)
if not target_user_id:
return
# Don't notify the user who triggered the action
if target_user_id == current_user.id:
return
# Format message with variables
message = TriggerService._format_template(template, task, old_values, new_values)
NotificationService.create_notification(
db=db,
user_id=target_user_id,
notification_type="status_change",
reference_type="task",
reference_id=task.id,
title=f"自動化通知: {task.title}",
message=message,
)
@staticmethod
def _resolve_target(task: Task, target: str) -> Optional[str]:
"""Resolve notification target to user ID."""
if target == "assignee":
return task.assignee_id
elif target == "creator":
return task.created_by
elif target == "project_owner":
return task.project.owner_id if task.project else None
elif target.startswith("user:"):
return target.split(":", 1)[1]
return None
@staticmethod
def _format_template(
template: str,
task: Task,
old_values: Dict[str, Any],
new_values: Dict[str, Any],
) -> str:
"""Format message template with task variables."""
replacements = {
"{task_title}": task.title,
"{task_id}": task.id,
"{old_value}": str(old_values.get("status_id", old_values.get("assignee_id", old_values.get("priority", "")))),
"{new_value}": str(new_values.get("status_id", new_values.get("assignee_id", new_values.get("priority", "")))),
}
result = template
for key, value in replacements.items():
result = result.replace(key, value)
return result
@staticmethod
def log_execution(
db: Session,
trigger: Trigger,
task: Optional[Task],
status: str,
details: Optional[Dict[str, Any]] = None,
error_message: Optional[str] = None,
) -> TriggerLog:
"""Log a trigger execution."""
log = TriggerLog(
id=str(uuid.uuid4()),
trigger_id=trigger.id,
task_id=task.id if task else None,
status=status,
details=details,
error_message=error_message,
)
db.add(log)
return log
@staticmethod
def validate_actions(actions: List[Dict[str, Any]], db: Session) -> None:
"""Validate trigger actions configuration.
Args:
actions: List of action configurations
db: Database session
Raises:
ActionValidationError: If any action is invalid
"""
valid_action_types = ["notify", "update_field", "auto_assign"]
for action in actions:
action_type = action.get("type")
if not action_type:
raise ActionValidationError("Missing action 'type'")
if action_type not in valid_action_types:
raise ActionValidationError(
f"Invalid action type '{action_type}'. "
f"Valid types: {valid_action_types}"
)
# Validate via ActionExecutor for extensible actions
if action_type in ["update_field", "auto_assign"]:
ActionExecutor.validate_action(action, db)
@staticmethod
def get_supported_action_types() -> List[str]:
"""Get list of all supported action types."""
return ["notify"] + ActionExecutor.get_supported_actions()