diff --git a/frontend/src/stores/crm.js b/frontend/src/stores/crm.js index aa7ec7b..f220586 100644 --- a/frontend/src/stores/crm.js +++ b/frontend/src/stores/crm.js @@ -3,7 +3,7 @@ import api from '../api' export const useCrmStore = defineStore('crm', { state: () => ({ - activeTab: 'leads', // 'leads' | 'opportunities' | 'contacts' | 'accounts' | 'custom_objects' | 'flows' | 'outreach' | 'tasks' + activeTab: 'leads', currentRecord: null, leads: [], opportunities: [], @@ -11,6 +11,7 @@ export const useCrmStore = defineStore('crm', { accounts: [], activities: [], customObjects: [], + customFields: [], customRecords: {}, flows: [], campaigns: [], @@ -30,6 +31,11 @@ export const useCrmStore = defineStore('crm', { console.error(err) } }, + async createLead(leadData) { + const res = await api.post('/leads/', leadData) + await this.fetchLeads() + return res.data + }, async fetchOpportunities() { try { const res = await api.get('/opportunities/') @@ -38,6 +44,11 @@ export const useCrmStore = defineStore('crm', { console.error(err) } }, + async createOpportunity(oppData) { + const res = await api.post('/opportunities/', oppData) + await this.fetchOpportunities() + return res.data + }, async fetchContacts() { try { const res = await api.get('/contacts/') @@ -46,6 +57,11 @@ export const useCrmStore = defineStore('crm', { console.error(err) } }, + async createContact(contactData) { + const res = await api.post('/contacts/', contactData) + await this.fetchContacts() + return res.data + }, async fetchAccounts() { try { const res = await api.get('/accounts/') @@ -54,6 +70,11 @@ export const useCrmStore = defineStore('crm', { console.error(err) } }, + async createAccount(accountData) { + const res = await api.post('/accounts/', accountData) + await this.fetchAccounts() + return res.data + }, async fetchActivities() { try { const res = await api.get('/activities/') @@ -62,6 +83,16 @@ export const useCrmStore = defineStore('crm', { console.error(err) } }, + async createActivity(activityData) { + const res = await api.post('/activities/', activityData) + await this.fetchActivities() + return res.data + }, + async updateActivityStatus(activityId, status) { + const res = await api.patch(`/activities/${activityId}/`, { status }) + await this.fetchActivities() + return res.data + }, async fetchCustomObjects() { try { const res = await api.get('/custom-objects/') @@ -70,6 +101,31 @@ export const useCrmStore = defineStore('crm', { console.error(err) } }, + async createCustomObject(objData) { + const res = await api.post('/custom-objects/', objData) + await this.fetchCustomObjects() + return res.data + }, + async createCustomField(fieldData) { + const res = await api.post('/custom-fields/', fieldData) + await this.fetchCustomObjects() + return res.data + }, + async fetchCustomRecords(objectName) { + try { + const res = await api.get(`/custom/${objectName}/`) + this.customRecords[objectName] = res.data.results || res.data + return this.customRecords[objectName] + } catch (err) { + console.error(err) + return [] + } + }, + async insertCustomRecord(objectName, data) { + const res = await api.post(`/custom/${objectName}/`, { data }) + await this.fetchCustomRecords(objectName) + return res.data + }, async fetchFlows() { try { const res = await api.get('/flows/') @@ -86,6 +142,16 @@ export const useCrmStore = defineStore('crm', { console.error(err) } }, + async createCampaign(campaignData) { + const res = await api.post('/campaigns/', campaignData) + await this.fetchCampaigns() + return res.data + }, + async dispatchCampaign(campaignId) { + const res = await api.post(`/campaigns/${campaignId}/dispatch/`) + await this.fetchCampaigns() + return res.data + }, async convertLead(leadId, payload) { const res = await api.post(`/leads/${leadId}/convert/`, payload) await this.fetchLeads() diff --git a/frontend/src/views/CustomObjectsView.vue b/frontend/src/views/CustomObjectsView.vue index e003a70..d479351 100644 --- a/frontend/src/views/CustomObjectsView.vue +++ b/frontend/src/views/CustomObjectsView.vue @@ -1,151 +1,235 @@ @@ -68,9 +99,22 @@ import { useCrmStore } from '../stores/crm' const crmStore = useCrmStore() const showDispatchModal = ref(false) +const newCampaign = ref({ + name: '', + subject: '', + target_object: 'Lead' +}) + function getStatusClass(status) { if (status === 'Sent') return 'bg-emerald-50 text-emerald-700 border border-emerald-200 px-2 py-0.5 rounded text-[11px] font-medium' if (status === 'Sending') return 'bg-blue-50 text-blue-700 border border-blue-200 px-2 py-0.5 rounded text-[11px] font-medium animate-pulse' return 'bg-slate-100 text-slate-700 px-2 py-0.5 rounded text-[11px] font-medium' } + +async function handleLaunchCampaign() { + if (!newCampaign.value.name || !newCampaign.value.subject) return + await crmStore.createCampaign(newCampaign.value) + showDispatchModal.value = false + newCampaign.value = { name: '', subject: '', target_object: 'Lead' } +} diff --git a/tests/flow_engine/test_diamond_join.py b/tests/flow_engine/test_diamond_join.py new file mode 100644 index 0000000..02df10a --- /dev/null +++ b/tests/flow_engine/test_diamond_join.py @@ -0,0 +1,62 @@ +import pytest +from workflows.engine import execute_flow_dag + +def test_diamond_rejoin_execution(): + """ + Graph Topology: + start -> decision + decision -> (winning handle) -> node_a -> join_node + decision -> (losing handle) -> node_b -> join_node + Both node_a and node_b connect to join_node. + join_node must execute when branch A is chosen. + node_b must NOT execute. + """ + graph = { + "nodes": [ + {"id": "start", "type": "trigger", "data": {}}, + { + "id": "decision", + "type": "decision", + "data": { + "outcomes": [ + { + "id": "path_a", + "rules": [{"field": "status", "operator": "equals", "value": "A"}] + }, + { + "id": "path_b", + "rules": [{"field": "status", "operator": "equals", "value": "B"}] + } + ] + } + }, + { + "id": "node_a", + "type": "assignment", + "data": {"variable": "executed_a", "operator": "equals", "value": True} + }, + { + "id": "node_b", + "type": "assignment", + "data": {"variable": "executed_b", "operator": "equals", "value": True} + }, + { + "id": "join_node", + "type": "assignment", + "data": {"variable": "executed_join", "operator": "equals", "value": True} + } + ], + "edges": [ + {"source": "start", "target": "decision"}, + {"source": "decision", "target": "node_a", "sourceHandle": "path_a"}, + {"source": "decision", "target": "node_b", "sourceHandle": "path_b"}, + {"source": "node_a", "target": "join_node"}, + {"source": "node_b", "target": "join_node"} + ] + } + + result = execute_flow_dag(graph, initial_context={"status": "A"}) + ctx = result if isinstance(result, dict) else result.context + 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" diff --git a/tests/flow_engine/test_rollback.py b/tests/flow_engine/test_rollback.py new file mode 100644 index 0000000..097fbf0 --- /dev/null +++ b/tests/flow_engine/test_rollback.py @@ -0,0 +1,38 @@ +import pytest +from django.db import transaction +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(): + """ + Test that an active record-triggered flow failure rolls back the triggering record + outside of implicit test transactions. + """ + # 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 + ], + "edges": [ + {"source": "start", "target": "step_fail"} + ] + } + FlowDefinition.objects.create( + name="Failing Trigger Flow", + trigger_type="record_created", + trigger_object="Account", + is_active=True, + 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) + + # 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!" diff --git a/tests/flow_engine/test_vue_contract.py b/tests/flow_engine/test_vue_contract.py new file mode 100644 index 0000000..23c4e27 --- /dev/null +++ b/tests/flow_engine/test_vue_contract.py @@ -0,0 +1,70 @@ +import pytest +from workflows.engine import execute_flow_dag +from workflows.models import FlowDefinition + +@pytest.mark.django_db +def test_vue_flow_initial_graph_executes_successfully(): + subflow = FlowDefinition.objects.create( + name="Child Sync Subflow", + graph={"nodes": [{"id": "sub_start", "type": "trigger", "data": {}}], "edges": []} + ) + + vue_graph = { + "nodes": [ + { + "id": "start-trigger", + "type": "input", + "data": {"type": "trigger"} + }, + { + "id": "decision-tier", + "type": "decision", + "data": { + "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" + } + }, + { + "id": "assign-vip", + "type": "assignment", + "data": { + "assignments": [ + {"variable": "account_tier", "op": "equals", "value": "VIP"}, + {"variable": "priority_score", "op": "add", "value": 100} + ] + } + }, + { + "id": "assign-standard", + "type": "assignment", + "data": { + "assignments": [ + {"variable": "account_tier", "op": "equals", "value": "Standard"}, + {"variable": "priority_score", "op": "add", "value": 10} + ] + } + }, + { + "id": "subflow-sync", + "type": "subflow", + "data": { + "subflow_id": subflow.id + } + } + ], + "edges": [ + {"id": "e1-2", "source": "start-trigger", "target": "decision-tier"}, + {"id": "e2-3", "source": "decision-tier", "target": "assign-vip"}, + {"id": "e2-4", "source": "decision-tier", "target": "assign-standard"}, + {"id": "e3-5", "source": "assign-vip", "target": "subflow-sync"}, + {"id": "e4-5", "source": "assign-standard", "target": "subflow-sync"} + ] + } + + res = execute_flow_dag(vue_graph, initial_context={"amount": 75000}) + ctx = res if isinstance(res, dict) else res.context + assert ctx.get("account_tier") == "VIP", f"Expected VIP, got {ctx.get('account_tier')}" + assert ctx.get("priority_score") == 100, f"Expected 100, got {ctx.get('priority_score')}" diff --git a/workflows/dispatcher.py b/workflows/dispatcher.py index d30307a..d363ffd 100644 --- a/workflows/dispatcher.py +++ b/workflows/dispatcher.py @@ -104,9 +104,9 @@ def on_record_post_save(sender, instance, created, **kwargs): _set_active_flow_depth(depth + 1) try: for flow in flows: - try: - dispatch_flow(flow, context=context) - except Exception as e: - logger.error(f"Error executing flow {flow.id} on {trigger_type}: {e}") + # 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) finally: _set_active_flow_depth(depth) diff --git a/workflows/engine.py b/workflows/engine.py index ade9e38..7d5ea4e 100644 --- a/workflows/engine.py +++ b/workflows/engine.py @@ -123,6 +123,34 @@ def evaluate_outcome(outcome, context): return False +def _evaluate_decision_node(node_data, context): + """ + Evaluates a Decision node either using outcomes list or conditions list. + Returns (matched_handle, target_node_id). + """ + outcomes = node_data.get('outcomes', []) + if outcomes: + for outcome in outcomes: + conds = outcome.get('conditions', []) + logic = outcome.get('logic', 'ALL') + if _evaluate_condition(conds, logic, context): + return outcome.get('handle', 'default'), outcome.get('target_node') + return 'default', node_data.get('default_target_node') + + conditions = node_data.get('conditions', []) + if conditions: + for cond in conditions: + field = cond.get('field') + op = cond.get('op') or cond.get('operator') + val = cond.get('value') + target = cond.get('target_node') + if _evaluate_single_condition(field, op, val, context): + return 'match', target + return 'default', node_data.get('default_target_node') + + return 'default', node_data.get('default_target_node') + + def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None, depth=0): from .models import FlowDefinition, FlowExecutionLog @@ -192,7 +220,7 @@ 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') + node_type = node.get('type') or node_data.get('type') node_data = node.get('data', {}) step_record = { @@ -233,46 +261,99 @@ def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None, inst.save() elif node_type == 'assignment': - var_name = node_data.get('variable') - op = node_data.get('operator', 'equals') - val = node_data.get('value') - if var_name: - if op in ('equals', '=', None): - context[var_name] = val - elif op in ('add', '+='): - curr = context.get(var_name, 0) - context[var_name] = curr + val - elif op in ('subtract', '-='): - curr = context.get(var_name, 0) - context[var_name] = curr - val + # Handle single assignment fields or assignments array + assignments = node_data.get('assignments') + if assignments and isinstance(assignments, list): + for item in assignments: + var_name = item.get('variable') + op = item.get('op') or item.get('operator', 'equals') + val = item.get('value') + if var_name: + if op in ('equals', '=', None): + context[var_name] = val + elif op in ('add', '+='): + curr = context.get(var_name, 0) + context[var_name] = curr + val + elif op in ('subtract', '-='): + curr = context.get(var_name, 0) + context[var_name] = curr - val + else: + var_name = node_data.get('variable') + op = node_data.get('operator', 'equals') + val = node_data.get('value') + if var_name: + if op in ('equals', '=', None): + context[var_name] = val + elif op in ('add', '+='): + curr = context.get(var_name, 0) + context[var_name] = curr + val + elif op in ('subtract', '-='): + curr = context.get(var_name, 0) + context[var_name] = curr - val elif node_type == 'decision': outcomes = node_data.get('outcomes', []) + conditions = node_data.get('conditions', []) winning_handle = None - for outcome in outcomes: - if evaluate_outcome(outcome, context): - winning_handle = outcome.get('id') - break + direct_target = None - # Disable paths from unchosen handles + if outcomes: + for outcome in outcomes: + if evaluate_outcome(outcome, context): + winning_handle = outcome.get('id') + break + elif conditions: + for cond in conditions: + field = cond.get('field') + op = cond.get('op') or cond.get('operator') + val = cond.get('value') + tgt = cond.get('target_node') + if evaluate_condition({'field': field, 'operator': op, 'value': val}, context): + direct_target = tgt + break + if not direct_target: + direct_target = node_data.get('default_target_node') or node_data.get('default_target') + + # The decision routes only down the winning outcome handle or direct target node_edges = outgoing_edges.get(node_id, []) + chosen_targets = set() + unchosen_targets = set() for e in node_edges: handle = e.get('sourceHandle') target = e.get('target') - if handle != winning_handle: - # Disable target and all downstream exclusively reached nodes - downstream = [target] - visited_sub = set() - while downstream: - d = downstream.pop() - if d not in visited_sub: - visited_sub.add(d) - disabled_nodes.add(d) - for nxt_edge in outgoing_edges.get(d, []): - downstream.append(nxt_edge.get('target')) + if direct_target: + if target == direct_target: + chosen_targets.add(target) + else: + unchosen_targets.add(target) + elif winning_handle: + if handle == winning_handle: + chosen_targets.add(target) + else: + unchosen_targets.add(target) + else: + unchosen_targets.add(target) + + # For every unchosen target branch, disable it ONLY if it is not reachable + # from any chosen branch (handles diamond join topologies) + def get_all_reachable(starts): + reachable = set() + queue = list(starts) + while queue: + curr = queue.pop() + if curr not in reachable: + reachable.add(curr) + for nxt_edge in outgoing_edges.get(curr, []): + queue.append(nxt_edge.get('target')) + return reachable + + chosen_reachable = get_all_reachable(chosen_targets) + unchosen_exclusive = get_all_reachable(unchosen_targets) - chosen_reachable + for d in unchosen_exclusive: + disabled_nodes.add(d) elif node_type == 'subflow': - child_flow_id = node_data.get('flow_id') + 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()