diff --git a/django_forms_workflows/tasks.py b/django_forms_workflows/tasks.py index 05e4068..55b9eb5 100644 --- a/django_forms_workflows/tasks.py +++ b/django_forms_workflows/tasks.py @@ -30,7 +30,7 @@ from django.core.serializers.json import DjangoJSONEncoder from django.core.validators import validate_email from django.db import transaction -from django.db.models import F, Prefetch +from django.db.models import F, Prefetch, Q from django.template.loader import render_to_string from django.urls import reverse from django.utils import timezone @@ -2142,13 +2142,19 @@ def send_notification_rules( # Build a denormalized "public_comments" list for template context on a # per-workflow basis so rule recipients only see comments from their # workflow. Ordered by workflow flow (stage → step → completion time). + legacy_workflow = submission.form_definition.workflow + legacy_workflow_id = legacy_workflow.id if legacy_workflow else None + def _build_public_comments_for_workflow(workflow_id: int | None) -> list[dict]: if not workflow_id: return [] + task_scope = Q(workflow_stage__workflow_id=workflow_id) + if workflow_id == legacy_workflow_id: + task_scope |= Q(workflow_stage__isnull=True) _comments_qs = ( submission.approval_tasks.select_related("workflow_stage", "completed_by") .filter( - workflow_stage__workflow_id=workflow_id, + task_scope, status__in=["approved", "rejected"], ) .exclude(comments="") @@ -2200,8 +2206,6 @@ def _build_public_comments_for_workflow(workflow_id: int | None) -> list[dict]: # versa), producing duplicate emails. ``use_triggering_stage=True`` # rules handle scoping at recipient resolution time and must remain # candidates here regardless of which task triggered the event. - from django.db.models import Q - if explicit_task and task and getattr(task, "workflow_stage_id", None): triggering_stage_id = task.workflow_stage_id rules_qs = rules_qs.filter( @@ -2689,12 +2693,6 @@ def _locked_recipient_cc(recipient, cc_candidates=(), *, cc_only=False): if rule_task: base_context["task"] = rule_task - # Pre-fetch User objects for all recipients so templates that - # reference ``{{ approver }}`` (e.g. approval_request.html) work - # identically to the legacy send_approval_request task. - from django.contrib.auth import get_user_model - - user_model = get_user_model() _users_by_email: dict = {} all_recipient_emails = list( dict.fromkeys(list(recipients) + list(cc_recipients)) @@ -2702,16 +2700,6 @@ def _locked_recipient_cc(recipient, cc_candidates=(), *, cc_only=False): normalized_recipient_emails = { _recipient_key(e) for e in all_recipient_emails if _recipient_key(e) } - if normalized_recipient_emails: - normalized_email_list = list(normalized_recipient_emails) - chunk_size = 500 - for i in range(0, len(normalized_email_list), chunk_size): - email_chunk = normalized_email_list[i : i + chunk_size] - for u in user_model.objects.annotate(email_lc=Lower("email")).filter( - email_lc__in=email_chunk - ): - if u.email: - _users_by_email[_recipient_key(u.email)] = u # Check cadence — batch or send immediately cadence = ( @@ -2780,6 +2768,22 @@ def _locked_recipient_cc(recipient, cc_candidates=(), *, cc_only=False): scheduled_for, ) else: + # Pre-fetch User objects only for immediate delivery so templates + # that reference ``{{ approver }}`` (e.g. approval_request.html) + # work identically to the legacy send_approval_request task. + from django.contrib.auth import get_user_model + + user_model = get_user_model() + if normalized_recipient_emails: + normalized_email_list = list(normalized_recipient_emails) + chunk_size = 500 + for i in range(0, len(normalized_email_list), chunk_size): + email_chunk = normalized_email_list[i : i + chunk_size] + for u in user_model.objects.annotate( + email_lc=Lower("email") + ).filter(email_lc__in=email_chunk): + if u.email: + _users_by_email[_recipient_key(u.email)] = u # Determine template: per-rule body_template overrides file. rule_body = getattr(rule, "body_template", "") or "" diff --git a/django_forms_workflows/workflow_builder_views.py b/django_forms_workflows/workflow_builder_views.py index ac53f22..96f815a 100644 --- a/django_forms_workflows/workflow_builder_views.py +++ b/django_forms_workflows/workflow_builder_views.py @@ -1312,41 +1312,6 @@ def _get_stage_defaults(): visual_data = workflow.visual_workflow_data # Check if it has the new format with nodes array if isinstance(visual_data, dict) and "nodes" in visual_data: - stage_node_map = {} - for node in visual_data.get("nodes", []): - if node.get("type") == "stage": - raw_stage_id = node.get("data", {}).get("stage_id") - stage_id = None - if isinstance(raw_stage_id, int) and not isinstance( - raw_stage_id, bool - ): - stage_id = raw_stage_id - elif isinstance(raw_stage_id, str): - value = raw_stage_id.strip() - if value.isascii() and value.isdigit(): - try: - stage_id = int(value) - except ValueError: - stage_id = None - node_id = node.get("id") - if ( - stage_id in stage_defaults - and isinstance(node_id, str | int) - and not isinstance(node_id, bool) - and str(node_id).strip() - ): - stage_node_map[stage_id] = node_id - - notification_rule_defaults = [ - _serialize_notification_rule( - rule, - stage_node_id=stage_node_map.get(rule.stage_id), - ) - for rule in workflow.notification_rules.select_related("stage") - .prefetch_related("notify_groups") - .order_by("event", "stage_id", "id") - ] - has_workflow_settings_node = False has_sub_workflow_node = False form_node_defaults = None @@ -1413,7 +1378,6 @@ def _get_stage_defaults(): if key == "notification_rules": continue node_data[key] = value - node_data["notification_rules"] = notification_rule_defaults elif node_type == "email": action_id = node_data.get("action_id") defaults = email_action_defaults.get(action_id) @@ -1490,7 +1454,6 @@ def allocate_unique_node_id(base_node_id): "y": 0, "data": { **settings_defaults, - "notification_rules": notification_rule_defaults, }, } ) @@ -1735,6 +1698,25 @@ def normalize_action_id(action_id): merged_nodes + missing_mixed_action_nodes + missing_stage_nodes ) + stage_node_map = { + stage_id: node["id"] + for stage_id, node in updated_stage_nodes_by_stage_id.items() + } + notification_rule_defaults = [ + _serialize_notification_rule( + rule, + stage_node_id=stage_node_map.get(rule.stage_id), + ) + for rule in workflow.notification_rules.select_related("stage") + .prefetch_related("notify_groups") + .order_by("event", "stage_id", "id") + ] + for node in visual_data["nodes"]: + if node.get("type") == "workflow_settings": + node.setdefault("data", {})["notification_rules"] = ( + notification_rule_defaults + ) + def _canonical_node_id(node_id): if node_id is None: return None @@ -2227,11 +2209,21 @@ def graph_action_ids(graph): normalized_notification_cadence = ( settings_data.get("notification_cadence") or "immediate" ) + start_trigger_value = settings_data.get("start_trigger", "on_submission") + valid_start_triggers = { + choice[0] + for choice in WorkflowDefinition._meta.get_field("start_trigger").choices + } + if ( + not isinstance(start_trigger_value, str) + or start_trigger_value not in valid_start_triggers + ): + raise ValidationError({"start_trigger": "Unsupported start trigger."}) # ── Workflow-level settings ────────────────────────────────────────── wf_defaults = { "name_label": settings_data.get("name_label", ""), - "start_trigger": settings_data.get("start_trigger", "on_submission"), + "start_trigger": start_trigger_value, "requires_approval": settings_data.get("requires_approval", requires_approval), "visual_workflow_data": workflow_data, "notification_cadence": normalized_notification_cadence, diff --git a/tests/test_builders.py b/tests/test_builders.py index 37e6c80..40cf29f 100644 --- a/tests/test_builders.py +++ b/tests/test_builders.py @@ -1032,6 +1032,37 @@ def test_saved_numeric_string_stage_id_keeps_notification_rule_node( settings["data"]["notification_rules"][0]["stage_node_id"] == "saved-stage" ) + @pytest.mark.parametrize("settings_present", [False, True]) + def test_restored_stage_keeps_notification_rule_node( + self, form_definition, settings_present + ): + workflow = WorkflowDefinition.objects.create(form_definition=form_definition) + stage = workflow.stages.create(name="Restored", order=1) + NotificationRule.objects.create( + workflow=workflow, stage=stage, event="approval_request" + ) + workflow.visual_workflow_data = { + "nodes": ( + [{"id": "settings", "type": "workflow_settings", "data": {}}] + if settings_present + else [] + ), + "connections": [], + } + workflow.save(update_fields=["visual_workflow_data"]) + + visual = convert_workflow_to_visual(workflow, form_definition) + + stage_node = next(node for node in visual["nodes"] if node["type"] == "stage") + settings_node = next( + node for node in visual["nodes"] if node["type"] == "workflow_settings" + ) + assert stage_node["data"]["stage_id"] == stage.id + assert ( + settings_node["data"]["notification_rules"][0]["stage_node_id"] + == stage_node["id"] + ) + def test_loads_stage_approval_group_positions( self, staged_workflow, form_definition ): @@ -1090,6 +1121,24 @@ def _make_visual(self, stages=None, settings=None, actions=None): nodes.append({"type": "end", "data": {}}) return {"nodes": nodes, "connections": []} + @pytest.mark.parametrize("start_trigger", ["unsupported", [], None]) + def test_rejects_unsupported_start_trigger_without_modifying_workflow( + self, form_definition, start_trigger + ): + workflow = WorkflowDefinition.objects.create( + form_definition=form_definition, name_label="Original" + ) + visual = self._make_visual( + settings={"name_label": "Changed", "start_trigger": start_trigger} + ) + + with pytest.raises(ValidationError, match="start_trigger"): + convert_visual_to_workflow(visual, form_definition, workflow=workflow) + + workflow.refresh_from_db() + assert workflow.name_label == "Original" + assert workflow.start_trigger == "on_submission" + def test_creates_stages( self, form_with_fields, approval_group, second_approval_group ): diff --git a/tests/test_notifications.py b/tests/test_notifications.py index ea7ba17..ecb2eec 100644 --- a/tests/test_notifications.py +++ b/tests/test_notifications.py @@ -4411,6 +4411,14 @@ def test_taskless_final_notifications_keep_workflow_context_separate( ), ) + ApprovalTask.objects.create( + submission=submission, + step_name="Legacy review", + status="approved", + comments="Legacy workflow 1", + completed_by=approver_user, + ) + send_notification_rules(submission.pk, "workflow_approved") assert len(mailoutbox) == 2 @@ -4424,6 +4432,7 @@ def test_taskless_final_notifications_keep_workflow_context_separate( assert "Private to workflow 1" in first_task_comments assert "Private to workflow 2" not in first_public_comments assert "Private to workflow 2" not in first_task_comments + assert "Legacy workflow 1" in first_public_comments assert second.count("|") == 1 second_public_comments, second_task_comments = second.split("|", 1) @@ -4431,3 +4440,4 @@ def test_taskless_final_notifications_keep_workflow_context_separate( assert "Private to workflow 2" in second_task_comments assert "Private to workflow 1" not in second_public_comments assert "Private to workflow 1" not in second_task_comments + assert "Legacy workflow 1" not in second_public_comments