diff --git a/django_forms_workflows/static/django_forms_workflows/js/workflow-builder.js b/django_forms_workflows/static/django_forms_workflows/js/workflow-builder.js index 239a4cf5..deee2925 100644 --- a/django_forms_workflows/static/django_forms_workflows/js/workflow-builder.js +++ b/django_forms_workflows/static/django_forms_workflows/js/workflow-builder.js @@ -838,9 +838,30 @@ export class WorkflowBuilder { const content = document.getElementById('propertiesContent'); content.innerHTML = this.buildPropertiesForm(node); + if (node.type === 'stage') { + for (const name of ['name', 'order', 'approve_label']) { + const input = content.querySelector(`[name="${name}"]`); + if (input) input.value = node.data?.[name] ?? (name === 'order' ? 1 : ''); + } + content.querySelectorAll('[data-stage-group-id]').forEach(button => { + button.addEventListener('click', () => { + this.moveStageApprovalGroup( + node.id, + Number(button.dataset.stageGroupId), + Number(button.dataset.stageGroupDirection), + ); + }); + }); + } + // Add event listeners for property changes content.querySelectorAll('input, select, textarea').forEach(input => { input.addEventListener('change', (e) => { + if (e.target.hasAttribute('onchange') || !e.target.name) return; + if (node.type === 'stage') { + this.updateStageConfig(node.id); + return; + } let value = e.target.value; if (e.target.type === 'checkbox') { value = e.target.checked; @@ -924,33 +945,30 @@ export class WorkflowBuilder {
+ />
+ /> Stages with the same order number run in parallel (fork/join).
+ /> Custom label for the approve button (e.g. "Sign Off")
- -
@@ -958,10 +976,10 @@ export class WorkflowBuilder {
- -
@@ -970,10 +988,10 @@ export class WorkflowBuilder {
- -
@@ -982,10 +1000,10 @@ export class WorkflowBuilder {
- -
@@ -996,8 +1014,8 @@ export class WorkflowBuilder { let routingSection = `
- `; this.groups.forEach(group => { @@ -1015,7 +1033,7 @@ export class WorkflowBuilder {
+ + > ${this.fields.map(f => ` @@ -1052,7 +1070,7 @@ export class WorkflowBuilder {
-
@@ -1129,11 +1147,11 @@ export class WorkflowBuilder {
@@ -1152,9 +1170,9 @@ export class WorkflowBuilder {
+ onchange="workflowBuilder.updateWorkflowSettings(${this.inlineNodeId(node.id)})" /> Helpful when a form has multiple workflow tracks.
`; @@ -1164,26 +1182,25 @@ export class WorkflowBuilder { + onchange="workflowBuilder.updateWorkflowSettings(${this.inlineNodeId(node.id)})" />
+ onchange="workflowBuilder.updateWorkflowSettings(${this.inlineNodeId(node.id)})" />
+ onchange="workflowBuilder.updateWorkflowSettings(${this.inlineNodeId(node.id)})" />
+ value="${data.notification_cadence_day ?? ''}" placeholder="Weekly: 0-6, Monthly: 1-31" + onchange="workflowBuilder.updateWorkflowSettings(${this.inlineNodeId(node.id)})" /> Used for weekly and monthly cadences only.
+ value="${this.escapeHtmlAttribute(data.notification_cadence_time || '')}" + onchange="workflowBuilder.updateWorkflowSettings(${this.inlineNodeId(node.id)})" />
+ onchange="workflowBuilder.updateNotificationRules(${this.inlineNodeId(node.id)})"> ${stageOptions.map(option => ` @@ -1308,7 +1325,7 @@ export class WorkflowBuilder {
+ onchange="workflowBuilder.updateNotificationRules(${this.inlineNodeId(node.id)})" />
+ onchange="workflowBuilder.updateNotificationRules(${this.inlineNodeId(node.id)})" />
+ onchange="workflowBuilder.updateNotificationRules(${this.inlineNodeId(node.id)})">
@@ -1360,7 +1377,7 @@ export class WorkflowBuilder {
+ onchange="workflowBuilder.updateNotificationRules(${this.inlineNodeId(node.id)})">
@@ -1368,7 +1385,7 @@ export class WorkflowBuilder {
+ onchange="workflowBuilder.updateNotificationRules(${this.inlineNodeId(node.id)})">
@@ -1376,20 +1393,20 @@ export class WorkflowBuilder { ${this.buildConditionsEditor({ title: 'Rule conditions', conditions: state.conditions, - onChangeHandler: `workflowBuilder.updateNotificationRules('${node.id}')`, + onChangeHandler: `workflowBuilder.updateNotificationRules(${this.inlineNodeId(node.id)})`, editorKind: 'notification-rule', extraAttributes: `data-rule-index="${index}"`, - removeConditionHandler: `workflowBuilder.removeNotificationRuleCondition('${node.id}', ${index}, __INDEX__)`, + removeConditionHandler: `workflowBuilder.removeNotificationRuleCondition(${this.inlineNodeId(node.id)}, ${index}, __INDEX__)`, })}
`; }).join('')} - `; @@ -1473,7 +1490,7 @@ export class WorkflowBuilder {
@@ -1515,13 +1532,13 @@ export class WorkflowBuilder { ${this.buildConditionsEditor({ title, conditions: node.data.trigger_conditions, - onChangeHandler: `workflowBuilder.updateNodeTriggerConditions('${node.id}')`, + onChangeHandler: `workflowBuilder.updateNodeTriggerConditions(${this.inlineNodeId(node.id)})`, editorKind: 'node-trigger', - removeConditionHandler: `workflowBuilder.removeTriggerCondition('${node.id}', __INDEX__)`, + removeConditionHandler: `workflowBuilder.removeTriggerCondition(${this.inlineNodeId(node.id)}, __INDEX__)`, showHeader: false, })} `; @@ -1550,7 +1567,7 @@ export class WorkflowBuilder { html += `
- `; @@ -1569,7 +1586,7 @@ export class WorkflowBuilder { html += `
- +
`; } @@ -1679,7 +1696,7 @@ export class WorkflowBuilder { let html = `
- +
@@ -1722,11 +1739,11 @@ export class WorkflowBuilder { return `
- +
- @@ -1735,7 +1752,7 @@ export class WorkflowBuilder {
- @@ -1745,7 +1762,7 @@ export class WorkflowBuilder {
- + Action-specific configuration in JSON format
`; @@ -1762,16 +1779,16 @@ export class WorkflowBuilder { return `
- +
- + Comma-separated email addresses.
- ${fieldOptions} @@ -1779,18 +1796,18 @@ export class WorkflowBuilder {
- +
- ${ccFieldOptions}
- @@ -1799,15 +1816,15 @@ export class WorkflowBuilder {
- +
- +
- +
`; } @@ -1833,7 +1850,7 @@ export class WorkflowBuilder {
The workflow definition used for each sub-workflow instance @@ -1842,16 +1859,16 @@ export class WorkflowBuilder {
+ onchange="workflowBuilder.updateSubWorkflowConfig(${this.inlineNodeId(node.id)})" /> Heading shown to end users in approval history. If blank, uses the workflow name.
Form field whose value determines how many sub-workflows to spawn @@ -1860,8 +1877,8 @@ export class WorkflowBuilder {
+ value="${this.escapeHtmlAttribute(data.label_template || 'Sub-workflow {index}')}" + onchange="workflowBuilder.updateSubWorkflowConfig(${this.inlineNodeId(node.id)})" /> Use {index} as placeholder (e.g. "Payment {index}")
`; @@ -1870,7 +1887,7 @@ export class WorkflowBuilder {
@@ -1879,17 +1896,17 @@ export class WorkflowBuilder {
+ value="${this.escapeHtmlAttribute(data.data_prefix || '')}" + onchange="workflowBuilder.updateSubWorkflowConfig(${this.inlineNodeId(node.id)})" /> Field prefix to scope data per instance (e.g. "payment" matches payment_type_1, payment_amount_1 …)
- -
@@ -1898,10 +1915,10 @@ export class WorkflowBuilder {
- -
@@ -2006,13 +2023,13 @@ export class WorkflowBuilder { node.data.name = container.querySelector('input[name="name"]').value; node.data.order = parseInt(container.querySelector('input[name="order"]').value) || 1; node.data.approve_label = container.querySelector('input[name="approve_label"]').value; - node.data.requires_manager_approval = container.querySelector(`#stage_requires_manager_${nodeId}`).checked; - node.data.allow_send_back = container.querySelector(`#stage_allow_send_back_${nodeId}`).checked; - node.data.allow_reassign = container.querySelector(`#stage_allow_reassign_${nodeId}`).checked; - node.data.allow_edit_form_data = container.querySelector(`#stage_allow_edit_form_data_${nodeId}`).checked; + node.data.requires_manager_approval = container.querySelector('[name="requires_manager_approval"]').checked; + node.data.allow_send_back = container.querySelector('[name="allow_send_back"]').checked; + node.data.allow_reassign = container.querySelector('[name="allow_reassign"]').checked; + node.data.allow_edit_form_data = container.querySelector('[name="allow_edit_form_data"]').checked; node.data.assignee_form_field = container.querySelector('select[name="assignee_form_field"]').value; node.data.assignee_lookup_type = container.querySelector('select[name="assignee_lookup_type"]').value; - node.data.validate_assignee_group = container.querySelector(`#stage_validate_assignee_group_${nodeId}`).checked; + node.data.validate_assignee_group = container.querySelector('[name="validate_assignee_group"]').checked; node.data.trigger_conditions = this.readNodeTriggerConditions(container); node.data.approval_groups = this.readStageApprovalGroupsFromPanel( container, @@ -2087,28 +2104,31 @@ export class WorkflowBuilder { } readStageApprovalGroupsFromPanel(container, nodeId, existingGroups) { - const groupSelect = container.querySelector(`#stage_groups_${nodeId}`); + const groupSelect = container.querySelector('[name="approval_groups"]'); + if (!groupSelect) return []; const selected = Array.from(groupSelect.selectedOptions).map(opt => ({ - id: parseInt(opt.value), + id: parseInt(opt.value, 10), name: opt.text, - })); + })).filter(group => !Number.isNaN(group.id)); + const selectedIds = new Set(selected.map(group => group.id)); const existingOrdered = this.getNormalizedStageApprovalGroups(existingGroups || []); const existingMap = new Map(existingOrdered.map(group => [group.id, group])); - const kept = existingOrdered.filter(group => selected.some(sel => sel.id === group.id)); + const kept = existingOrdered.filter(group => selectedIds.has(group.id)); const appended = selected .filter(group => !existingMap.has(group.id)) - .map(group => ({ id: group.id, name: group.name })); + .map(group => ({ id: group.id, name: group.name, role: 'approval' })); return [...kept, ...appended].map((group, index) => ({ id: group.id, name: group.name, + role: group.role || 'approval', position: index, })); } readStageApprovalFieldsFromPanel(container, nodeId) { - const fieldSelect = container.querySelector(`#stage_fields_${nodeId}`); + const fieldSelect = container.querySelector('[name="approval_fields"]'); if (!fieldSelect) { return []; } @@ -2325,6 +2345,19 @@ export class WorkflowBuilder { return div.innerHTML; } + escapeHtmlAttribute(value) { + return String(value) + .replace(/&/g, '&') + .replace(/"/g, '"') + .replace(/'/g, ''') + .replace(//g, '>'); + } + + inlineNodeId(nodeId) { + return this.escapeHtmlAttribute(JSON.stringify(String(nodeId))); + } + addNodeIssue(result, nodeId, severity, message) { if (!nodeId) return; if (!result.nodeIssues[nodeId]) { @@ -2653,13 +2686,13 @@ export class WorkflowBuilder {
${canDelete ? `
-
` : ''} -
-
+
+
`; // Add connection point event listeners diff --git a/django_forms_workflows/workflow_builder_views.py b/django_forms_workflows/workflow_builder_views.py index 07f536c1..9cb09035 100644 --- a/django_forms_workflows/workflow_builder_views.py +++ b/django_forms_workflows/workflow_builder_views.py @@ -31,6 +31,11 @@ logger = logging.getLogger(__name__) + +class BuilderValidationError(ValidationError): + """A user-facing error produced by the workflow builder's own validators.""" + + SUPPORTED_CONDITION_OPERATORS = { "equals", "not_equals", @@ -815,7 +820,7 @@ def is_valid_field_name(value): def _validate_visual_workflow(workflow_data, form_definition, workflow=None): errors = _collect_visual_workflow_errors(workflow_data, form_definition, workflow) if errors: - raise ValidationError(errors) + raise BuilderValidationError(errors) def _serialize_notification_rule(rule, stage_node_id=None): @@ -1190,6 +1195,16 @@ def parse_positive_pk(value, field_name, *, allow_empty=False): return JsonResponse( {"success": False, "error": "Invalid JSON data"}, status=400 ) + except BuilderValidationError as exc: + logger.info("Workflow validation failed: %s", exc) + return JsonResponse( + { + "success": False, + "error": "Workflow validation failed.", + "errors": exc.messages, + }, + status=400, + ) except ValidationError as exc: logger.warning("Workflow validation failed: %s", exc) return JsonResponse( @@ -2551,7 +2566,7 @@ def graph_action_ids(graph): conflicting_ids_display = ", ".join( str(fid) for fid in sorted(conflicting_field_ids) ) - raise ValidationError( + raise BuilderValidationError( "Approval fields already assigned to another workflow track " f"cannot be reused here: {conflicting_ids_display}." ) diff --git a/tests/test_builders.py b/tests/test_builders.py index 1d125e5f..65b60d7c 100644 --- a/tests/test_builders.py +++ b/tests/test_builders.py @@ -1090,7 +1090,7 @@ class TestConvertVisualToWorkflow: """Tests for converting visual node graph → WorkflowDefinition + stages.""" def test_rejects_approval_field_owned_by_another_track( - self, form_with_fields, approval_group + self, form_with_fields, approval_group, client, superuser ): first = WorkflowDefinition.objects.create(form_definition=form_with_fields) first_stage = first.stages.create(name="First review", order=1) @@ -1109,7 +1109,24 @@ def test_rejects_approval_field_owned_by_another_track( ) with pytest.raises(ValidationError, match="another workflow track"): - convert_visual_to_workflow(visual, form_with_fields, workflow=second) + convert_visual_to_workflow( + copy.deepcopy(visual), form_with_fields, workflow=second + ) + + client.force_login(superuser) + response = client.post( + _wf_url("workflow/api/save/"), + data=json.dumps( + { + "form_id": form_with_fields.id, + "workflow_id": second.id, + "workflow": visual, + } + ), + content_type="application/json", + ) + assert response.status_code == 400 + assert "another workflow track" in response.json()["errors"][0] field.refresh_from_db() assert field.workflow_stage_id == first_stage.id diff --git a/tests_js/workflow-builder/showNodeProperties.test.js b/tests_js/workflow-builder/showNodeProperties.test.js index 6a111b15..8e8dc95d 100644 --- a/tests_js/workflow-builder/showNodeProperties.test.js +++ b/tests_js/workflow-builder/showNodeProperties.test.js @@ -15,6 +15,7 @@ function createInstance() { const instance = Object.create(WorkflowBuilder.prototype); instance.store = createWorkflowBuilderStore(); instance.render = vi.fn(); + instance.validationState = { nodeIssues: {} }; return instance; } @@ -34,7 +35,7 @@ afterEach(() => { describe('WorkflowBuilder#showNodeProperties generic change listener', () => { it('stores a checkbox\'s checked state as a real boolean, not its "on" value attribute', () => { const instance = createInstance(); - const node = { id: 'node_1', type: 'stage', data: { requires_manager_approval: false } }; + const node = { id: 'node_1', type: 'condition', data: { requires_manager_approval: false } }; instance.nodes = [node]; instance.buildPropertiesForm = vi.fn( () => '' @@ -50,7 +51,7 @@ describe('WorkflowBuilder#showNodeProperties generic change listener', () => { it('stores an unchecked checkbox as false, not the string "on"', () => { const instance = createInstance(); - const node = { id: 'node_1', type: 'stage', data: { allow_send_back: true } }; + const node = { id: 'node_1', type: 'condition', data: { allow_send_back: true } }; instance.nodes = [node]; instance.buildPropertiesForm = vi.fn( () => '' @@ -66,7 +67,7 @@ describe('WorkflowBuilder#showNodeProperties generic change listener', () => { it('still forwards the typed value for non-checkbox inputs', () => { const instance = createInstance(); - const node = { id: 'node_1', type: 'stage', data: { approve_label: '' } }; + const node = { id: 'node_1', type: 'condition', data: { approve_label: '' } }; instance.nodes = [node]; instance.buildPropertiesForm = vi.fn( () => '' @@ -79,4 +80,91 @@ describe('WorkflowBuilder#showNodeProperties generic change listener', () => { expect(node.data.approve_label).toBe('Sign Off'); }); + + it('does not overwrite values managed by a specialized change handler', () => { + const instance = createInstance(); + const node = { id: 'node_1', type: 'condition', data: { approval_groups: [{ id: 1 }] } }; + instance.nodes = [node]; + instance.buildPropertiesForm = vi.fn( + () => '' + ); + const updateProperty = vi.spyOn(instance, 'updateNodeProperty'); + + instance.showNodeProperties(node); + dispatchChange(document.querySelector('[name="approval_groups"]')); + + expect(updateProperty).not.toHaveBeenCalled(); + expect(node.data.approval_groups).toEqual([{ id: 1 }]); + }); +}); + +describe('WorkflowBuilder stage editor', () => { + it('assigns saved text through input properties without injecting markup', () => { + const instance = createInstance(); + const node = { + id: `stage'" onclick="alert(1)`, + type: 'stage', + data: { name: 'Review" autofocus onfocus="alert(1)', approve_label: 'Sign "Off"', order: 2 }, + }; + instance.nodes = [node]; + instance.groups = []; + instance.fields = []; + + instance.showNodeProperties(node); + + expect(document.querySelector('[name="name"]').value).toBe(node.data.name); + expect(document.querySelector('[name="approve_label"]').value).toBe(node.data.approve_label); + expect(document.querySelector('[name="name"]').hasAttribute('autofocus')).toBe(false); + expect(document.querySelector('[name="name"]').hasAttribute('onclick')).toBe(false); + }); + + it('preserves group roles and approval field arrays on a stage change', () => { + const instance = createInstance(); + const node = { + id: 'stage_1', + type: 'stage', + data: { + name: 'Review', + approval_groups: [ + { id: 1, name: 'Reviewers', role: 'approval', position: 0 }, + { id: 1, name: 'Reviewers', role: 'validation', position: 1 }, + ], + approval_fields: [{ id: 2, field_name: 'notes' }], + }, + }; + instance.nodes = [node]; + instance.groups = [{ id: 1, name: 'Reviewers' }]; + instance.fields = [{ id: 2, field_name: 'notes', field_label: 'Notes' }]; + instance.selectNode = vi.fn(); + + instance.showNodeProperties(node); + const input = document.querySelector('[name="name"]'); + input.value = 'Updated'; + dispatchChange(input); + + expect(node.data.name).toBe('Updated'); + expect(node.data.approval_groups.map(group => group.role)).toEqual(['approval', 'validation']); + expect(node.data.approval_fields.map(field => field.id)).toEqual([2]); + }); +}); + +describe('WorkflowBuilder workflow settings editor', () => { + it('keeps weekly day zero visible and omits unsupported daily cadence', () => { + const instance = createInstance(); + instance.fields = []; + instance.groups = []; + const node = { id: 'settings', type: 'workflow_settings', data: { notification_cadence: 'weekly', notification_cadence_day: 0 } }; + instance.nodes = [node]; + instance.selectNode = vi.fn(); + + instance.showNodeProperties(node); + + expect(document.querySelector('[name="notification_cadence_day"]').value).toBe('0'); + expect(document.querySelector('option[value="daily"]')).toBeNull(); + + const label = document.querySelector('[name="name_label"]'); + label.value = 'Updated track'; + instance.updateWorkflowSettings(node.id); + expect(node.data.notification_cadence_day).toBe(0); + }); });