openforce/workflows/models.py

92 lines
3.2 KiB
Python

from django.db import models
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
User = get_user_model()
class FlowDefinition(models.Model):
TRIGGER_TYPE_CHOICES = [
('record_created', 'Record Created'),
('record_updated', 'Record Updated'),
('scheduled', 'Scheduled'),
('manual', 'Manual / API Trigger'),
]
name = models.CharField(max_length=255)
description = models.TextField(blank=True, default='')
trigger_type = models.CharField(max_length=50, choices=TRIGGER_TYPE_CHOICES, default='manual')
trigger_object = models.CharField(max_length=100, blank=True, null=True)
is_active = models.BooleanField(default=True)
# Vue Flow Graph: { "nodes": [...], "edges": [...] }
graph = models.JSONField(
default=dict,
help_text="Vue Flow DAG graph structure with nodes and edges"
)
created_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
def clean(self):
super().clean()
from .engine import validate_flow_dag
validate_flow_dag(self.graph)
def save(self, *args, **kwargs):
self.clean()
super().save(*args, **kwargs)
def __str__(self):
return f"{self.name} ({'Active' if self.is_active else 'Draft'})"
class FlowExecutionLog(models.Model):
STATUS_CHOICES = [
('pending', 'Pending'),
('running', 'Running'),
('completed', 'Completed'),
('failed', 'Failed'),
]
flow = models.ForeignKey(FlowDefinition, on_delete=models.CASCADE, related_name='executions')
flow_definition = models.ForeignKey(FlowDefinition, null=True, blank=True, on_delete=models.CASCADE, related_name='legacy_executions')
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending')
started_at = models.DateTimeField(auto_now_add=True)
completed_at = models.DateTimeField(null=True, blank=True)
steps_executed = models.JSONField(default=list)
context_data = models.JSONField(default=dict)
error_message = models.TextField(blank=True, default='')
idempotency_key = models.CharField(max_length=255, null=True, blank=True, db_index=True)
class Meta:
ordering = ['-started_at']
constraints = [
models.UniqueConstraint(
fields=['flow', 'idempotency_key'],
name='unique_flow_idempotency_key_when_not_null',
condition=models.Q(idempotency_key__isnull=False)
)
]
@property
def context(self):
return self.context_data
@context.setter
def context(self, value):
self.context_data = value
def save(self, *args, **kwargs):
if self.flow_id and not self.flow_definition_id:
self.flow_definition = self.flow
elif self.flow_definition_id and not self.flow_id:
self.flow = self.flow_definition
super().save(*args, **kwargs)
def __str__(self):
return f"Execution of {self.flow.name} [{self.status}]"