Skip to main content

loops_so/client/
workflow_nodes.rs

1//! Workflow node endpoints.
2//!
3//! Node payloads are polymorphic on `typeName`, and the generated models
4//! flatten those unions badly (a node read keeps only its revision ID), so
5//! node reads and node mutations return the response body as JSON.
6
7use serde_json::Value;
8
9use super::params::node_type_name;
10use super::workflows::{queued_contact_policy_value, revision_body};
11use super::{DeleteNodeOptions, LoopsClient, NodePlacement};
12use crate::error::Result;
13use crate::generated::{
14    AddWorkflowBranchRequestParams, AddWorkflowBranchResponse, AddWorkflowBranchResponseEnum,
15    CreateWorkflowNodeTypeName, DeleteWorkflowNodeRecursivelyRequest,
16    DeleteWorkflowNodeRequestParams, DeleteWorkflowNodeResponse, DeleteWorkflowNodeResponseEnum,
17    EmailMetricsResponse, GetWorkflowNodeMetricsRequest, GetWorkflowNodeMetricsResponse,
18};
19use crate::routes::Route;
20
21impl LoopsClient {
22    /// Get a workflow node as JSON; its shape depends on `typeName`.
23    pub async fn get_workflow_node(&self, workflow_id: &str, node_id: &str) -> Result<Value> {
24        let raw = self
25            .send(Route::GetWorkflowNode, &[workflow_id, node_id], |r| r)
26            .await?;
27        raw.parse_json("get workflow node")
28    }
29
30    /// All-time engagement metrics of a `SendEmailAction` node. Any other
31    /// node type fails with 400; a node that has not sent yet reports zeros.
32    pub async fn get_workflow_node_metrics(
33        &self,
34        workflow_id: &str,
35        node_id: &str,
36    ) -> Result<EmailMetricsResponse> {
37        const ACTION: &str = "get workflow node metrics";
38        let raw = self
39            .send(
40                Route::GetWorkflowNodeMetrics,
41                &[workflow_id, node_id],
42                |r| r,
43            )
44            .await?;
45        match raw
46            .parse(ACTION, GetWorkflowNodeMetricsRequest::parse_response)
47            .await?
48        {
49            GetWorkflowNodeMetricsResponse::Ok(metrics) => Ok(metrics),
50            _ => Err(raw.unexpected(ACTION)),
51        }
52    }
53
54    /// Add a node to a workflow at `placement`. The node is created with
55    /// default settings; configure it with
56    /// [`update_workflow_node`](Self::update_workflow_node).
57    ///
58    /// Returns the response as JSON: the created `node` and the updated
59    /// `workflow`.
60    pub async fn create_workflow_node(
61        &self,
62        workflow_id: &str,
63        node_type: CreateWorkflowNodeTypeName,
64        expected_revision_id: Option<&str>,
65        placement: NodePlacement,
66    ) -> Result<Value> {
67        let mut body = revision_body(expected_revision_id);
68        body.insert("nodeTypeName".to_owned(), node_type_name(&node_type));
69        let (mode, from, to) = match placement {
70            NodePlacement::Between {
71                from_node_id,
72                to_node_id,
73            } => ("between", Some(from_node_id), Some(to_node_id)),
74            NodePlacement::Before { to_node_id } => ("before", None, Some(to_node_id)),
75            NodePlacement::After { from_node_id } => ("after", Some(from_node_id), None),
76        };
77        body.insert("insertMode".to_owned(), Value::from(mode));
78        if let Some(from) = from {
79            body.insert("fromNodeId".to_owned(), Value::from(from));
80        }
81        if let Some(to) = to {
82            body.insert("toNodeId".to_owned(), Value::from(to));
83        }
84        let raw = self
85            .send(Route::CreateWorkflowNode, &[workflow_id], |r| r.json(&body))
86            .await?;
87        raw.parse_json("create workflow node")
88    }
89
90    /// Update a node's settings. `payload` holds the node-type-specific
91    /// fields, e.g. `{"amount": 2, "unit": "d"}` for a `TimerAction`.
92    ///
93    /// Returns the response as JSON: the updated node's fields plus the
94    /// latest `workflow`.
95    pub async fn update_workflow_node(
96        &self,
97        workflow_id: &str,
98        node_id: &str,
99        expected_revision_id: Option<&str>,
100        payload: Value,
101    ) -> Result<Value> {
102        let mut body = revision_body(expected_revision_id);
103        body.insert("payload".to_owned(), payload);
104        let raw = self
105            .send(Route::UpdateWorkflowNode, &[workflow_id, node_id], |r| {
106                r.json(&body)
107            })
108            .await?;
109        raw.parse_json("update workflow node")
110    }
111
112    /// Add an unconfigured branch to a `BranchNode` or `ExperimentBranchNode`.
113    pub async fn add_workflow_branch(
114        &self,
115        workflow_id: &str,
116        node_id: &str,
117        expected_revision_id: Option<&str>,
118    ) -> Result<AddWorkflowBranchResponse> {
119        const ACTION: &str = "add workflow branch";
120        let body = revision_body(expected_revision_id);
121        let raw = self
122            .send(Route::AddWorkflowBranch, &[workflow_id, node_id], |r| {
123                r.json(&body)
124            })
125            .await?;
126        match raw
127            .parse(ACTION, AddWorkflowBranchRequestParams::parse_response)
128            .await?
129        {
130            AddWorkflowBranchResponseEnum::Ok(response) => Ok(response),
131            _ => Err(raw.unexpected(ACTION)),
132        }
133    }
134
135    /// Move the single outgoing connection of `node_id` to
136    /// `new_target_node_id`. Branch nodes have several outputs and cannot be
137    /// rerouted this way; the old target must keep another incoming
138    /// connection.
139    ///
140    /// Returns the response as JSON: the updated source node plus the latest
141    /// `workflow`.
142    pub async fn reroute_workflow_node_connection(
143        &self,
144        workflow_id: &str,
145        node_id: &str,
146        expected_revision_id: Option<&str>,
147        new_target_node_id: &str,
148    ) -> Result<Value> {
149        let mut body = revision_body(expected_revision_id);
150        body.insert(
151            "newTargetNodeId".to_owned(),
152            Value::from(new_target_node_id),
153        );
154        let raw = self
155            .send(Route::RerouteNodeConnection, &[workflow_id, node_id], |r| {
156                r.json(&body)
157            })
158            .await?;
159        raw.parse_json("reroute workflow node connection")
160    }
161
162    /// Delete a node, or with [`DeleteNodeOptions::recursive`] the node and
163    /// everything downstream of it.
164    ///
165    /// With `dry_run`, or when contacts are queued at the node, Loops answers
166    /// with a preview instead of deleting.
167    pub async fn delete_workflow_node(
168        &self,
169        workflow_id: &str,
170        node_id: &str,
171        expected_revision_id: Option<&str>,
172        options: DeleteNodeOptions,
173    ) -> Result<DeleteWorkflowNodeResponse> {
174        const ACTION: &str = "delete workflow node";
175        let mut body = revision_body(expected_revision_id);
176        if let Some(dry_run) = options.dry_run {
177            body.insert("dryRun".to_owned(), Value::Bool(dry_run));
178        }
179        if let Some(policy) = options.queued_contact_policy {
180            body.insert(
181                "queuedContactPolicy".to_owned(),
182                queued_contact_policy_value(&policy),
183            );
184        }
185        let route = if options.recursive {
186            Route::DeleteWorkflowNodeRecursively
187        } else {
188            Route::DeleteWorkflowNode
189        };
190        let raw = self
191            .send(route, &[workflow_id, node_id], |r| r.json(&body))
192            .await?;
193        let parsed = if options.recursive {
194            raw.parse(ACTION, DeleteWorkflowNodeRecursivelyRequest::parse_response)
195                .await?
196        } else {
197            raw.parse(ACTION, DeleteWorkflowNodeRequestParams::parse_response)
198                .await?
199        };
200        match parsed {
201            DeleteWorkflowNodeResponseEnum::Ok(response) => Ok(response),
202            _ => Err(raw.unexpected(ACTION)),
203        }
204    }
205}