Compare commits
10 commits
af8556597a
...
d15b3c51ac
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d15b3c51ac | ||
|
|
ef9424f6f4 | ||
|
|
264d2a575e | ||
|
|
cba612622e | ||
|
|
2d41c964d2 | ||
|
|
a97fde2d59 | ||
|
|
eb3a85586a | ||
|
|
e81d4339c3 | ||
|
|
f579400ac5 | ||
|
|
9318bb3736 |
34 changed files with 1808 additions and 169 deletions
30
.forgejo/workflows/deploy.yaml
Normal file
30
.forgejo/workflows/deploy.yaml
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
name: Build, Test, and Deploy
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
build-and-deploy:
|
||||
runs-on: self-hosted
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Build and Package Docker Image
|
||||
run: |
|
||||
docker build \
|
||||
-t git.ch4t.buzz/buzzparty/openforce:${{ github.sha }} \
|
||||
-t git.ch4t.buzz/buzzparty/openforce:latest \
|
||||
.
|
||||
|
||||
- name: Push to Forgejo Registry
|
||||
run: |
|
||||
docker push git.ch4t.buzz/buzzparty/openforce:${{ github.sha }}
|
||||
docker push git.ch4t.buzz/buzzparty/openforce:latest
|
||||
|
||||
- name: Roll out to Kubernetes
|
||||
run: |
|
||||
kubectl set image deployment/openforce \
|
||||
openforce=git.ch4t.buzz/buzzparty/openforce:${{ github.sha }} \
|
||||
-n default
|
||||
kubectl rollout status deployment/openforce -n default --timeout=180s
|
||||
47
Dockerfile
Normal file
47
Dockerfile
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
# Stage 1: Build Vue 3 Frontend
|
||||
FROM node:20-alpine AS frontend-builder
|
||||
WORKDIR /app/frontend
|
||||
|
||||
COPY frontend/package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY frontend/ ./
|
||||
RUN npm run build
|
||||
|
||||
# Stage 2: Python / Django Runtime
|
||||
FROM python:3.11-slim
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
DJANGO_SETTINGS_MODULE=openforce.settings.prod \
|
||||
PORT=8000
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install system dependencies
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
libpq-dev \
|
||||
curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Python requirements
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy application source
|
||||
COPY . .
|
||||
|
||||
# Copy built frontend assets to frontend/dist
|
||||
COPY --from=frontend-builder /app/frontend/dist /app/frontend/dist
|
||||
|
||||
# Collect static files into STATIC_ROOT
|
||||
RUN mkdir -p /app/staticfiles /app/data && \
|
||||
python manage.py collectstatic --noinput
|
||||
|
||||
RUN chmod +x /app/entrypoint.sh
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
# Start via entrypoint
|
||||
ENTRYPOINT ["/app/entrypoint.sh"]
|
||||
|
|
@ -19,51 +19,124 @@ class CustomFieldsValidationMixin:
|
|||
return attrs
|
||||
|
||||
|
||||
class AccountSerializer(CustomFieldsValidationMixin, serializers.ModelSerializer):
|
||||
class OwnerScopedRelationMixin:
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
request = self.context.get('request')
|
||||
if request and hasattr(request, 'user') and request.user.is_authenticated:
|
||||
user = request.user
|
||||
if not (user.is_superuser or user.is_staff):
|
||||
for field_name, field in self.fields.items():
|
||||
if isinstance(field, serializers.PrimaryKeyRelatedField):
|
||||
model = getattr(field.queryset, 'model', None)
|
||||
if model:
|
||||
if hasattr(model, 'owner'):
|
||||
field.queryset = field.queryset.filter(owner=user)
|
||||
elif hasattr(model, 'created_by'):
|
||||
field.queryset = field.queryset.filter(created_by=user)
|
||||
|
||||
|
||||
class AccountSerializer(OwnerScopedRelationMixin, CustomFieldsValidationMixin, serializers.ModelSerializer):
|
||||
entity_name = 'Account'
|
||||
|
||||
class Meta:
|
||||
model = Account
|
||||
fields = '__all__'
|
||||
read_only_fields = ['id', 'created_at', 'updated_at']
|
||||
read_only_fields = ['id', 'owner', 'created_at', 'updated_at']
|
||||
|
||||
|
||||
class ContactSerializer(CustomFieldsValidationMixin, serializers.ModelSerializer):
|
||||
class ContactSerializer(OwnerScopedRelationMixin, CustomFieldsValidationMixin, serializers.ModelSerializer):
|
||||
entity_name = 'Contact'
|
||||
|
||||
class Meta:
|
||||
model = Contact
|
||||
fields = '__all__'
|
||||
read_only_fields = ['id', 'created_at', 'updated_at']
|
||||
read_only_fields = ['id', 'owner', 'created_at', 'updated_at']
|
||||
|
||||
|
||||
class LeadSerializer(CustomFieldsValidationMixin, serializers.ModelSerializer):
|
||||
class LeadSerializer(OwnerScopedRelationMixin, CustomFieldsValidationMixin, serializers.ModelSerializer):
|
||||
entity_name = 'Lead'
|
||||
|
||||
class Meta:
|
||||
model = Lead
|
||||
fields = '__all__'
|
||||
read_only_fields = [
|
||||
'id', 'is_converted', 'converted_date',
|
||||
'id', 'owner', 'is_converted', 'converted_date',
|
||||
'converted_account', 'converted_contact',
|
||||
'converted_opportunity', 'created_at', 'updated_at'
|
||||
]
|
||||
|
||||
|
||||
class OpportunitySerializer(CustomFieldsValidationMixin, serializers.ModelSerializer):
|
||||
class OpportunitySerializer(OwnerScopedRelationMixin, CustomFieldsValidationMixin, serializers.ModelSerializer):
|
||||
entity_name = 'Opportunity'
|
||||
|
||||
class Meta:
|
||||
model = Opportunity
|
||||
fields = '__all__'
|
||||
read_only_fields = ['id', 'expected_revenue', 'created_at', 'updated_at']
|
||||
read_only_fields = ['id', 'owner', 'expected_revenue', 'created_at', 'updated_at']
|
||||
|
||||
|
||||
class ActivitySerializer(serializers.ModelSerializer):
|
||||
class ActivitySerializer(OwnerScopedRelationMixin, serializers.ModelSerializer):
|
||||
ALLOWED_TARGET_MODELS = {
|
||||
('crm_core', 'account'),
|
||||
('crm_core', 'contact'),
|
||||
('crm_core', 'lead'),
|
||||
('crm_core', 'opportunity'),
|
||||
('crm_core', 'activity'),
|
||||
('custom_objects', 'customrecord'),
|
||||
}
|
||||
class Meta:
|
||||
model = Activity
|
||||
fields = '__all__'
|
||||
read_only_fields = ['id', 'completed_at', 'created_at', 'updated_at']
|
||||
read_only_fields = ['id', 'assigned_to', 'completed_at', 'created_at', 'updated_at']
|
||||
|
||||
def validate(self, attrs):
|
||||
attrs = super().validate(attrs)
|
||||
# For partial updates, check attrs first, then fall back to instance
|
||||
content_type = attrs['content_type'] if 'content_type' in attrs else getattr(self.instance, 'content_type', None)
|
||||
object_id = attrs['object_id'] if 'object_id' in attrs else getattr(self.instance, 'object_id', None)
|
||||
|
||||
# Disallow half-cleared or half-specified polymorphic relationship
|
||||
if (content_type is not None and object_id is None) or (content_type is None and object_id is not None):
|
||||
raise serializers.ValidationError({
|
||||
'non_field_errors': ['Polymorphic parent requires both content_type and object_id to be set together, or both cleared.']
|
||||
})
|
||||
|
||||
# If both are present, validate against the allowed model registry and actor-scoped queryset
|
||||
if content_type and object_id:
|
||||
target_key = (content_type.app_label, content_type.model)
|
||||
if target_key not in self.ALLOWED_TARGET_MODELS:
|
||||
raise serializers.ValidationError({
|
||||
'content_type': f'Target model "{content_type.app_label}.{content_type.model}" is not allowed for Activity association.'
|
||||
})
|
||||
|
||||
model_cls = content_type.model_class()
|
||||
if model_cls is None:
|
||||
raise serializers.ValidationError({'content_type': 'Invalid content type.'})
|
||||
|
||||
request = self.context.get('request')
|
||||
user = getattr(request, 'user', None) if request else None
|
||||
|
||||
qs = model_cls.objects.all()
|
||||
if user and user.is_authenticated and not (user.is_superuser or user.is_staff):
|
||||
if hasattr(model_cls, 'owner'):
|
||||
qs = qs.filter(owner=user)
|
||||
elif hasattr(model_cls, 'created_by'):
|
||||
qs = qs.filter(created_by=user)
|
||||
elif hasattr(model_cls, 'assigned_to'):
|
||||
qs = qs.filter(assigned_to=user)
|
||||
else:
|
||||
# Default-deny for models without tenant ownership fields
|
||||
raise serializers.ValidationError({
|
||||
'content_type': f'Target model "{content_type.app_label}.{content_type.model}" has no tenant ownership mapping.'
|
||||
})
|
||||
|
||||
if not qs.filter(id=object_id).exists():
|
||||
raise serializers.ValidationError({
|
||||
'object_id': f'Invalid pk "{object_id}" - object does not exist or unauthorized.'
|
||||
})
|
||||
|
||||
return attrs
|
||||
|
||||
|
||||
class LeadConvertSerializer(serializers.Serializer):
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
from decimal import Decimal
|
||||
from django.db import transaction, models
|
||||
from rest_framework import viewsets, status
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.exceptions import ValidationError
|
||||
|
||||
from .models import Account, Contact, Lead, Opportunity, Activity
|
||||
from .serializers import (
|
||||
|
|
@ -11,29 +11,63 @@ from .serializers import (
|
|||
OpportunitySerializer, ActivitySerializer, LeadConvertSerializer
|
||||
)
|
||||
from .services import convert_lead
|
||||
from openforce.permissions import ScopedOwnerAccessPermission
|
||||
|
||||
|
||||
class AccountViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = Account.objects.all().order_by('-created_at')
|
||||
class ScopedQuerySetMixin:
|
||||
permission_classes = [IsAuthenticated, ScopedOwnerAccessPermission]
|
||||
|
||||
def get_queryset(self):
|
||||
qs = super().get_queryset()
|
||||
user = self.request.user
|
||||
if not user or not user.is_authenticated:
|
||||
return qs.none()
|
||||
if user.is_superuser or user.is_staff:
|
||||
return qs
|
||||
if hasattr(self.queryset.model, 'owner'):
|
||||
return qs.filter(owner=user)
|
||||
if hasattr(self.queryset.model, 'assigned_to'):
|
||||
return qs.filter(assigned_to=user)
|
||||
return qs
|
||||
|
||||
|
||||
class AccountViewSet(ScopedQuerySetMixin, viewsets.ModelViewSet):
|
||||
queryset = Account.objects.all()
|
||||
serializer_class = AccountSerializer
|
||||
search_fields = ['name', 'industry']
|
||||
|
||||
def perform_create(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save(owner=self.request.user)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save()
|
||||
|
||||
|
||||
class ContactViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = Contact.objects.all().order_by('-created_at')
|
||||
class ContactViewSet(ScopedQuerySetMixin, viewsets.ModelViewSet):
|
||||
queryset = Contact.objects.all()
|
||||
serializer_class = ContactSerializer
|
||||
filterset_fields = ['account', 'lead_source']
|
||||
search_fields = ['first_name', 'last_name', 'email']
|
||||
|
||||
def perform_create(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save(owner=self.request.user)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save()
|
||||
|
||||
|
||||
class LeadViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = Lead.objects.all().order_by('-created_at')
|
||||
class LeadViewSet(ScopedQuerySetMixin, viewsets.ModelViewSet):
|
||||
queryset = Lead.objects.all()
|
||||
serializer_class = LeadSerializer
|
||||
filterset_fields = ['status', 'rating']
|
||||
search_fields = ['first_name', 'last_name', 'company', 'email']
|
||||
|
||||
def perform_create(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save(owner=self.request.user)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save()
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='convert')
|
||||
def convert(self, request, pk=None):
|
||||
|
|
@ -42,42 +76,55 @@ class LeadViewSet(viewsets.ModelViewSet):
|
|||
serializer.is_valid(raise_exception=True)
|
||||
validated = serializer.validated_data
|
||||
|
||||
try:
|
||||
account_name = validated.get('account_name') or lead.company
|
||||
create_opportunity = validated.get('create_opportunity', False)
|
||||
opportunity_name = validated.get('opportunity_name') or f"{account_name} - Opportunity"
|
||||
opportunity_amount = validated.get('opportunity_amount')
|
||||
opportunity_close_date = validated.get('opportunity_close_date')
|
||||
|
||||
with transaction.atomic():
|
||||
result = convert_lead(
|
||||
lead=lead,
|
||||
account_name=validated.get('account_name'),
|
||||
create_opportunity=validated.get('create_opportunity', False),
|
||||
opportunity_name=validated.get('opportunity_name'),
|
||||
opportunity_amount=validated.get('opportunity_amount'),
|
||||
opportunity_close_date=validated.get('opportunity_close_date'),
|
||||
account_name=account_name,
|
||||
create_opportunity=create_opportunity,
|
||||
opportunity_name=opportunity_name,
|
||||
opportunity_amount=opportunity_amount,
|
||||
opportunity_close_date=opportunity_close_date,
|
||||
user=request.user
|
||||
)
|
||||
return Response({
|
||||
'account': result['account'].id,
|
||||
'contact': result['contact'].id,
|
||||
'opportunity': result['opportunity'].id if result['opportunity'] else None,
|
||||
'account_id': result['account'].id,
|
||||
'contact_id': result['contact'].id,
|
||||
'opportunity_id': result['opportunity'].id if result['opportunity'] else None,
|
||||
'status': 'converted'
|
||||
}, status=status.HTTP_200_OK)
|
||||
except ValidationError as e:
|
||||
return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
|
||||
except Exception as e:
|
||||
return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
return Response({
|
||||
'account': result['account'].id,
|
||||
'contact': result['contact'].id,
|
||||
'opportunity': result['opportunity'].id if result['opportunity'] else None,
|
||||
'account_id': result['account'].id,
|
||||
'contact_id': result['contact'].id,
|
||||
'opportunity_id': result['opportunity'].id if result['opportunity'] else None,
|
||||
'status': 'converted'
|
||||
}, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class OpportunityViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = Opportunity.objects.all().order_by('-close_date')
|
||||
class OpportunityViewSet(ScopedQuerySetMixin, viewsets.ModelViewSet):
|
||||
queryset = Opportunity.objects.all()
|
||||
serializer_class = OpportunitySerializer
|
||||
filterset_fields = ['stage', 'account']
|
||||
search_fields = ['name']
|
||||
|
||||
def perform_create(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save(owner=self.request.user)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save()
|
||||
|
||||
|
||||
class ActivityViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = Activity.objects.all().order_by('-due_date')
|
||||
class ActivityViewSet(ScopedQuerySetMixin, viewsets.ModelViewSet):
|
||||
queryset = Activity.objects.all()
|
||||
serializer_class = ActivitySerializer
|
||||
filterset_fields = ['activity_type', 'status', 'priority']
|
||||
search_fields = ['subject', 'description']
|
||||
|
||||
def perform_create(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save(assigned_to=self.request.user)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save()
|
||||
|
|
|
|||
|
|
@ -3,7 +3,24 @@ from .models import CustomObjectDefinition, CustomFieldDefinition, CustomRecord
|
|||
from .schema_engine import validate_record_data
|
||||
|
||||
|
||||
class CustomFieldDefinitionSerializer(serializers.ModelSerializer):
|
||||
class OwnerScopedRelationMixin:
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
request = self.context.get('request')
|
||||
if request and hasattr(request, 'user') and request.user.is_authenticated:
|
||||
user = request.user
|
||||
if not (user.is_superuser or user.is_staff):
|
||||
for field_name, field in self.fields.items():
|
||||
if isinstance(field, serializers.PrimaryKeyRelatedField):
|
||||
model = getattr(field.queryset, 'model', None)
|
||||
if model:
|
||||
if hasattr(model, 'owner'):
|
||||
field.queryset = field.queryset.filter(owner=user)
|
||||
elif hasattr(model, 'created_by'):
|
||||
field.queryset = field.queryset.filter(created_by=user)
|
||||
|
||||
|
||||
class CustomFieldDefinitionSerializer(OwnerScopedRelationMixin, serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = CustomFieldDefinition
|
||||
fields = '__all__'
|
||||
|
|
@ -16,14 +33,14 @@ class CustomObjectDefinitionSerializer(serializers.ModelSerializer):
|
|||
class Meta:
|
||||
model = CustomObjectDefinition
|
||||
fields = '__all__'
|
||||
read_only_fields = ['id', 'created_at', 'updated_at']
|
||||
read_only_fields = ['id', 'created_by', 'created_at', 'updated_at']
|
||||
|
||||
|
||||
class CustomRecordSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = CustomRecord
|
||||
fields = '__all__'
|
||||
read_only_fields = ['id', 'custom_object', 'created_at', 'updated_at']
|
||||
read_only_fields = ['id', 'custom_object', 'owner', 'created_at', 'updated_at']
|
||||
|
||||
def validate(self, attrs):
|
||||
view = self.context.get('view')
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
from django.db import models
|
||||
from django.db import models, transaction
|
||||
from rest_framework import viewsets, status
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.exceptions import NotFound
|
||||
from rest_framework.exceptions import NotFound, PermissionDenied
|
||||
|
||||
from .models import CustomObjectDefinition, CustomFieldDefinition, CustomRecord
|
||||
from .serializers import (
|
||||
|
|
@ -10,23 +9,57 @@ from .serializers import (
|
|||
CustomFieldDefinitionSerializer,
|
||||
CustomRecordSerializer
|
||||
)
|
||||
from openforce.permissions import ScopedOwnerAccessPermission
|
||||
|
||||
|
||||
class CustomObjectDefinitionViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = CustomObjectDefinition.objects.all().order_by('label')
|
||||
permission_classes = [ScopedOwnerAccessPermission]
|
||||
queryset = CustomObjectDefinition.objects.all()
|
||||
serializer_class = CustomObjectDefinitionSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
qs = super().get_queryset()
|
||||
user = self.request.user
|
||||
if not user or not user.is_authenticated:
|
||||
return qs.none()
|
||||
if user.is_superuser or user.is_staff:
|
||||
return qs
|
||||
return qs.filter(created_by=user)
|
||||
|
||||
def perform_create(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save(created_by=self.request.user)
|
||||
|
||||
|
||||
class CustomFieldDefinitionViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = CustomFieldDefinition.objects.all().order_by('name')
|
||||
permission_classes = [ScopedOwnerAccessPermission]
|
||||
queryset = CustomFieldDefinition.objects.all()
|
||||
serializer_class = CustomFieldDefinitionSerializer
|
||||
filterset_fields = ['custom_object']
|
||||
|
||||
def get_queryset(self):
|
||||
qs = super().get_queryset()
|
||||
user = self.request.user
|
||||
if not user or not user.is_authenticated:
|
||||
return qs.none()
|
||||
if user.is_superuser or user.is_staff:
|
||||
return qs
|
||||
return qs.filter(
|
||||
models.Q(custom_object__created_by=user) | models.Q(entity_name__isnull=False)
|
||||
)
|
||||
|
||||
def perform_create(self, serializer):
|
||||
with transaction.atomic():
|
||||
# Validate that if custom_object is supplied, user owns it
|
||||
obj = serializer.validated_data.get('custom_object')
|
||||
user = self.request.user
|
||||
if obj and not (user.is_superuser or user.is_staff):
|
||||
if obj.created_by and obj.created_by != user:
|
||||
raise PermissionDenied("Cannot add fields to another user's custom object.")
|
||||
serializer.save()
|
||||
|
||||
|
||||
class CustomRecordViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
permission_classes = [IsAuthenticated, ScopedOwnerAccessPermission]
|
||||
serializer_class = CustomRecordSerializer
|
||||
|
||||
def get_custom_object(self):
|
||||
|
|
@ -40,8 +73,17 @@ class CustomRecordViewSet(viewsets.ModelViewSet):
|
|||
|
||||
def get_queryset(self):
|
||||
custom_object = self.get_custom_object()
|
||||
return CustomRecord.objects.filter(custom_object=custom_object).order_by('-created_at')
|
||||
user = self.request.user
|
||||
qs = CustomRecord.objects.filter(custom_object=custom_object)
|
||||
if user.is_superuser or user.is_staff:
|
||||
return qs
|
||||
return qs.filter(owner=user)
|
||||
|
||||
def perform_create(self, serializer):
|
||||
custom_object = self.get_custom_object()
|
||||
serializer.save(custom_object=custom_object, owner=self.request.user)
|
||||
with transaction.atomic():
|
||||
custom_object = self.get_custom_object()
|
||||
serializer.save(custom_object=custom_object, owner=self.request.user)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save()
|
||||
|
|
|
|||
10
entrypoint.sh
Executable file
10
entrypoint.sh
Executable file
|
|
@ -0,0 +1,10 @@
|
|||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# Run database migrations
|
||||
echo "Running database migrations..."
|
||||
python manage.py migrate --noinput
|
||||
|
||||
# Start Gunicorn server
|
||||
echo "Starting Gunicorn server..."
|
||||
exec gunicorn --bind 0.0.0.0:8000 --workers 3 --timeout 120 openforce.wsgi:application
|
||||
|
|
@ -144,6 +144,37 @@ export const useCrmStore = defineStore('crm', {
|
|||
},
|
||||
async createCampaign(campaignData) {
|
||||
const res = await api.post('/campaigns/', campaignData)
|
||||
const campaignId = res.data.id
|
||||
|
||||
// Auto-populate recipients from target object (Leads or Contacts) if store has them
|
||||
let recipients = []
|
||||
if (campaignData.target_object === 'Lead' && this.leads.length > 0) {
|
||||
recipients = this.leads.filter(l => l.email).map(l => ({
|
||||
email: l.email,
|
||||
first_name: l.first_name || '',
|
||||
last_name: l.last_name || '',
|
||||
merge_data: { first_name: l.first_name, company: l.company }
|
||||
}))
|
||||
} else if (campaignData.target_object === 'Contact' && this.contacts.length > 0) {
|
||||
recipients = this.contacts.filter(c => c.email).map(c => ({
|
||||
email: c.email,
|
||||
first_name: c.first_name || '',
|
||||
last_name: c.last_name || '',
|
||||
merge_data: { first_name: c.first_name }
|
||||
}))
|
||||
}
|
||||
|
||||
if (recipients.length > 0) {
|
||||
await api.post(`/campaigns/${campaignId}/add-recipients/`, { recipients })
|
||||
}
|
||||
|
||||
// Auto-dispatch campaign
|
||||
try {
|
||||
await api.post(`/campaigns/${campaignId}/dispatch/`)
|
||||
} catch (err) {
|
||||
console.warn('Dispatch failed or pending:', err)
|
||||
}
|
||||
|
||||
await this.fetchCampaigns()
|
||||
return res.data
|
||||
},
|
||||
|
|
|
|||
|
|
@ -36,10 +36,11 @@
|
|||
</button>
|
||||
<button
|
||||
@click="runFlow"
|
||||
:disabled="isRunning"
|
||||
:disabled="isRunning || !currentFlowId"
|
||||
:title="!currentFlowId ? 'Please save the flow before running' : 'Run Flow'"
|
||||
class="px-4 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-semibold rounded-md shadow-sm transition disabled:opacity-50"
|
||||
>
|
||||
{{ isRunning ? 'Running...' : 'Run Flow' }}
|
||||
{{ isRunning ? 'Running...' : (currentFlowId ? `Run Flow (#${currentFlowId})` : 'Run Flow (Save First)') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -73,6 +74,9 @@
|
|||
</div>
|
||||
<div class="flex-1 p-4 overflow-y-auto space-y-4">
|
||||
<div v-if="executionResult" class="space-y-3">
|
||||
<div v-if="executionResult.error" class="bg-rose-50 border border-rose-200 text-rose-800 text-xs p-2.5 rounded-md">
|
||||
<span class="font-bold">Error:</span> {{ executionResult.error }}
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-xs text-slate-500 font-medium">Steps Executed:</span>
|
||||
<div class="mt-1 flex flex-wrap gap-1">
|
||||
|
|
@ -108,6 +112,7 @@ import api from '../api'
|
|||
|
||||
const isSaving = ref(false)
|
||||
const isRunning = ref(false)
|
||||
const currentFlowId = ref(null)
|
||||
const executionResult = ref(null)
|
||||
|
||||
const nodes = ref([
|
||||
|
|
@ -238,8 +243,14 @@ async function saveFlow() {
|
|||
edges: edges.value
|
||||
}
|
||||
}
|
||||
await api.post('/workflows/', payload)
|
||||
alert('Workflow graph saved successfully!')
|
||||
let res
|
||||
if (currentFlowId.value) {
|
||||
res = await api.put(`/workflows/${currentFlowId.value}/`, payload)
|
||||
} else {
|
||||
res = await api.post('/workflows/', payload)
|
||||
currentFlowId.value = res.data.id
|
||||
}
|
||||
alert(`Workflow graph saved successfully! (ID: ${currentFlowId.value})`)
|
||||
} catch (err) {
|
||||
console.error('Failed to save workflow:', err)
|
||||
alert('Failed to save workflow: ' + (err.response?.data?.message || err.message))
|
||||
|
|
@ -249,9 +260,19 @@ async function saveFlow() {
|
|||
}
|
||||
|
||||
async function runFlow() {
|
||||
if (!currentFlowId.value) {
|
||||
executionResult.value = {
|
||||
status: 'failed',
|
||||
error: 'Cannot run flow: flow must be saved before execution. Please click "Save Flow".',
|
||||
steps_executed: [],
|
||||
context_data: {}
|
||||
}
|
||||
return
|
||||
}
|
||||
isRunning.value = true
|
||||
try {
|
||||
const res = await api.post('/workflows/1/execute/', {
|
||||
const flowId = currentFlowId.value
|
||||
const res = await api.post(`/workflows/${flowId}/execute/`, {
|
||||
context: {
|
||||
record: { id: 101, name: 'Acme Corp', amount: 75000 },
|
||||
amount: 75000
|
||||
|
|
@ -262,7 +283,7 @@ async function runFlow() {
|
|||
console.error('Execute API error:', err)
|
||||
executionResult.value = {
|
||||
status: 'failed',
|
||||
error: err.response?.data?.detail || err.message || 'Execution failed',
|
||||
error: err.response?.data?.error || err.response?.data?.detail || err.message || 'Execution failed',
|
||||
steps_executed: [],
|
||||
context_data: {}
|
||||
}
|
||||
|
|
|
|||
108
k8s.yaml
Normal file
108
k8s.yaml
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: openforce
|
||||
namespace: default
|
||||
labels:
|
||||
app: openforce
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: openforce
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: openforce
|
||||
spec:
|
||||
containers:
|
||||
- name: openforce
|
||||
image: git.ch4t.buzz/buzzparty/openforce:latest
|
||||
imagePullPolicy: Always
|
||||
ports:
|
||||
- containerPort: 8000
|
||||
name: http
|
||||
env:
|
||||
- name: DJANGO_SETTINGS_MODULE
|
||||
value: "openforce.settings.prod"
|
||||
- name: DJANGO_SECRET_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: openforce-secret
|
||||
key: DJANGO_SECRET_KEY
|
||||
optional: true
|
||||
- name: SQLITE_DB_PATH
|
||||
value: "/app/data/db.sqlite3"
|
||||
volumeMounts:
|
||||
- name: openforce-data
|
||||
mountPath: /app/data
|
||||
resources:
|
||||
requests:
|
||||
memory: "256Mi"
|
||||
cpu: "100m"
|
||||
limits:
|
||||
memory: "512Mi"
|
||||
cpu: "500m"
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /
|
||||
port: 8000
|
||||
httpHeaders:
|
||||
- name: Host
|
||||
value: crm.ch4t.buzz
|
||||
initialDelaySeconds: 10
|
||||
periodSeconds: 10
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /
|
||||
port: 8000
|
||||
httpHeaders:
|
||||
- name: Host
|
||||
value: crm.ch4t.buzz
|
||||
initialDelaySeconds: 15
|
||||
periodSeconds: 20
|
||||
volumes:
|
||||
- name: openforce-data
|
||||
emptyDir: {}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: openforce
|
||||
namespace: default
|
||||
labels:
|
||||
app: openforce
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
- port: 80
|
||||
targetPort: 8000
|
||||
protocol: TCP
|
||||
name: http
|
||||
selector:
|
||||
app: openforce
|
||||
---
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: openforce
|
||||
namespace: default
|
||||
annotations:
|
||||
cert-manager.io/cluster-issuer: letsencrypt-prod
|
||||
spec:
|
||||
ingressClassName: traefik
|
||||
rules:
|
||||
- host: crm.ch4t.buzz
|
||||
http:
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: openforce
|
||||
port:
|
||||
number: 80
|
||||
tls:
|
||||
- hosts:
|
||||
- crm.ch4t.buzz
|
||||
secretName: openforce-tls
|
||||
5
openforce/asgi.py
Normal file
5
openforce/asgi.py
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import os
|
||||
from django.core.asgi import get_asgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', os.environ.get('DJANGO_SETTINGS_MODULE', 'openforce.settings.prod'))
|
||||
application = get_asgi_application()
|
||||
32
openforce/permissions.py
Normal file
32
openforce/permissions.py
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
from rest_framework import permissions
|
||||
|
||||
class ScopedOwnerAccessPermission(permissions.BasePermission):
|
||||
"""
|
||||
Enforces that non-superuser/non-staff users can only access records they own.
|
||||
Superusers/staff have administrative access across all records.
|
||||
Default-denies access if object ownership is absent or not matched.
|
||||
"""
|
||||
def has_permission(self, request, view):
|
||||
return request.user and request.user.is_authenticated
|
||||
|
||||
def has_object_permission(self, request, view, obj):
|
||||
user = request.user
|
||||
if user.is_superuser or user.is_staff:
|
||||
return True
|
||||
owner = getattr(obj, 'owner', None)
|
||||
if owner is not None:
|
||||
return owner == user
|
||||
assigned = getattr(obj, 'assigned_to', None)
|
||||
if assigned is not None:
|
||||
return assigned == user
|
||||
created_by = getattr(obj, 'created_by', None)
|
||||
if created_by is not None:
|
||||
return created_by == user
|
||||
# In CustomFieldDefinition, check custom_object's creator
|
||||
custom_obj = getattr(obj, 'custom_object', None)
|
||||
if custom_obj is not None:
|
||||
c_created_by = getattr(custom_obj, 'created_by', None)
|
||||
if c_created_by is not None:
|
||||
return c_created_by == user
|
||||
# Default-deny if no ownership fields exist or if unowned
|
||||
return False
|
||||
|
|
@ -33,6 +33,16 @@ MIDDLEWARE = [
|
|||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
]
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_AUTHENTICATION_CLASSES': [
|
||||
'rest_framework.authentication.SessionAuthentication',
|
||||
'rest_framework.authentication.BasicAuthentication',
|
||||
],
|
||||
'DEFAULT_PERMISSION_CLASSES': [
|
||||
'rest_framework.permissions.IsAuthenticated',
|
||||
],
|
||||
}
|
||||
|
||||
CORS_ALLOW_ALL_ORIGINS = True
|
||||
|
||||
ROOT_URLCONF = 'openforce.urls'
|
||||
|
|
@ -59,6 +69,7 @@ DATABASES = {
|
|||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': BASE_DIR / 'db.sqlite3',
|
||||
'ATOMIC_REQUESTS': True,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
43
openforce/settings/prod.py
Normal file
43
openforce/settings/prod.py
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import os
|
||||
from .base import *
|
||||
|
||||
DEBUG = False
|
||||
|
||||
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'insecure-prod-key-override-via-env')
|
||||
|
||||
ALLOWED_HOSTS = [
|
||||
'crm.ch4t.buzz',
|
||||
'localhost',
|
||||
'127.0.0.1',
|
||||
]
|
||||
|
||||
# CSRF & Security Headers
|
||||
CSRF_TRUSTED_ORIGINS = [
|
||||
'https://crm.ch4t.buzz',
|
||||
]
|
||||
|
||||
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
|
||||
SECURE_SSL_REDIRECT = os.environ.get('SECURE_SSL_REDIRECT', 'false').lower() in ('true', '1')
|
||||
SESSION_COOKIE_SECURE = True
|
||||
CSRF_COOKIE_SECURE = True
|
||||
SECURE_BROWSER_XSS_FILTER = True
|
||||
SECURE_CONTENT_TYPE_NOSNIFF = True
|
||||
X_FRAME_OPTIONS = 'DENY'
|
||||
|
||||
# Database configuration: support SQLite persistent volume or PostgreSQL via env
|
||||
DATABASE_URL = os.environ.get('DATABASE_URL')
|
||||
if DATABASE_URL:
|
||||
import dj_database_url # optional if installed
|
||||
DATABASES = {
|
||||
'default': dj_database_url.config(default=DATABASE_URL, conn_max_age=600)
|
||||
}
|
||||
else:
|
||||
DB_PATH = os.environ.get('SQLITE_DB_PATH', str(BASE_DIR / 'data' / 'db.sqlite3'))
|
||||
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': DB_PATH,
|
||||
'ATOMIC_REQUESTS': True,
|
||||
}
|
||||
}
|
||||
|
|
@ -8,6 +8,7 @@ DATABASES = {
|
|||
'PASSWORD': 'openforce',
|
||||
'HOST': 'localhost',
|
||||
'PORT': '5432',
|
||||
'ATOMIC_REQUESTS': True,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -16,3 +17,5 @@ PASSWORD_HASHERS = [
|
|||
]
|
||||
|
||||
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
|
||||
|
||||
ALLOWED_HOSTS = ['*']
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import os
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'openforce.settings.base')
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', os.environ.get('DJANGO_SETTINGS_MODULE', 'openforce.settings.prod'))
|
||||
application = get_wsgi_application()
|
||||
|
|
|
|||
|
|
@ -0,0 +1,22 @@
|
|||
# Generated by Django 4.2.30 on 2026-09-26 22:26
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('outreach', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='emailtemplate',
|
||||
name='name',
|
||||
field=models.CharField(max_length=255),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='emailtemplate',
|
||||
constraint=models.UniqueConstraint(condition=models.Q(('created_by__isnull', False)), fields=('created_by', 'name'), name='unique_template_name_per_user'),
|
||||
),
|
||||
]
|
||||
|
|
@ -8,7 +8,7 @@ User = get_user_model()
|
|||
|
||||
|
||||
class EmailTemplate(models.Model):
|
||||
name = models.CharField(max_length=255, unique=True)
|
||||
name = models.CharField(max_length=255)
|
||||
subject = models.CharField(max_length=255)
|
||||
body_html = models.TextField(help_text="HTML content supporting merge tags like {{first_name}}")
|
||||
body_text = models.TextField(blank=True, default='')
|
||||
|
|
@ -17,6 +17,15 @@ class EmailTemplate(models.Model):
|
|||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=['created_by', 'name'],
|
||||
name='unique_template_name_per_user',
|
||||
condition=models.Q(created_by__isnull=False)
|
||||
)
|
||||
]
|
||||
|
||||
def render(self, context):
|
||||
"""
|
||||
Safely renders template variables with {{var_name}} merge tags.
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
from rest_framework import serializers
|
||||
from crm_core.serializers import OwnerScopedRelationMixin
|
||||
from .models import EmailTemplate, Campaign, CampaignRecipient
|
||||
|
||||
|
||||
|
|
@ -6,7 +7,7 @@ class EmailTemplateSerializer(serializers.ModelSerializer):
|
|||
class Meta:
|
||||
model = EmailTemplate
|
||||
fields = '__all__'
|
||||
read_only_fields = ['id', 'created_at', 'updated_at']
|
||||
read_only_fields = ['id', 'created_by', 'created_at', 'updated_at']
|
||||
|
||||
|
||||
class CampaignRecipientSerializer(serializers.ModelSerializer):
|
||||
|
|
@ -16,10 +17,49 @@ class CampaignRecipientSerializer(serializers.ModelSerializer):
|
|||
read_only_fields = ['id', 'tracking_token', 'sent_at', 'opened_at', 'clicked_at']
|
||||
|
||||
|
||||
class CampaignSerializer(serializers.ModelSerializer):
|
||||
class CampaignSerializer(OwnerScopedRelationMixin, serializers.ModelSerializer):
|
||||
recipients = CampaignRecipientSerializer(many=True, read_only=True)
|
||||
template = serializers.PrimaryKeyRelatedField(
|
||||
queryset=EmailTemplate.objects.all(),
|
||||
required=False,
|
||||
allow_null=True
|
||||
)
|
||||
subject = serializers.CharField(write_only=True, required=False, allow_blank=True)
|
||||
sent_count = serializers.SerializerMethodField()
|
||||
open_count = serializers.SerializerMethodField()
|
||||
click_count = serializers.SerializerMethodField()
|
||||
|
||||
class Meta:
|
||||
model = Campaign
|
||||
fields = '__all__'
|
||||
read_only_fields = ['id', 'created_at', 'updated_at']
|
||||
read_only_fields = ['id', 'created_by', 'status', 'sent_at', 'created_at', 'updated_at']
|
||||
|
||||
def create(self, validated_data):
|
||||
user_subject = validated_data.pop('subject', None)
|
||||
template = validated_data.get('template')
|
||||
if not template:
|
||||
# Fallback or create a default template matching campaign subject/name scoped to user
|
||||
name = validated_data.get('name', 'Default Campaign')
|
||||
subject = user_subject or name
|
||||
request = self.context.get('request')
|
||||
created_by = request.user if request and request.user and request.user.is_authenticated else None
|
||||
template, _ = EmailTemplate.objects.get_or_create(
|
||||
name=f"{name} Template",
|
||||
created_by=created_by,
|
||||
defaults={
|
||||
'subject': subject,
|
||||
'body_html': '<p>Hello {{first_name}},</p><p>We are reaching out to you regarding your account.</p>',
|
||||
'body_text': 'Hello {{first_name}},\nWe are reaching out to you regarding your account.',
|
||||
}
|
||||
)
|
||||
validated_data['template'] = template
|
||||
return super().create(validated_data)
|
||||
|
||||
def get_sent_count(self, obj):
|
||||
return obj.recipients.filter(status__in=['sent', 'delivered', 'opened', 'clicked']).count()
|
||||
|
||||
def get_open_count(self, obj):
|
||||
return obj.recipients.filter(status__in=['opened', 'clicked']).count()
|
||||
|
||||
def get_click_count(self, obj):
|
||||
return obj.recipients.filter(status='clicked').count()
|
||||
|
|
|
|||
|
|
@ -1,35 +1,69 @@
|
|||
import base64
|
||||
from django.http import HttpResponse
|
||||
from django.utils import timezone
|
||||
from rest_framework import viewsets, status
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.permissions import IsAuthenticated, AllowAny
|
||||
from django.db import models
|
||||
from django.http import HttpResponse
|
||||
|
||||
from .models import EmailTemplate, Campaign, CampaignRecipient
|
||||
from .serializers import EmailTemplateSerializer, CampaignSerializer, CampaignRecipientSerializer
|
||||
from .serializers import (
|
||||
EmailTemplateSerializer, CampaignSerializer, CampaignRecipientSerializer
|
||||
)
|
||||
from .engine import dispatch_campaign
|
||||
from openforce.permissions import ScopedOwnerAccessPermission
|
||||
|
||||
# 1x1 transparent GIF in binary format
|
||||
PIXEL_GIF_BYTES = base64.b64decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')
|
||||
|
||||
|
||||
class EmailTemplateViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = EmailTemplate.objects.all().order_by('-created_at')
|
||||
permission_classes = [IsAuthenticated, ScopedOwnerAccessPermission]
|
||||
queryset = EmailTemplate.objects.all()
|
||||
serializer_class = EmailTemplateSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
qs = super().get_queryset()
|
||||
user = self.request.user
|
||||
if not user or not user.is_authenticated:
|
||||
return qs
|
||||
if user.is_superuser or user.is_staff:
|
||||
return qs
|
||||
if hasattr(EmailTemplate, 'created_by'):
|
||||
return qs.filter(created_by=user)
|
||||
return qs
|
||||
|
||||
def perform_create(self, serializer):
|
||||
kwargs = {}
|
||||
if hasattr(EmailTemplate, 'created_by'):
|
||||
kwargs['created_by'] = self.request.user
|
||||
serializer.save(**kwargs)
|
||||
|
||||
|
||||
class CampaignViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = Campaign.objects.all().order_by('-created_at')
|
||||
permission_classes = [IsAuthenticated, ScopedOwnerAccessPermission]
|
||||
queryset = Campaign.objects.all()
|
||||
serializer_class = CampaignSerializer
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='dispatch')
|
||||
def dispatch_now(self, request, pk=None):
|
||||
campaign = self.get_object()
|
||||
sent_count = dispatch_campaign(campaign.id)
|
||||
return Response({'status': 'dispatched', 'sent_count': sent_count}, status=status.HTTP_200_OK)
|
||||
def get_queryset(self):
|
||||
qs = super().get_queryset()
|
||||
user = self.request.user
|
||||
if not user or not user.is_authenticated:
|
||||
return qs
|
||||
if user.is_superuser or user.is_staff:
|
||||
return qs
|
||||
if hasattr(Campaign, 'created_by'):
|
||||
return qs.filter(created_by=user)
|
||||
return qs
|
||||
|
||||
def perform_create(self, serializer):
|
||||
kwargs = {}
|
||||
if hasattr(Campaign, 'created_by'):
|
||||
kwargs['created_by'] = self.request.user
|
||||
serializer.save(**kwargs)
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='add-recipients')
|
||||
def add_recipients(self, request, pk=None):
|
||||
|
|
@ -45,17 +79,30 @@ class CampaignViewSet(viewsets.ModelViewSet):
|
|||
created.append(rec)
|
||||
return Response({'count': len(created)}, status=status.HTTP_201_CREATED)
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='dispatch')
|
||||
def dispatch_action(self, request, pk=None):
|
||||
campaign = self.get_object()
|
||||
dispatched_count = dispatch_campaign(campaign.id)
|
||||
return Response({
|
||||
'status': 'dispatched',
|
||||
'dispatched_count': dispatched_count,
|
||||
'sent_count': dispatched_count,
|
||||
'campaign_id': campaign.id
|
||||
}, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class TrackEmailOpenView(APIView):
|
||||
permission_classes = [AllowAny]
|
||||
|
||||
def get(self, request, token=None):
|
||||
try:
|
||||
recipient = CampaignRecipient.objects.get(tracking_token=token)
|
||||
if not recipient.opened_at:
|
||||
recipient.opened_at = timezone.now()
|
||||
recipient.status = 'opened'
|
||||
recipient.save(update_fields=['opened_at', 'status'])
|
||||
except CampaignRecipient.DoesNotExist:
|
||||
pass
|
||||
if token:
|
||||
now = timezone.now()
|
||||
# Update opened_at and advance status to 'opened' if not already opened/clicked
|
||||
recipients = CampaignRecipient.objects.filter(tracking_token=token)
|
||||
for recipient in recipients:
|
||||
if not recipient.opened_at:
|
||||
recipient.opened_at = now
|
||||
if recipient.status in ('pending', 'sent', 'delivered'):
|
||||
recipient.status = 'opened'
|
||||
recipient.save()
|
||||
return HttpResponse(PIXEL_GIF_BYTES, content_type='image/gif')
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ psycopg2-binary>=2.9
|
|||
jsonschema>=4.0
|
||||
django-cors-headers>=4.0
|
||||
whitenoise>=6.5
|
||||
gunicorn>=21.2.0
|
||||
pytest>=7.0
|
||||
pytest-django>=4.5
|
||||
pytest-cov>=4.0
|
||||
|
|
|
|||
|
|
@ -60,3 +60,10 @@ def test_diamond_rejoin_execution():
|
|||
assert ctx.get("executed_a") is True, "Branch A should have executed"
|
||||
assert ctx.get("executed_b") is not True, "Branch B must NEVER execute"
|
||||
assert ctx.get("executed_join") is True, "Diamond join node MUST execute when reached via Branch A"
|
||||
|
||||
# Opposite branch test: status == 'B'
|
||||
result_b = execute_flow_dag(graph, initial_context={"status": "B"})
|
||||
ctx_b = result_b if isinstance(result_b, dict) else result_b.context
|
||||
assert ctx_b.get("executed_b") is True, "Branch B should have executed when status is B"
|
||||
assert ctx_b.get("executed_a") is not True, "Branch A must NEVER execute when status is B"
|
||||
assert ctx_b.get("executed_join") is True, "Diamond join node MUST execute when reached via Branch B"
|
||||
|
|
|
|||
|
|
@ -1,19 +1,19 @@
|
|||
import pytest
|
||||
from django.db import transaction
|
||||
from rest_framework.test import APIClient
|
||||
from django.contrib.auth.models import User
|
||||
from crm_core.models import Account
|
||||
from workflows.models import FlowDefinition
|
||||
|
||||
@pytest.mark.django_db(transaction=True)
|
||||
def test_flow_failure_rolls_back_triggering_record():
|
||||
def test_flow_failure_rolls_back_account_via_viewset_endpoint():
|
||||
"""
|
||||
Test that an active record-triggered flow failure rolls back the triggering record
|
||||
outside of implicit test transactions.
|
||||
when calling the AccountViewSet POST endpoint directly, WITHOUT any manual transaction.atomic wrapper in test!
|
||||
"""
|
||||
# Create an active flow that intentionally fails
|
||||
failing_dag = {
|
||||
"nodes": [
|
||||
{"id": "start", "type": "trigger", "data": {}},
|
||||
{"id": "step_fail", "type": "subflow", "data": {"flow_id": 999999}} # Will raise ValidationError
|
||||
{"id": "step_fail", "type": "subflow", "data": {"flow_id": 999999}}
|
||||
],
|
||||
"edges": [
|
||||
{"source": "start", "target": "step_fail"}
|
||||
|
|
@ -27,12 +27,15 @@ def test_flow_failure_rolls_back_triggering_record():
|
|||
graph=failing_dag
|
||||
)
|
||||
|
||||
account_name = "Doomed Transaction Account"
|
||||
# Attempt to create Account in an atomic block
|
||||
with pytest.raises(Exception):
|
||||
with transaction.atomic():
|
||||
Account.objects.create(name=account_name)
|
||||
user = User.objects.create_user(username="test_rollback_user", password="password")
|
||||
client = APIClient()
|
||||
client.force_authenticate(user=user)
|
||||
|
||||
# Verify that the Account was rolled back and does not exist in the database
|
||||
account_name = "Doomed Endpoint Account"
|
||||
# Call the actual DRF endpoint without any transaction wrapper in the test
|
||||
with pytest.raises(Exception):
|
||||
client.post('/api/accounts/', {'name': account_name}, format='json')
|
||||
|
||||
# Verify that the Account was rolled back and does not exist in the database!
|
||||
exists = Account.objects.filter(name=account_name).exists()
|
||||
assert not exists, "Account creation MUST be rolled back when record-triggered flow fails!"
|
||||
assert not exists, "Account creation via API endpoint MUST roll back when record-triggered flow fails!"
|
||||
|
|
|
|||
|
|
@ -14,45 +14,61 @@ def test_vue_flow_initial_graph_executes_successfully():
|
|||
{
|
||||
"id": "start-trigger",
|
||||
"type": "input",
|
||||
"data": {"type": "trigger"}
|
||||
"label": "⚡ Trigger: Account Created",
|
||||
"position": {"x": 100, "y": 150},
|
||||
"class": "bg-emerald-600 text-white font-semibold text-xs p-3 rounded-lg shadow-md border-0"
|
||||
},
|
||||
{
|
||||
"id": "decision-tier",
|
||||
"type": "decision",
|
||||
"label": "⚖️ Decision: VIP Tier Check",
|
||||
"position": {"x": 340, "y": 150},
|
||||
"data": {
|
||||
"type": "decision",
|
||||
"conditions": [
|
||||
{"field": "amount", "op": "gte", "value": 50000, "target_node": "assign-vip"},
|
||||
{"field": "amount", "op": "gte", "value": 10000, "target_node": "assign-standard"}
|
||||
],
|
||||
"default_target": "assign-standard"
|
||||
}
|
||||
},
|
||||
"class": "bg-indigo-600 text-white font-semibold text-xs p-3 rounded-lg shadow-md border-0"
|
||||
},
|
||||
{
|
||||
"id": "assign-vip",
|
||||
"type": "assignment",
|
||||
"label": "💎 Assignment: VIP Customer",
|
||||
"position": {"x": 600, "y": 80},
|
||||
"data": {
|
||||
"type": "assignment",
|
||||
"assignments": [
|
||||
{"variable": "account_tier", "op": "equals", "value": "VIP"},
|
||||
{"variable": "priority_score", "op": "add", "value": 100}
|
||||
]
|
||||
}
|
||||
},
|
||||
"class": "bg-blue-600 text-white font-semibold text-xs p-3 rounded-lg shadow-md border-0"
|
||||
},
|
||||
{
|
||||
"id": "assign-standard",
|
||||
"type": "assignment",
|
||||
"label": "📦 Assignment: Standard Customer",
|
||||
"position": {"x": 600, "y": 220},
|
||||
"data": {
|
||||
"type": "assignment",
|
||||
"assignments": [
|
||||
{"variable": "account_tier", "op": "equals", "value": "Standard"},
|
||||
{"variable": "priority_score", "op": "add", "value": 10}
|
||||
]
|
||||
}
|
||||
},
|
||||
"class": "bg-slate-600 text-white font-semibold text-xs p-3 rounded-lg shadow-md border-0"
|
||||
},
|
||||
{
|
||||
"id": "subflow-sync",
|
||||
"type": "subflow",
|
||||
"label": "🔄 Subflow: Sync to Billing",
|
||||
"position": {"x": 860, "y": 150},
|
||||
"data": {
|
||||
"subflow_id": subflow.id
|
||||
}
|
||||
"type": "subflow",
|
||||
"subflow_id": subflow.id,
|
||||
"input_mapping": {"customer_id": "record.id"},
|
||||
"output_mapping": {"sync_status": "status"}
|
||||
},
|
||||
"class": "bg-violet-600 text-white font-semibold text-xs p-3 rounded-lg shadow-md border-0"
|
||||
}
|
||||
],
|
||||
"edges": [
|
||||
|
|
|
|||
|
|
@ -90,14 +90,17 @@ class TestSignalReentrancyGuard:
|
|||
],
|
||||
"edges": [{"source": "start", "target": "upd"}],
|
||||
}
|
||||
from django.contrib.auth.models import User
|
||||
system_user, _ = User.objects.get_or_create(username="reentrancy_owner")
|
||||
FlowDefinition.objects.create(
|
||||
name="SelfUpdateFlow",
|
||||
trigger_type="record_updated",
|
||||
trigger_object="Account",
|
||||
is_active=True,
|
||||
created_by=system_user,
|
||||
graph=update_self_dag,
|
||||
)
|
||||
acct = Account.objects.create(name="Original")
|
||||
acct = Account.objects.create(name="Original", owner=system_user)
|
||||
|
||||
# This must complete without RecursionError or hitting Django's recursion limit
|
||||
import threading
|
||||
|
|
|
|||
|
|
@ -21,7 +21,8 @@ class TestOutreachAndWorkflowEndpoints(TestCase):
|
|||
campaign = Campaign.objects.create(
|
||||
name='Summer Campaign',
|
||||
template=template,
|
||||
status='draft'
|
||||
status='draft',
|
||||
created_by=self.user
|
||||
)
|
||||
CampaignRecipient.objects.create(
|
||||
campaign=campaign,
|
||||
|
|
@ -48,6 +49,7 @@ class TestOutreachAndWorkflowEndpoints(TestCase):
|
|||
def test_workflow_execute_api(self):
|
||||
flow = FlowDefinition.objects.create(
|
||||
name='Lead Scoring Flow',
|
||||
created_by=self.user,
|
||||
graph={
|
||||
'nodes': [{'id': 'n1', 'type': 'action', 'data': {'action': 'increment_score', 'points': 10}}],
|
||||
'edges': []
|
||||
|
|
|
|||
|
|
@ -106,3 +106,49 @@ class TestOutreachEngine:
|
|||
assert email2.to == ['bob@example.com']
|
||||
assert email2.subject == 'Special Offer for Bob'
|
||||
assert str(rec2.tracking_token) in email2.alternatives[0][0]
|
||||
|
||||
def test_campaign_launch_modal_payload_and_tracking_open(self):
|
||||
from rest_framework.test import APIClient
|
||||
from django.contrib.auth.models import User
|
||||
user = User.objects.create_user('outreach_user', 'outreach@test.com', 'pw')
|
||||
client = APIClient()
|
||||
client.force_authenticate(user=user)
|
||||
|
||||
# 1. UI payload with only {name, subject, target_object} without explicit template
|
||||
res = client.post('/api/campaigns/', {
|
||||
'name': 'UI Launched Campaign',
|
||||
'subject': 'Special Offer For You',
|
||||
'target_object': 'Lead'
|
||||
}, format='json')
|
||||
assert res.status_code == 201
|
||||
campaign_id = res.data['id']
|
||||
assert res.data['template'] is not None
|
||||
|
||||
# 2. Add recipient
|
||||
add_res = client.post(f'/api/campaigns/{campaign_id}/add-recipients/', {
|
||||
'recipients': [{'email': 'prospect@example.com', 'first_name': 'Prospect'}]
|
||||
}, format='json')
|
||||
assert add_res.status_code == 201
|
||||
assert add_res.data['count'] == 1
|
||||
|
||||
# 3. Dispatch
|
||||
dispatch_res = client.post(f'/api/campaigns/{campaign_id}/dispatch/')
|
||||
assert dispatch_res.status_code == 200
|
||||
|
||||
# Check metrics before open
|
||||
camp_res = client.get(f'/api/campaigns/{campaign_id}/')
|
||||
assert camp_res.data['sent_count'] == 1
|
||||
assert camp_res.data['open_count'] == 0
|
||||
|
||||
# 4. Open tracking pixel
|
||||
recipient = CampaignRecipient.objects.get(campaign_id=campaign_id)
|
||||
open_res = client.get(f'/api/outreach/track/open/{recipient.tracking_token}/')
|
||||
assert open_res.status_code == 200
|
||||
|
||||
recipient.refresh_from_db()
|
||||
assert recipient.opened_at is not None
|
||||
assert recipient.status == 'opened'
|
||||
|
||||
# Check metrics after open
|
||||
camp_res = client.get(f'/api/campaigns/{campaign_id}/')
|
||||
assert camp_res.data['open_count'] == 1
|
||||
|
|
|
|||
726
tests/test_tenant_isolation.py
Normal file
726
tests/test_tenant_isolation.py
Normal file
|
|
@ -0,0 +1,726 @@
|
|||
import pytest
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.contrib.auth.models import User
|
||||
from workflows.engine import execute_flow_dag
|
||||
from rest_framework.test import APIClient
|
||||
from crm_core.models import Account, Contact, Lead, Opportunity
|
||||
from custom_objects.models import CustomObjectDefinition, CustomRecord
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestTenantAccessIsolation:
|
||||
|
||||
def setup_method(self):
|
||||
self.user_a = User.objects.create_user(username='tenant_a', password='password123')
|
||||
self.user_b = User.objects.create_user(username='tenant_b', password='password123')
|
||||
self.client_a = APIClient()
|
||||
self.client_a.force_authenticate(user=self.user_a)
|
||||
self.client_b = APIClient()
|
||||
self.client_b.force_authenticate(user=self.user_b)
|
||||
|
||||
def test_tenant_cannot_read_other_tenant_account(self):
|
||||
acct_a = Account.objects.create(name='Tenant A Account', owner=self.user_a)
|
||||
|
||||
# Tenant A can read
|
||||
res_a = self.client_a.get(f'/api/accounts/{acct_a.id}/')
|
||||
assert res_a.status_code == 200
|
||||
|
||||
# Tenant B gets 404
|
||||
res_b = self.client_b.get(f'/api/accounts/{acct_a.id}/')
|
||||
assert res_b.status_code == 404
|
||||
|
||||
def test_tenant_cannot_update_other_tenant_account(self):
|
||||
acct_a = Account.objects.create(name='Tenant A Account', owner=self.user_a)
|
||||
|
||||
# Tenant B attempts write
|
||||
res_b = self.client_b.patch(f'/api/accounts/{acct_a.id}/', {'name': 'Hacked Name'})
|
||||
assert res_b.status_code == 404
|
||||
acct_a.refresh_from_db()
|
||||
assert acct_a.name == 'Tenant A Account'
|
||||
|
||||
def test_tenant_cannot_read_other_tenant_custom_records(self):
|
||||
obj = CustomObjectDefinition.objects.create(name='Widget__c', label='Widget')
|
||||
rec_a = CustomRecord.objects.create(custom_object=obj, owner=self.user_a, data={'title': 'Secret A'})
|
||||
|
||||
# Tenant A can list and retrieve
|
||||
res_a = self.client_a.get(f'/api/custom/Widget__c/{rec_a.id}/')
|
||||
assert res_a.status_code == 200
|
||||
|
||||
# Tenant B is blocked
|
||||
res_b = self.client_b.get(f'/api/custom/Widget__c/{rec_a.id}/')
|
||||
assert res_b.status_code == 404
|
||||
|
||||
def test_tenant_cannot_update_other_tenant_custom_records(self):
|
||||
obj = CustomObjectDefinition.objects.create(name='Gadget__c', label='Gadget', created_by=self.user_a)
|
||||
rec_a = CustomRecord.objects.create(custom_object=obj, owner=self.user_a, data={'title': 'Protected'})
|
||||
|
||||
res_b = self.client_b.patch(f'/api/custom/Gadget__c/{rec_a.id}/', {'data': {'title': 'Overwritten'}}, format='json')
|
||||
assert res_b.status_code == 404
|
||||
rec_a.refresh_from_db()
|
||||
assert rec_a.data.get('title') == 'Protected'
|
||||
|
||||
def test_tenant_cannot_patch_other_tenant_custom_object_definition(self):
|
||||
obj = CustomObjectDefinition.objects.create(name='Invoice__c', label='Invoice', created_by=self.user_a)
|
||||
res_b = self.client_b.patch(f'/api/custom-objects/{obj.id}/', {'label': 'Hacked Invoice'})
|
||||
assert res_b.status_code == 404
|
||||
obj.refresh_from_db()
|
||||
assert obj.label == 'Invoice'
|
||||
|
||||
def test_tenant_cannot_attach_foreign_relation(self):
|
||||
acct_a = Account.objects.create(name='Tenant A Account', owner=self.user_a)
|
||||
res_b = self.client_b.post('/api/contacts/', {
|
||||
'first_name': 'Sneaky',
|
||||
'last_name': 'Contact',
|
||||
'account': acct_a.id
|
||||
}, format='json')
|
||||
assert res_b.status_code == 400
|
||||
assert 'account' in res_b.data
|
||||
|
||||
def test_tenant_cannot_modify_foreign_record_via_flow_execution(self):
|
||||
from workflows.models import FlowDefinition
|
||||
acct_a = Account.objects.create(name='Untouchable Account', owner=self.user_a)
|
||||
|
||||
hack_graph = {
|
||||
'nodes': [
|
||||
{'id': 'start', 'type': 'trigger', 'data': {}},
|
||||
{'id': 'update', 'type': 'update_record', 'data': {
|
||||
'target_model': 'Account',
|
||||
'record_id_source': 'context.record_id',
|
||||
'field_updates': {'name': 'Changed by Bob'}
|
||||
}}
|
||||
],
|
||||
'edges': [{'source': 'start', 'target': 'update'}]
|
||||
}
|
||||
flow_b = FlowDefinition.objects.create(
|
||||
name='Bob Flow',
|
||||
created_by=self.user_b,
|
||||
trigger_type='manual',
|
||||
graph=hack_graph,
|
||||
is_active=True
|
||||
)
|
||||
|
||||
res_b = self.client_b.post(f'/api/workflows/{flow_b.id}/execute/', {
|
||||
'context': {'record_id': acct_a.id}
|
||||
}, format='json')
|
||||
assert res_b.status_code == 400
|
||||
acct_a.refresh_from_db()
|
||||
assert acct_a.name == 'Untouchable Account'
|
||||
|
||||
def test_tenant_permissions_and_helpers(self):
|
||||
# Cover ScopedOwnerAccessPermission lines
|
||||
from openforce.permissions import ScopedOwnerAccessPermission
|
||||
from rest_framework.request import Request
|
||||
from django.test.client import RequestFactory
|
||||
from custom_objects.models import CustomFieldDefinition
|
||||
|
||||
perm = ScopedOwnerAccessPermission()
|
||||
rf = RequestFactory()
|
||||
req = rf.get('/')
|
||||
req.user = self.user_a
|
||||
|
||||
# Object with no owner, assigned_to, or created_by
|
||||
class DummyObj:
|
||||
pass
|
||||
assert not perm.has_object_permission(req, None, DummyObj())
|
||||
|
||||
# Object with assigned_to matching
|
||||
class AssignedObj:
|
||||
assigned_to = self.user_a
|
||||
assert perm.has_object_permission(req, None, AssignedObj())
|
||||
|
||||
# CustomFieldDefinition ownership via custom_object
|
||||
custom_obj_a = CustomObjectDefinition.objects.create(name='TestA_c', label='Test A', created_by=self.user_a)
|
||||
field_a = CustomFieldDefinition.objects.create(custom_object=custom_obj_a, name='fld_a_c', label='Fld A', field_type='text')
|
||||
assert perm.has_object_permission(req, None, field_a)
|
||||
|
||||
# Unauthenticated user
|
||||
class AnonUser:
|
||||
is_authenticated = False
|
||||
req.user = AnonUser()
|
||||
assert not perm.has_permission(req, None)
|
||||
|
||||
def test_record_triggered_flow_cannot_modify_foreign_record(self):
|
||||
from workflows.models import FlowDefinition
|
||||
acct_alice = Account.objects.create(name='Alice Account', owner=self.user_a)
|
||||
|
||||
# Bob creates a record-triggered flow on Account creation that updates Alice's account
|
||||
hack_graph = {
|
||||
'nodes': [
|
||||
{'id': 'start', 'type': 'trigger', 'data': {}},
|
||||
{'id': 'upd', 'type': 'update_record', 'data': {
|
||||
'target_model': 'Account',
|
||||
'field_updates': {'name': 'Compromised by Trigger'}
|
||||
}}
|
||||
],
|
||||
'edges': [{'source': 'start', 'target': 'upd'}]
|
||||
}
|
||||
FlowDefinition.objects.create(
|
||||
name='Bob Trigger Flow',
|
||||
created_by=self.user_b,
|
||||
trigger_type='record_created',
|
||||
trigger_object='Account',
|
||||
is_active=True,
|
||||
graph=hack_graph
|
||||
)
|
||||
|
||||
# Bob creates an account via API and attempts to pass Alice's record_id in context
|
||||
# Even if triggered, update_record is evaluated under Bob's execution principal
|
||||
# so it cannot update Alice's record.
|
||||
with pytest.raises(Exception):
|
||||
# When trigger runs under Bob principal targeting Alice's record ID,
|
||||
# it raises PermissionDenied and prevents the modification
|
||||
from workflows.dispatcher import dispatch_flow
|
||||
flow = FlowDefinition.objects.get(name='Bob Trigger Flow')
|
||||
dispatch_flow(flow, context={'record_id': acct_alice.id, 'record_type': 'Account'}, user=self.user_b)
|
||||
|
||||
acct_alice.refresh_from_db()
|
||||
assert acct_alice.name == 'Alice Account'
|
||||
|
||||
def test_flow_cannot_patch_created_by_to_forge_staff_identity(self):
|
||||
from workflows.models import FlowDefinition
|
||||
flow = FlowDefinition.objects.create(
|
||||
name='Bob Own Flow',
|
||||
created_by=self.user_b,
|
||||
graph={'nodes': [{'id': 'start', 'type': 'trigger', 'data': {}}], 'edges': []}
|
||||
)
|
||||
staff_user = User.objects.create_user('staff_victim', 'staff@test.com', 'pw', is_staff=True)
|
||||
res = self.client_b.patch(f'/api/workflows/{flow.id}/', {'created_by': staff_user.id}, format='json')
|
||||
# created_by is read-only, so PATCHing it cannot alter authority
|
||||
flow.refresh_from_db()
|
||||
assert flow.created_by == self.user_b
|
||||
|
||||
def test_flow_cannot_modify_foreign_activity(self):
|
||||
from workflows.models import FlowDefinition
|
||||
from crm_core.models import Activity
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
ct = ContentType.objects.get_for_model(Account)
|
||||
acct_a = Account.objects.create(name='Alice Acct For Act', owner=self.user_a)
|
||||
act_alice = Activity.objects.create(
|
||||
subject='Alice Secret Task',
|
||||
activity_type='task',
|
||||
content_type=ct,
|
||||
object_id=acct_a.id,
|
||||
assigned_to=self.user_a
|
||||
)
|
||||
|
||||
hack_graph = {
|
||||
'nodes': [
|
||||
{'id': 'start', 'type': 'trigger', 'data': {}},
|
||||
{'id': 'upd', 'type': 'update_record', 'data': {
|
||||
'target_model': 'Activity',
|
||||
'field_updates': {'subject': 'Hacked Activity Task'}
|
||||
}}
|
||||
],
|
||||
'edges': [{'source': 'start', 'target': 'upd'}]
|
||||
}
|
||||
flow = FlowDefinition.objects.create(
|
||||
name='Bob Hack Activity',
|
||||
created_by=self.user_b,
|
||||
graph=hack_graph
|
||||
)
|
||||
|
||||
res = self.client_b.post(f'/api/workflows/{flow.id}/execute/', {
|
||||
'context': {'record_id': act_alice.id, 'record_type': 'Activity'}
|
||||
}, format='json')
|
||||
assert res.status_code == 400
|
||||
assert 'Permission denied' in res.data.get('error', '')
|
||||
act_alice.refresh_from_db()
|
||||
assert act_alice.subject == 'Alice Secret Task'
|
||||
|
||||
def test_execute_flow_dag_with_missing_user_fails_closed(self):
|
||||
from workflows.engine import execute_flow_dag
|
||||
from django.core.exceptions import PermissionDenied
|
||||
acct_a = Account.objects.create(name='Alice Unmodified', owner=self.user_a)
|
||||
dag = {
|
||||
'nodes': [
|
||||
{'id': 'start', 'type': 'trigger', 'data': {}},
|
||||
{'id': 'upd', 'type': 'update_record', 'data': {
|
||||
'target_model': 'Account',
|
||||
'field_updates': {'name': 'Forged No-User Update'}
|
||||
}}
|
||||
],
|
||||
'edges': [{'source': 'start', 'target': 'upd'}]
|
||||
}
|
||||
with pytest.raises(PermissionDenied):
|
||||
execute_flow_dag(dag, initial_context={'record_id': acct_a.id, 'record_type': 'Account'}, user=None)
|
||||
acct_a.refresh_from_db()
|
||||
assert acct_a.name == 'Alice Unmodified'
|
||||
|
||||
def test_flow_cannot_rewrite_primary_key_or_authority_fields(self):
|
||||
from workflows.models import FlowDefinition
|
||||
acct_alice = Account.objects.create(name='Alice Original', owner=self.user_a)
|
||||
acct_bob = Account.objects.create(name='Bob Original', owner=self.user_b)
|
||||
|
||||
# Bob attempts to rewrite primary key to overwrite Alice's account
|
||||
id_rewrite_graph = {
|
||||
'nodes': [
|
||||
{'id': 'start', 'type': 'trigger', 'data': {}},
|
||||
{'id': 'update', 'type': 'update_record', 'data': {
|
||||
'target_model': 'Account',
|
||||
'field_updates': {'id': acct_alice.id, 'name': 'OVERWRITTEN'}
|
||||
}}
|
||||
],
|
||||
'edges': [{'source': 'start', 'target': 'update'}]
|
||||
}
|
||||
flow = FlowDefinition.objects.create(
|
||||
name='Bob ID Rewrite Flow',
|
||||
created_by=self.user_b,
|
||||
graph=id_rewrite_graph
|
||||
)
|
||||
self.client_b.force_authenticate(user=self.user_b)
|
||||
res = self.client_b.post(f'/api/workflows/{flow.id}/execute/', {
|
||||
'context': {'record_id': acct_bob.id, 'record_type': 'Account'}
|
||||
}, format='json')
|
||||
assert res.status_code == 400
|
||||
assert 'Permission denied' in res.data['error']
|
||||
|
||||
# Both Alice's and Bob's accounts must remain completely unchanged
|
||||
acct_alice.refresh_from_db()
|
||||
acct_bob.refresh_from_db()
|
||||
assert acct_alice.name == 'Alice Original'
|
||||
assert acct_alice.owner == self.user_a
|
||||
assert acct_bob.name == 'Bob Original'
|
||||
assert acct_bob.owner == self.user_b
|
||||
|
||||
# Setup contacts for relationship & allowlist tests
|
||||
contact_bob = Contact.objects.create(first_name='Bob', last_name='Contact', owner=self.user_b)
|
||||
flow_update_contact = FlowDefinition.objects.create(
|
||||
name='Update Contact Flow',
|
||||
created_by=self.user_b,
|
||||
graph={
|
||||
'nodes': [
|
||||
{'id': 'start', 'type': 'trigger', 'data': {}},
|
||||
{'id': 'update', 'type': 'update_record', 'data': {
|
||||
'target_model': 'Contact',
|
||||
'field_updates': {'account': acct_alice.id}
|
||||
}}
|
||||
],
|
||||
'edges': [{'source': 'start', 'target': 'update'}]
|
||||
}
|
||||
)
|
||||
|
||||
# Verify: foreign relationship write via update_record is rejected
|
||||
from django.core.exceptions import ValidationError as DjangoValidationError
|
||||
from rest_framework.exceptions import ValidationError as DRFValidationError
|
||||
with pytest.raises((PermissionDenied, DRFValidationError, DjangoValidationError)):
|
||||
execute_flow_dag(
|
||||
flow_update_contact,
|
||||
initial_context={'record_id': contact_bob.id, 'record_type': 'Contact'},
|
||||
user=self.user_b
|
||||
)
|
||||
contact_bob.refresh_from_db()
|
||||
assert contact_bob.account is None
|
||||
|
||||
# Verify: raw FK alias (account_id) is rejected
|
||||
hack_fk_graph = {
|
||||
'nodes': [
|
||||
{'id': 'start', 'type': 'trigger', 'data': {}},
|
||||
{'id': 'update', 'type': 'update_record', 'data': {
|
||||
'target_model': 'Contact',
|
||||
'field_updates': {'account_id': acct_alice.id}
|
||||
}}
|
||||
],
|
||||
'edges': [{'source': 'start', 'target': 'update'}]
|
||||
}
|
||||
flow_hack_fk = FlowDefinition.objects.create(
|
||||
name='Hack FK Flow',
|
||||
created_by=self.user_b,
|
||||
graph=hack_fk_graph
|
||||
)
|
||||
with pytest.raises(PermissionDenied):
|
||||
execute_flow_dag(
|
||||
flow_hack_fk,
|
||||
initial_context={'record_id': contact_bob.id, 'record_type': 'Contact'},
|
||||
user=self.user_b
|
||||
)
|
||||
contact_bob.refresh_from_db()
|
||||
assert contact_bob.account is None
|
||||
|
||||
# Verify: internal attribute (__dict__) is rejected
|
||||
hack_internal_graph = {
|
||||
'nodes': [
|
||||
{'id': 'start', 'type': 'trigger', 'data': {}},
|
||||
{'id': 'update', 'type': 'update_record', 'data': {
|
||||
'target_model': 'Contact',
|
||||
'field_updates': {'__dict__': {}}
|
||||
}}
|
||||
],
|
||||
'edges': [{'source': 'start', 'target': 'update'}]
|
||||
}
|
||||
flow_hack_internal = FlowDefinition.objects.create(
|
||||
name='Hack Internal Flow',
|
||||
created_by=self.user_b,
|
||||
graph=hack_internal_graph
|
||||
)
|
||||
with pytest.raises(PermissionDenied):
|
||||
execute_flow_dag(
|
||||
flow_hack_internal,
|
||||
initial_context={'record_id': contact_bob.id, 'record_type': 'Contact'},
|
||||
user=self.user_b
|
||||
)
|
||||
|
||||
# Verify: invalid business value is rejected
|
||||
hack_invalid_val_graph = {
|
||||
'nodes': [
|
||||
{'id': 'start', 'type': 'trigger', 'data': {}},
|
||||
{'id': 'update', 'type': 'update_record', 'data': {
|
||||
'target_model': 'Account',
|
||||
'field_updates': {'rating': 'NON_EXISTENT_RATING'}
|
||||
}}
|
||||
],
|
||||
'edges': [{'source': 'start', 'target': 'update'}]
|
||||
}
|
||||
flow_hack_invalid_val = FlowDefinition.objects.create(
|
||||
name='Hack Invalid Val Flow',
|
||||
created_by=self.user_b,
|
||||
graph=hack_invalid_val_graph
|
||||
)
|
||||
with pytest.raises((PermissionDenied, DRFValidationError, DjangoValidationError)):
|
||||
execute_flow_dag(
|
||||
flow_hack_invalid_val,
|
||||
initial_context={'record_id': acct_bob.id, 'record_type': 'Account'},
|
||||
user=self.user_b
|
||||
)
|
||||
acct_bob.refresh_from_db()
|
||||
assert acct_bob.rating != 'NON_EXISTENT_RATING'
|
||||
|
||||
# Verify: allowed own-record update succeeds
|
||||
valid_update_graph = {
|
||||
'nodes': [
|
||||
{'id': 'start', 'type': 'trigger', 'data': {}},
|
||||
{'id': 'update', 'type': 'update_record', 'data': {
|
||||
'target_model': 'Contact',
|
||||
'field_updates': {'first_name': 'Bobby'}
|
||||
}}
|
||||
],
|
||||
'edges': [{'source': 'start', 'target': 'update'}]
|
||||
}
|
||||
flow_valid_update = FlowDefinition.objects.create(
|
||||
name='Valid Update Flow',
|
||||
created_by=self.user_b,
|
||||
graph=valid_update_graph
|
||||
)
|
||||
execute_flow_dag(
|
||||
flow_valid_update,
|
||||
initial_context={'record_id': contact_bob.id, 'record_type': 'Contact'},
|
||||
user=self.user_b
|
||||
)
|
||||
contact_bob.refresh_from_db()
|
||||
assert contact_bob.first_name == 'Bobby'
|
||||
|
||||
def test_ownerless_trigger_flow_fails_closed_without_superuser_elevation(self):
|
||||
from workflows.models import FlowDefinition
|
||||
from django.core.exceptions import PermissionDenied
|
||||
acct_alice = Account.objects.create(name='Alice Safe', owner=self.user_a)
|
||||
|
||||
# Create trigger flow with no created_by
|
||||
trigger_graph = {
|
||||
'nodes': [
|
||||
{'id': 'start', 'type': 'trigger', 'data': {}},
|
||||
{'id': 'update', 'type': 'update_record', 'data': {
|
||||
'target_model': 'Account',
|
||||
'field': 'name',
|
||||
'value': 'Trigger Hack'
|
||||
}}
|
||||
],
|
||||
'edges': [{'source': 'start', 'target': 'update'}]
|
||||
}
|
||||
FlowDefinition.objects.create(
|
||||
name='Ownerless Trigger Flow',
|
||||
trigger_type='record_created',
|
||||
trigger_object='Account',
|
||||
is_active=True,
|
||||
created_by=None,
|
||||
graph=trigger_graph
|
||||
)
|
||||
from workflows.dispatcher import dispatch_flow
|
||||
# If dispatched with no user, must raise PermissionDenied and not elevate to superuser
|
||||
with pytest.raises(PermissionDenied):
|
||||
dispatch_flow(
|
||||
FlowDefinition.objects.get(name='Ownerless Trigger Flow'),
|
||||
context={'record_id': acct_alice.id, 'record_type': 'Account'},
|
||||
user=None
|
||||
)
|
||||
acct_alice.refresh_from_db()
|
||||
assert acct_alice.name == 'Alice Safe'
|
||||
|
||||
def test_idempotency_key_does_not_leak_other_user_execution(self):
|
||||
from workflows.models import FlowDefinition, FlowExecutionLog
|
||||
dag = {
|
||||
'nodes': [
|
||||
{'id': 'start', 'type': 'trigger', 'data': {}},
|
||||
{'id': 'assign', 'type': 'assignment', 'data': {'variable': 'secret', 'value': 'AliceTopSecret'}}
|
||||
],
|
||||
'edges': [{'source': 'start', 'target': 'assign'}]
|
||||
}
|
||||
flow_alice = FlowDefinition.objects.create(
|
||||
name='Alice Secret Flow',
|
||||
created_by=self.user_a,
|
||||
trigger_type='manual',
|
||||
graph=dag,
|
||||
is_active=True
|
||||
)
|
||||
flow_bob = FlowDefinition.objects.create(
|
||||
name='Bob Innocent Flow',
|
||||
created_by=self.user_b,
|
||||
trigger_type='manual',
|
||||
graph=dag,
|
||||
is_active=True
|
||||
)
|
||||
|
||||
# Alice runs with key 'shared-key-123'
|
||||
res_a = self.client_a.post(f'/api/workflows/{flow_alice.id}/execute/', {
|
||||
'idempotency_key': 'shared-key-123'
|
||||
}, format='json')
|
||||
assert res_a.status_code == 200
|
||||
|
||||
# Bob attempts to execute his flow using Alice's idempotency key
|
||||
res_b = self.client_b.post(f'/api/workflows/{flow_bob.id}/execute/', {
|
||||
'idempotency_key': 'shared-key-123'
|
||||
}, format='json')
|
||||
assert res_b.status_code == 200
|
||||
# Bob must get his own run, not Alice's execution log/context
|
||||
assert res_b.data['id'] != res_a.data['id']
|
||||
|
||||
def test_campaign_template_collision_creates_separate_tenant_template(self):
|
||||
from outreach.models import EmailTemplate
|
||||
# Alice creates a template named "Launch Template"
|
||||
alice_tmpl = EmailTemplate.objects.create(
|
||||
name="Launch Template",
|
||||
created_by=self.user_a,
|
||||
subject="Alice Subject",
|
||||
body_html="<p>Alice</p>",
|
||||
body_text="Alice"
|
||||
)
|
||||
|
||||
# Bob creates a campaign named "Launch" with modal fallback
|
||||
res_b = self.client_b.post('/api/campaigns/', {
|
||||
'name': 'Launch',
|
||||
'subject': 'Bob Subject',
|
||||
'target_object': 'Lead'
|
||||
}, format='json')
|
||||
assert res_b.status_code == 201
|
||||
|
||||
# Must have created Bob's own template, not reused Alice's
|
||||
bob_tmpl = EmailTemplate.objects.filter(name="Launch Template", created_by=self.user_b).first()
|
||||
assert bob_tmpl is not None
|
||||
assert bob_tmpl.id != alice_tmpl.id
|
||||
assert bob_tmpl.created_by == self.user_b
|
||||
|
||||
def test_activity_polymorphic_generic_foreign_key_isolated(self):
|
||||
"""
|
||||
Bob cannot attach an Activity to Alice's Account via polymorphic (content_type, object_id).
|
||||
"""
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from crm_core.models import Activity
|
||||
|
||||
account_a = Account.objects.create(name='Alice Account', owner=self.user_a)
|
||||
account_b = Account.objects.create(name='Bob Account', owner=self.user_b)
|
||||
account_ct = ContentType.objects.get_for_model(Account)
|
||||
|
||||
# 1. Bob attempts to create an Activity pointing to Alice's Account
|
||||
create_res = self.client_b.post('/api/activities/', {
|
||||
'subject': 'Infiltrate Alice Account',
|
||||
'activity_type': 'Task',
|
||||
'content_type': account_ct.id,
|
||||
'object_id': account_a.id,
|
||||
}, format='json')
|
||||
assert create_res.status_code == 400
|
||||
assert 'object_id' in create_res.data
|
||||
|
||||
# 2. Bob creates a valid Activity on his own Account
|
||||
bob_valid = self.client_b.post('/api/activities/', {
|
||||
'subject': 'Bob Task',
|
||||
'activity_type': 'Task',
|
||||
'content_type': account_ct.id,
|
||||
'object_id': account_b.id,
|
||||
}, format='json')
|
||||
assert bob_valid.status_code == 201
|
||||
bob_act_id = bob_valid.data['id']
|
||||
|
||||
# 3. Bob attempts to patch/update the Activity to repoint to Alice's Account
|
||||
patch_res = self.client_b.patch(f'/api/activities/{bob_act_id}/', {
|
||||
'object_id': account_a.id,
|
||||
}, format='json')
|
||||
assert patch_res.status_code == 400
|
||||
assert 'object_id' in patch_res.data
|
||||
|
||||
# Verify in DB that the Activity was NOT repointed to Alice's Account
|
||||
act = Activity.objects.get(id=bob_act_id)
|
||||
assert act.object_id == account_b.id
|
||||
|
||||
# 4. Bob attempts to patch/update the Activity pointing to an unallowed system model (auth.User)
|
||||
user_ct = ContentType.objects.get_for_model(User)
|
||||
patch_user_res = self.client_b.patch(f'/api/activities/{bob_act_id}/', {
|
||||
'content_type': user_ct.id,
|
||||
'object_id': self.user_a.id,
|
||||
}, format='json')
|
||||
assert patch_user_res.status_code == 400
|
||||
assert 'content_type' in patch_user_res.data
|
||||
assert 'not allowed' in str(patch_user_res.data['content_type']).lower()
|
||||
|
||||
# 5. Partial update clearing only one of the polymorphic pair is rejected
|
||||
partial_clear_res = self.client_b.patch(f'/api/activities/{bob_act_id}/', {
|
||||
'content_type': None,
|
||||
}, format='json')
|
||||
assert partial_clear_res.status_code == 400
|
||||
|
||||
# Clearing both together succeeds
|
||||
clear_both_res = self.client_b.patch(f'/api/activities/{bob_act_id}/', {
|
||||
'content_type': None,
|
||||
'object_id': None,
|
||||
}, format='json')
|
||||
assert clear_both_res.status_code == 200
|
||||
act.refresh_from_db()
|
||||
assert act.content_type is None
|
||||
assert act.object_id is None
|
||||
|
||||
def test_flow_execution_atomic_rollback_on_failure(self):
|
||||
"""
|
||||
When manual flow execution encounters an error in a subsequent node,
|
||||
earlier record mutations are rolled back atomically while the failed log is preserved.
|
||||
"""
|
||||
from workflows.models import FlowDefinition, FlowExecutionLog
|
||||
|
||||
account_b = Account.objects.create(name='Bob Account Prior', owner=self.user_b)
|
||||
initial_name = account_b.name
|
||||
|
||||
# Create a DAG with two nodes:
|
||||
# Node 1: update Bob's account name
|
||||
# Node 2: call nonexistent child subflow (fails)
|
||||
dag = {
|
||||
"nodes": [
|
||||
{
|
||||
"id": "node_update",
|
||||
"type": "update_record",
|
||||
"data": {
|
||||
"model_name": "Account",
|
||||
"record_id_path": "account_id",
|
||||
"field_updates": {"name": "Should Be Rolled Back"}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "node_subflow_fail",
|
||||
"type": "subflow",
|
||||
"data": {
|
||||
"subflow_id": 999999
|
||||
}
|
||||
}
|
||||
],
|
||||
"edges": [
|
||||
{
|
||||
"source": "node_update",
|
||||
"target": "node_subflow_fail"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
flow = FlowDefinition.objects.create(
|
||||
name="Rollback Test Flow",
|
||||
graph=dag,
|
||||
is_active=True,
|
||||
created_by=self.user_b
|
||||
)
|
||||
|
||||
res = self.client_b.post(f'/api/workflows/{flow.id}/execute/', {
|
||||
'context': {'account_id': account_b.id}
|
||||
}, format='json')
|
||||
|
||||
assert res.status_code == 400
|
||||
assert res.data['status'] == 'failed'
|
||||
|
||||
# Verify Account B's name was rolled back and NOT persisted
|
||||
account_b.refresh_from_db()
|
||||
assert account_b.name == initial_name
|
||||
|
||||
# Verify execution log was saved with status 'failed'
|
||||
log = FlowExecutionLog.objects.filter(flow=flow).order_by('-started_at').first()
|
||||
assert log is not None
|
||||
assert log.status == 'failed'
|
||||
|
||||
def test_flow_execution_log_audit_integrity_across_runs(self):
|
||||
"""
|
||||
Verify that a failed execution does not overwrite or corrupt
|
||||
a previous successful execution log for the same flow.
|
||||
"""
|
||||
from workflows.models import FlowDefinition, FlowExecutionLog
|
||||
|
||||
account_b = Account.objects.create(name='Audit Integrity Test Acc', owner=self.user_b)
|
||||
initial_name = account_b.name
|
||||
|
||||
# 1. Flow that succeeds
|
||||
success_dag = {
|
||||
"nodes": [
|
||||
{"id": "start", "type": "trigger", "data": {}},
|
||||
],
|
||||
"edges": []
|
||||
}
|
||||
flow = FlowDefinition.objects.create(
|
||||
name="Audit Log Test Flow",
|
||||
graph=success_dag,
|
||||
is_active=True,
|
||||
created_by=self.user_b
|
||||
)
|
||||
|
||||
res1 = self.client_b.post(f'/api/workflows/{flow.id}/execute/', {}, format='json')
|
||||
assert res1.status_code == 200
|
||||
assert res1.data['status'] == 'completed'
|
||||
|
||||
logs_after_1 = list(FlowExecutionLog.objects.filter(flow=flow).order_by('id'))
|
||||
assert len(logs_after_1) == 1
|
||||
log1 = logs_after_1[0]
|
||||
assert log1.status == 'completed'
|
||||
|
||||
# 2. Update flow graph to mutate account and then fail on invalid subflow
|
||||
fail_dag = {
|
||||
"nodes": [
|
||||
{
|
||||
"id": "node_update",
|
||||
"type": "update_record",
|
||||
"data": {
|
||||
"model_name": "Account",
|
||||
"record_id": account_b.id,
|
||||
"field_updates": {"name": "Should Rollback"}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "node_subflow_fail",
|
||||
"type": "subflow",
|
||||
"data": {
|
||||
"flow_id": 999999
|
||||
}
|
||||
}
|
||||
],
|
||||
"edges": [
|
||||
{
|
||||
"source": "node_update",
|
||||
"target": "node_subflow_fail"
|
||||
}
|
||||
]
|
||||
}
|
||||
flow.graph = fail_dag
|
||||
flow.save()
|
||||
|
||||
res2 = self.client_b.post(f'/api/workflows/{flow.id}/execute/', {
|
||||
'context': {'account_id': account_b.id}
|
||||
}, format='json')
|
||||
assert res2.status_code == 400
|
||||
assert res2.data['status'] == 'failed'
|
||||
|
||||
# Mutation must be rolled back
|
||||
account_b.refresh_from_db()
|
||||
assert account_b.name == initial_name
|
||||
|
||||
# Verify two distinct logs exist: original success remains completed and intact,
|
||||
# new log is recorded as failed.
|
||||
logs_after_2 = list(FlowExecutionLog.objects.filter(flow=flow).order_by('id'))
|
||||
assert len(logs_after_2) == 2
|
||||
|
||||
log1_reloaded = FlowExecutionLog.objects.get(id=log1.id)
|
||||
assert log1_reloaded.status == 'completed'
|
||||
assert log1_reloaded.error_message == '' or log1_reloaded.error_message is None
|
||||
|
||||
log2 = logs_after_2[1]
|
||||
assert log2.id != log1.id
|
||||
assert log2.status == 'failed'
|
||||
assert '999999' in log2.error_message
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
import threading
|
||||
import logging
|
||||
from django.db import models
|
||||
from django.db.models.signals import pre_save, post_save
|
||||
from django.dispatch import receiver
|
||||
from .models import FlowDefinition, FlowExecutionLog
|
||||
|
|
@ -18,13 +19,14 @@ def _set_active_flow_depth(val):
|
|||
|
||||
MAX_SIGNAL_REENTRANCY_DEPTH = 1
|
||||
|
||||
def dispatch_flow(flow, context=None, idempotency_key=None):
|
||||
def dispatch_flow(flow, context=None, idempotency_key=None, user=None):
|
||||
"""
|
||||
Dispatches a single flow execution with the given context.
|
||||
Dispatches a single flow execution with the given context and user principal.
|
||||
"""
|
||||
if context is None:
|
||||
context = {}
|
||||
return execute_flow_dag(flow, initial_context=context, idempotency_key=idempotency_key)
|
||||
exec_user = user or getattr(flow, 'created_by', None)
|
||||
return execute_flow_dag(flow, initial_context=context, idempotency_key=idempotency_key, user=exec_user)
|
||||
|
||||
def snapshot_model(instance):
|
||||
data = {}
|
||||
|
|
@ -90,6 +92,13 @@ def on_record_post_save(sender, instance, created, **kwargs):
|
|||
trigger_object__iexact=model_name
|
||||
)
|
||||
|
||||
# Scope flows to the record's owner/creator if multi-tenancy applies
|
||||
owner = getattr(instance, 'owner', None) or getattr(instance, 'created_by', None)
|
||||
if owner and hasattr(FlowDefinition, 'created_by'):
|
||||
flows = flows.filter(models.Q(created_by=owner) | models.Q(created_by__isnull=True))
|
||||
elif hasattr(FlowDefinition, 'created_by'):
|
||||
flows = flows.filter(created_by__isnull=True)
|
||||
|
||||
current_state = snapshot_model(instance)
|
||||
prior_state = getattr(instance, '_prior_state', {})
|
||||
|
||||
|
|
@ -107,6 +116,9 @@ def on_record_post_save(sender, instance, created, **kwargs):
|
|||
# Under Salesforce transactional contract (docs/SALESFORCE_FLOW_ENGINE_SPEC.md:108),
|
||||
# an unhandled failure in a synchronous record-triggered flow must fail
|
||||
# the transaction and roll back the triggering record modification.
|
||||
dispatch_flow(flow, context=context)
|
||||
exec_user = getattr(flow, 'created_by', None) or owner
|
||||
# If neither flow nor record has an owner, dispatch_flow passes user=None
|
||||
# and any attempt to perform protected mutations in execute_flow_dag will fail closed.
|
||||
dispatch_flow(flow, context=context, user=exec_user)
|
||||
finally:
|
||||
_set_active_flow_depth(depth)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
from collections import deque
|
||||
from django.utils import timezone
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.exceptions import ValidationError, PermissionDenied
|
||||
|
||||
|
||||
def validate_flow_dag(graph):
|
||||
|
|
@ -111,7 +111,7 @@ def evaluate_condition(cond, context):
|
|||
|
||||
|
||||
def evaluate_outcome(outcome, context):
|
||||
conditions = outcome.get('conditions', [])
|
||||
conditions = outcome.get('conditions') or outcome.get('rules') or []
|
||||
if not conditions:
|
||||
return True # Default / Else branch
|
||||
logic = outcome.get('logic', 'AND').upper()
|
||||
|
|
@ -151,7 +151,7 @@ def _evaluate_decision_node(node_data, context):
|
|||
return 'default', node_data.get('default_target_node')
|
||||
|
||||
|
||||
def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None, depth=0):
|
||||
def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None, depth=0, user=None, execution_log=None):
|
||||
from .models import FlowDefinition, FlowExecutionLog
|
||||
|
||||
MAX_SUBFLOW_DEPTH = 10
|
||||
|
|
@ -164,13 +164,13 @@ def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None,
|
|||
|
||||
validate_flow_dag(graph)
|
||||
|
||||
if not is_dict and idempotency_key:
|
||||
existing = FlowExecutionLog.objects.filter(idempotency_key=idempotency_key).first()
|
||||
if not is_dict and idempotency_key and not execution_log:
|
||||
existing = FlowExecutionLog.objects.filter(flow=flow_def, idempotency_key=idempotency_key).first()
|
||||
if existing:
|
||||
return existing
|
||||
|
||||
log = None
|
||||
if not is_dict and flow_def:
|
||||
log = execution_log
|
||||
if log is None and not is_dict and flow_def:
|
||||
log = FlowExecutionLog.objects.create(
|
||||
flow=flow_def,
|
||||
status='running',
|
||||
|
|
@ -220,8 +220,8 @@ def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None,
|
|||
continue
|
||||
|
||||
node = node_map.get(node_id, {})
|
||||
node_type = node.get('type') or node_data.get('type')
|
||||
node_data = node.get('data', {})
|
||||
node_type = node.get('type') or node_data.get('type')
|
||||
|
||||
step_record = {
|
||||
'node_id': node_id,
|
||||
|
|
@ -245,20 +245,82 @@ def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None,
|
|||
for k, v in node_data.items():
|
||||
context[k] = v
|
||||
# Check if this flow was triggered by a model record and update DB record if field/value specified
|
||||
field = node_data.get('field')
|
||||
val = node_data.get('value')
|
||||
record_id = context.get('record_id')
|
||||
record_type = context.get('record_type')
|
||||
if field and val is not None and record_id and record_type:
|
||||
from django.apps import apps
|
||||
model_cls = apps.get_model('crm_core', record_type)
|
||||
if not model_cls:
|
||||
model_cls = apps.get_model('custom_objects', record_type)
|
||||
if model_cls:
|
||||
inst = model_cls.objects.filter(pk=record_id).first()
|
||||
if inst and hasattr(inst, field):
|
||||
setattr(inst, field, val)
|
||||
inst.save()
|
||||
record_type = context.get('record_type') or node_data.get('target_model')
|
||||
|
||||
# Check for direct field/value or field_updates dict
|
||||
updates = {}
|
||||
if node_data.get('field') and node_data.get('value') is not None:
|
||||
updates[node_data.get('field')] = node_data.get('value')
|
||||
if isinstance(node_data.get('field_updates'), dict):
|
||||
updates.update(node_data.get('field_updates'))
|
||||
|
||||
if updates and record_id and record_type:
|
||||
from crm_core.serializers import (
|
||||
AccountSerializer, ContactSerializer, LeadSerializer,
|
||||
OpportunitySerializer, ActivitySerializer
|
||||
)
|
||||
from custom_objects.serializers import CustomRecordSerializer
|
||||
from rest_framework.test import APIRequestFactory
|
||||
|
||||
SUPPORTED_SERIALIZER_REGISTRY = {
|
||||
'Account': AccountSerializer,
|
||||
'Contact': ContactSerializer,
|
||||
'Lead': LeadSerializer,
|
||||
'Opportunity': OpportunitySerializer,
|
||||
'Activity': ActivitySerializer,
|
||||
'CustomRecord': CustomRecordSerializer,
|
||||
}
|
||||
|
||||
serializer_cls = SUPPORTED_SERIALIZER_REGISTRY.get(record_type)
|
||||
if not serializer_cls:
|
||||
raise PermissionDenied(f"Permission denied: model '{record_type}' is not registered for flow updates.")
|
||||
|
||||
model_cls = serializer_cls.Meta.model
|
||||
if not user:
|
||||
# Fail-closed: unauthenticated / missing identity cannot perform DB writes
|
||||
raise PermissionDenied("Missing execution identity for update_record.")
|
||||
|
||||
qs = model_cls.objects.filter(pk=record_id)
|
||||
if not (user.is_superuser or user.is_staff):
|
||||
if hasattr(model_cls, 'owner'):
|
||||
qs = qs.filter(owner=user)
|
||||
elif hasattr(model_cls, 'assigned_to'):
|
||||
qs = qs.filter(assigned_to=user)
|
||||
elif hasattr(model_cls, 'created_by'):
|
||||
qs = qs.filter(created_by=user)
|
||||
else:
|
||||
raise PermissionDenied(f"Permission denied: no ownership policy defined for model {record_type}")
|
||||
|
||||
inst = qs.first()
|
||||
if not inst:
|
||||
raise PermissionDenied(f"Permission denied: cannot update unauthorized record {record_type}:{record_id}")
|
||||
else:
|
||||
inst = qs.first()
|
||||
|
||||
if inst:
|
||||
factory = APIRequestFactory()
|
||||
req = factory.post('/')
|
||||
req.user = user
|
||||
|
||||
# Use dummy serializer instance to inspect declared editable business fields
|
||||
inspect_serializer = serializer_cls(inst, data={}, partial=True, context={'request': req})
|
||||
allowed_business_fields = {
|
||||
fname for fname, f in inspect_serializer.fields.items() if not f.read_only
|
||||
}
|
||||
|
||||
# Reject any unknown fields, internal attributes, or raw FK aliases (e.g. account_id)
|
||||
disallowed_fields = set(updates.keys()) - allowed_business_fields
|
||||
if disallowed_fields:
|
||||
raise PermissionDenied(
|
||||
f"Permission denied: field(s) {disallowed_fields} are not declared editable business fields on {record_type}."
|
||||
)
|
||||
|
||||
# Validate updates via the model serializer with actor-scoped request context
|
||||
serializer = serializer_cls(inst, data=updates, partial=True, context={'request': req})
|
||||
if not serializer.is_valid():
|
||||
raise ValidationError(serializer.errors)
|
||||
serializer.save()
|
||||
|
||||
elif node_type == 'assignment':
|
||||
# Handle single assignment fields or assignments array
|
||||
|
|
@ -356,14 +418,18 @@ def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None,
|
|||
child_flow_id = node_data.get('flow_id') or node_data.get('subflow_id')
|
||||
if not child_flow_id:
|
||||
raise ValidationError("Subflow node requires flow_id.")
|
||||
child_flow = FlowDefinition.objects.filter(pk=child_flow_id).first()
|
||||
child_qs = FlowDefinition.objects.filter(pk=child_flow_id)
|
||||
if user and not (user.is_superuser or user.is_staff):
|
||||
child_qs = child_qs.filter(created_by=user)
|
||||
child_flow = child_qs.first()
|
||||
if not child_flow:
|
||||
raise ValidationError(f"Referenced child flow {child_flow_id} not found.")
|
||||
raise ValidationError(f"Referenced child flow {child_flow_id} not found or unauthorized.")
|
||||
|
||||
child_res = execute_flow_dag(
|
||||
child_flow.graph,
|
||||
initial_context=context,
|
||||
depth=depth + 1
|
||||
depth=depth + 1,
|
||||
user=user
|
||||
)
|
||||
if isinstance(child_res, dict):
|
||||
context.update(child_res)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,21 @@
|
|||
# Generated by Django 4.2.30 on 2026-09-26 22:23
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('workflows', '0002_flowdefinition_trigger_object_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveConstraint(
|
||||
model_name='flowexecutionlog',
|
||||
name='unique_idempotency_key_when_not_null',
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='flowexecutionlog',
|
||||
constraint=models.UniqueConstraint(condition=models.Q(('idempotency_key__isnull', False)), fields=('flow', 'idempotency_key'), name='unique_flow_idempotency_key_when_not_null'),
|
||||
),
|
||||
]
|
||||
|
|
@ -67,8 +67,8 @@ class FlowExecutionLog(models.Model):
|
|||
ordering = ['-started_at']
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=['idempotency_key'],
|
||||
name='unique_idempotency_key_when_not_null',
|
||||
fields=['flow', 'idempotency_key'],
|
||||
name='unique_flow_idempotency_key_when_not_null',
|
||||
condition=models.Q(idempotency_key__isnull=False)
|
||||
)
|
||||
]
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ class FlowDefinitionSerializer(serializers.ModelSerializer):
|
|||
class Meta:
|
||||
model = FlowDefinition
|
||||
fields = '__all__'
|
||||
read_only_fields = ['id', 'created_at', 'updated_at']
|
||||
read_only_fields = ['id', 'created_by', 'created_at', 'updated_at']
|
||||
|
||||
def validate_graph(self, value):
|
||||
validate_flow_dag(value)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
from django.db import models, transaction
|
||||
from rest_framework import viewsets, status
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
|
|
@ -6,28 +8,124 @@ from rest_framework.permissions import IsAuthenticated
|
|||
from .models import FlowDefinition, FlowExecutionLog
|
||||
from .serializers import FlowDefinitionSerializer, FlowExecutionLogSerializer
|
||||
from .engine import execute_flow_dag
|
||||
from openforce.permissions import ScopedOwnerAccessPermission
|
||||
|
||||
|
||||
class FlowDefinitionViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = FlowDefinition.objects.all().order_by('-created_at')
|
||||
permission_classes = [IsAuthenticated, ScopedOwnerAccessPermission]
|
||||
queryset = FlowDefinition.objects.all()
|
||||
serializer_class = FlowDefinitionSerializer
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='run')
|
||||
def run_flow(self, request, pk=None):
|
||||
flow = self.get_object()
|
||||
context_data = request.data.get('context', {})
|
||||
idempotency_key = request.data.get('idempotency_key')
|
||||
log = execute_flow_dag(flow, initial_context=context_data, idempotency_key=idempotency_key)
|
||||
return Response(FlowExecutionLogSerializer(log).data, status=status.HTTP_200_OK)
|
||||
def get_queryset(self):
|
||||
qs = super().get_queryset()
|
||||
user = self.request.user
|
||||
if not user or not user.is_authenticated:
|
||||
return qs
|
||||
if user.is_superuser or user.is_staff:
|
||||
return qs
|
||||
if hasattr(FlowDefinition, 'created_by'):
|
||||
return qs.filter(created_by=user)
|
||||
return qs
|
||||
|
||||
def perform_create(self, serializer):
|
||||
kwargs = {}
|
||||
if hasattr(FlowDefinition, 'created_by'):
|
||||
kwargs['created_by'] = self.request.user
|
||||
serializer.save(**kwargs)
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='execute')
|
||||
def execute_flow(self, request, pk=None):
|
||||
return self.run_flow(request, pk)
|
||||
def execute(self, request, pk=None):
|
||||
flow = self.get_object()
|
||||
initial_context = request.data.get('context', {})
|
||||
idempotency_key = request.data.get('idempotency_key')
|
||||
user = request.user if request.user and request.user.is_authenticated else None
|
||||
|
||||
# Check existing idempotency key before attempting new execution
|
||||
if idempotency_key:
|
||||
existing_log = FlowExecutionLog.objects.filter(flow=flow, idempotency_key=idempotency_key).first()
|
||||
if existing_log:
|
||||
if existing_log.status == 'failed':
|
||||
return Response(
|
||||
{
|
||||
'status': 'failed',
|
||||
'error': existing_log.error_message,
|
||||
'log': FlowExecutionLogSerializer(existing_log).data
|
||||
},
|
||||
status=status.HTTP_400_BAD_REQUEST
|
||||
)
|
||||
data = FlowExecutionLogSerializer(existing_log).data
|
||||
data['context_data'] = existing_log.context_data
|
||||
data['status'] = existing_log.status
|
||||
return Response(data, status=status.HTTP_200_OK)
|
||||
|
||||
# Allocate distinct execution log for this attempt outside the mutation savepoint
|
||||
current_log = FlowExecutionLog.objects.create(
|
||||
flow=flow,
|
||||
status='running',
|
||||
context_data=initial_context or {},
|
||||
idempotency_key=idempotency_key
|
||||
)
|
||||
|
||||
sid = transaction.savepoint()
|
||||
try:
|
||||
execution_log = execute_flow_dag(
|
||||
flow,
|
||||
initial_context=initial_context,
|
||||
idempotency_key=idempotency_key,
|
||||
user=user,
|
||||
execution_log=current_log
|
||||
)
|
||||
if execution_log and execution_log.status == 'failed':
|
||||
transaction.savepoint_rollback(sid)
|
||||
current_log.status = 'failed'
|
||||
current_log.error_message = execution_log.error_message
|
||||
current_log.save()
|
||||
return Response(
|
||||
{
|
||||
'status': 'failed',
|
||||
'error': current_log.error_message,
|
||||
'log': FlowExecutionLogSerializer(current_log).data
|
||||
},
|
||||
status=status.HTTP_400_BAD_REQUEST
|
||||
)
|
||||
transaction.savepoint_commit(sid)
|
||||
except Exception as e:
|
||||
transaction.savepoint_rollback(sid)
|
||||
current_log.status = 'failed'
|
||||
current_log.error_message = str(e)
|
||||
current_log.save()
|
||||
return Response(
|
||||
{
|
||||
'status': 'failed',
|
||||
'error': str(e),
|
||||
'log': FlowExecutionLogSerializer(current_log).data
|
||||
},
|
||||
status=status.HTTP_400_BAD_REQUEST
|
||||
)
|
||||
|
||||
# Refetch completed log state
|
||||
current_log.refresh_from_db()
|
||||
data = FlowExecutionLogSerializer(current_log).data
|
||||
data['context_data'] = current_log.context_data
|
||||
data['status'] = current_log.status
|
||||
return Response(
|
||||
data,
|
||||
status=status.HTTP_200_OK
|
||||
)
|
||||
|
||||
|
||||
class FlowExecutionLogViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = FlowExecutionLog.objects.all().order_by('-started_at')
|
||||
queryset = FlowExecutionLog.objects.all()
|
||||
serializer_class = FlowExecutionLogSerializer
|
||||
filterset_fields = ['flow', 'status']
|
||||
|
||||
def get_queryset(self):
|
||||
qs = super().get_queryset()
|
||||
user = self.request.user
|
||||
if not user or not user.is_authenticated:
|
||||
return qs
|
||||
if user.is_superuser or user.is_staff:
|
||||
return qs
|
||||
if hasattr(FlowDefinition, 'created_by'):
|
||||
return qs.filter(flow__created_by=user)
|
||||
return qs
|
||||
|
|
|
|||
Loading…
Reference in a new issue