Spaces:
Paused

yaz / src /core /tools /workflow /models.py
anaselamr's picture
v8.4.4: Auth & Security Hardening — Sprint 43 P2
091ca1d
Raw History Blame Contribute Delete
8.05 kB
"""
Workflow Tool - Domain Models
=================================
Domain-agnostic visual workflow automation engine.
Manages trigger-action rules, conditional branching,
parallel execution, scheduled tasks, and Zapier-like
automation without code.
Entities:
WorkflowDefinition - Automation blueprint (trigger + actions)
WorkflowRun - Active execution instance
WorkflowStep - Individual step within a run
WorkflowEvent - Hash-chained audit trail
Enums:
TriggerType, ActionType, StepStatus,
RunStatus, WorkflowEventType
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from typing import Any, Dict, List, Optional
from uuid import UUID, uuid4
from pydantic import BaseModel, Field
# ============================================================================
# ENUMS
# ============================================================================
class TriggerType(str, Enum):
EVENT = "event"
SCHEDULE = "schedule"
WEBHOOK = "webhook"
MANUAL = "manual"
THRESHOLD = "threshold"
DATA_CHANGE = "data_change"
FORM_SUBMIT = "form_submit"
TIMER = "timer"
class WorkflowActionType(str, Enum):
SEND_NOTIFICATION = "send_notification"
CREATE_ORDER = "create_order"
CREATE_DOCUMENT = "create_document"
INITIATE_CHECKLIST = "initiate_checklist"
CREATE_JOURNAL_ENTRY = "create_journal_entry"
START_MONITOR = "start_monitor"
SCHEDULE_APPOINTMENT = "schedule_appointment"
SEND_WEBHOOK = "send_webhook"
SEND_EMAIL = "send_email"
SEND_SMS = "send_sms"
UPDATE_RECORD = "update_record"
CALCULATE = "calculate"
BRANCH = "branch"
WAIT = "wait"
APPROVE = "approve"
CUSTOM = "custom"
class ConditionOperator(str, Enum):
EQUALS = "equals"
NOT_EQUALS = "not_equals"
GREATER_THAN = "greater_than"
LESS_THAN = "less_than"
CONTAINS = "contains"
IN_LIST = "in_list"
IS_EMPTY = "is_empty"
IS_NOT_EMPTY = "is_not_empty"
MATCHES_REGEX = "matches_regex"
class StepStatus(str, Enum):
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
SKIPPED = "skipped"
WAITING_APPROVAL = "waiting_approval"
TIMED_OUT = "timed_out"
class RunStatus(str, Enum):
QUEUED = "queued"
RUNNING = "running"
PAUSED = "paused"
COMPLETED = "completed"
FAILED = "failed"
CANCELLED = "cancelled"
TIMED_OUT = "timed_out"
class WorkflowEventType(str, Enum):
DEFINITION_CREATED = "workflow.definition_created"
RUN_STARTED = "workflow.run_started"
STEP_STARTED = "workflow.step_started"
STEP_COMPLETED = "workflow.step_completed"
STEP_FAILED = "workflow.step_failed"
BRANCH_EVALUATED = "workflow.branch_evaluated"
RUN_COMPLETED = "workflow.run_completed"
RUN_FAILED = "workflow.run_failed"
RUN_CANCELLED = "workflow.run_cancelled"
APPROVAL_REQUESTED = "workflow.approval_requested"
# ============================================================================
# VALUE OBJECTS
# ============================================================================
@dataclass
class WorkflowCondition:
"""Conditional logic for branching."""
field: str = ""
operator: ConditionOperator = ConditionOperator.EQUALS
value: Any = None
logic: str = "and" # "and" | "or"
@dataclass
class WorkflowAction:
"""Single action step in a workflow."""
action_id: str = ""
action_type: WorkflowActionType = WorkflowActionType.SEND_NOTIFICATION
label: str = ""
config: Dict[str, Any] = field(default_factory=dict)
conditions: List[WorkflowCondition] = field(default_factory=list)
on_failure: str = "stop" # "stop" | "continue" | "retry"
timeout_seconds: int = 300
retry_count: int = 0
# ============================================================================
# DOMAIN ENTITIES
# ============================================================================
@dataclass
class WorkflowDefinition:
"""Automation blueprint with trigger + action chain."""
id: UUID = field(default_factory=uuid4)
tenant_id: UUID = field(default_factory=uuid4)
key: str = ""
title: str = ""
description: str = ""
version: str = "1.0.0"
domain: str = ""
trigger_type: TriggerType = TriggerType.EVENT
trigger_config: Dict[str, Any] = field(default_factory=dict)
actions: List[WorkflowAction] = field(default_factory=list)
variables: Dict[str, Any] = field(default_factory=dict)
max_concurrent_runs: int = 10
timeout_seconds: int = 3600
is_active: bool = True
is_system: bool = False
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
@dataclass
class WorkflowRun:
"""Active workflow execution instance."""
id: UUID = field(default_factory=uuid4)
tenant_id: UUID = field(default_factory=uuid4)
definition_id: UUID = field(default_factory=uuid4)
run_number: str = ""
status: RunStatus = RunStatus.QUEUED
trigger_data: Dict[str, Any] = field(default_factory=dict)
variables: Dict[str, Any] = field(default_factory=dict)
current_step_index: int = 0
steps_completed: int = 0
steps_total: int = 0
error_message: str = ""
started_by: UUID = field(default_factory=uuid4)
started_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
completed_at: Optional[datetime] = None
@dataclass
class WorkflowStep:
"""Individual step execution within a run."""
id: UUID = field(default_factory=uuid4)
tenant_id: UUID = field(default_factory=uuid4)
run_id: UUID = field(default_factory=uuid4)
action_id: str = ""
action_type: WorkflowActionType = WorkflowActionType.SEND_NOTIFICATION
label: str = ""
status: StepStatus = StepStatus.PENDING
input_data: Dict[str, Any] = field(default_factory=dict)
output_data: Dict[str, Any] = field(default_factory=dict)
error_message: str = ""
attempt_number: int = 1
started_at: Optional[datetime] = None
completed_at: Optional[datetime] = None
@dataclass
class WorkflowEvent:
"""Hash-chained workflow event."""
id: UUID = field(default_factory=uuid4)
tenant_id: UUID = field(default_factory=uuid4)
event_type: WorkflowEventType = WorkflowEventType.RUN_STARTED
data: Dict[str, Any] = field(default_factory=dict)
prev_hash: str = ""
hash: str = ""
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
# ============================================================================
# PYDANTIC SCHEMAS
# ============================================================================
class WorkflowTriggerRequest(BaseModel):
definition_id: Optional[UUID] = None
definition_key: Optional[str] = None
trigger_data: Dict[str, Any] = Field(default_factory=dict)
tenant_id: Optional[UUID] = None
user_id: Optional[UUID] = None
class WorkflowApproveRequest(BaseModel):
approved: bool = True
comment: str = ""
tenant_id: Optional[UUID] = None
user_id: Optional[UUID] = None
class WorkflowDefinitionResponse(BaseModel):
id: UUID
key: str
title: str
description: str
version: str
domain: str
trigger_type: str
trigger_config: Dict[str, Any]
actions: List[Dict[str, Any]]
max_concurrent_runs: int
is_active: bool
is_system: bool
class WorkflowRunResponse(BaseModel):
id: UUID
definition_id: UUID
run_number: str
status: str
current_step_index: int
steps_completed: int
steps_total: int
error_message: str
started_at: datetime
completed_at: Optional[datetime]
class WorkflowStepResponse(BaseModel):
id: UUID
run_id: UUID
action_id: str
action_type: str
label: str
status: str
output_data: Dict[str, Any]
error_message: str
attempt_number: int
started_at: Optional[datetime]
completed_at: Optional[datetime]