Skip to main content

loops_so/client/
workflows.rs

1use serde_json::{Map, Value};
2
3use super::{LoopsClient, Page, check};
4use crate::error::{LoopsError, Result};
5use crate::generated::{
6    ChangeWorkflowMailingListRequestParams, ChangeWorkflowMailingListResponse,
7    ChangeWorkflowMailingListResponseEnum, CreateWorkflowRequest, CreateWorkflowRequestParams,
8    CreateWorkflowResponse, DeleteWorkflowRequestParams, DeleteWorkflowResponse,
9    GetWorkflowRequest, GetWorkflowResponse, ListWorkflowsRequest, ListWorkflowsRequestQuery,
10    ListWorkflowsResponse, ListWorkflowsResponseEnum, SimplifiedWorkflow,
11    UpdateWorkflowPropertiesRequestParams, UpdateWorkflowPropertiesResponse,
12    WorkflowQueuedContactPolicy,
13};
14use crate::routes::Route;
15
16impl LoopsClient {
17    /// List workflows.
18    pub async fn list_workflows(&self, page: Page) -> Result<ListWorkflowsResponse> {
19        const ACTION: &str = "list workflows";
20        let query = ListWorkflowsRequestQuery {
21            per_page: page.per_page_param(),
22            cursor: page.cursor,
23        };
24        let raw = self
25            .send(Route::ListWorkflows, &[], |r| r.query(&query))
26            .await?;
27        match raw
28            .parse(ACTION, ListWorkflowsRequest::parse_response)
29            .await?
30        {
31            ListWorkflowsResponseEnum::Ok(workflows) => Ok(workflows),
32            _ => Err(raw.unexpected(ACTION)),
33        }
34    }
35
36    /// Get a workflow with its node graph.
37    pub async fn get_workflow(&self, workflow_id: &str) -> Result<SimplifiedWorkflow> {
38        const ACTION: &str = "get workflow";
39        let raw = self.send(Route::GetWorkflow, &[workflow_id], |r| r).await?;
40        match raw
41            .parse(ACTION, GetWorkflowRequest::parse_response)
42            .await?
43        {
44            GetWorkflowResponse::Ok(workflow) => Ok(workflow),
45            _ => Err(raw.unexpected(ACTION)),
46        }
47    }
48
49    /// Create a draft workflow with a blank trigger and an exit node. Build
50    /// out its graph with the workflow node methods.
51    ///
52    /// Without `workflow_group_id`, Loops files the workflow in the team's
53    /// Unsorted group.
54    pub async fn create_workflow(
55        &self,
56        name: &str,
57        description: Option<&str>,
58        mailing_list_id: Option<&str>,
59        workflow_group_id: Option<&str>,
60    ) -> Result<SimplifiedWorkflow> {
61        const ACTION: &str = "create workflow";
62        let body = CreateWorkflowRequest {
63            name: name.to_owned(),
64            description: description.map(str::to_owned),
65            mailing_list_id: mailing_list_id.map(str::to_owned),
66            workflow_group_id: workflow_group_id.map(str::to_owned),
67        };
68        check(&body)?;
69        let raw = self
70            .send(Route::CreateWorkflow, &[], |r| r.json(&body))
71            .await?;
72        match raw
73            .parse(ACTION, CreateWorkflowRequestParams::parse_response)
74            .await?
75        {
76            CreateWorkflowResponse::Ok(workflow) => Ok(workflow),
77            _ => Err(raw.unexpected(ACTION)),
78        }
79    }
80
81    /// Rename a workflow, change its description, and/or move it to another
82    /// workflow group. At least one of the three must be `Some`, or the call
83    /// fails with [`LoopsError::InvalidInput`] before any request is sent.
84    ///
85    /// `expected_revision_id` is the optimistic concurrency token: pass the
86    /// latest `workflow_revision_id`, or `None` for a workflow that has none
87    /// yet. A stale value fails with 409.
88    pub async fn update_workflow(
89        &self,
90        workflow_id: &str,
91        expected_revision_id: Option<&str>,
92        name: Option<&str>,
93        description: Option<&str>,
94        workflow_group_id: Option<&str>,
95    ) -> Result<SimplifiedWorkflow> {
96        const ACTION: &str = "update workflow";
97        if name.is_none() && description.is_none() && workflow_group_id.is_none() {
98            return Err(LoopsError::InvalidInput(
99                "update_workflow requires name, description or workflow_group_id".to_owned(),
100            ));
101        }
102        let mut body = revision_body(expected_revision_id);
103        if let Some(name) = name {
104            body.insert("name".to_owned(), Value::from(name));
105        }
106        if let Some(description) = description {
107            body.insert("description".to_owned(), Value::from(description));
108        }
109        if let Some(workflow_group_id) = workflow_group_id {
110            body.insert("workflowGroupId".to_owned(), Value::from(workflow_group_id));
111        }
112        let raw = self
113            .send(Route::UpdateWorkflow, &[workflow_id], |r| r.json(&body))
114            .await?;
115        match raw
116            .parse(
117                ACTION,
118                UpdateWorkflowPropertiesRequestParams::parse_response,
119            )
120            .await?
121        {
122            UpdateWorkflowPropertiesResponse::Ok(workflow) => Ok(workflow),
123            _ => Err(raw.unexpected(ACTION)),
124        }
125    }
126
127    /// Set (`Some`) or clear (`None`) the mailing list of a workflow.
128    ///
129    /// With `dry_run`, or when contacts queued in the workflow would be
130    /// excluded by the new list, Loops answers with a preview instead of
131    /// applying the change; retry with
132    /// [`WorkflowQueuedContactPolicy::Discard`] to apply it and discard them.
133    pub async fn change_workflow_mailing_list(
134        &self,
135        workflow_id: &str,
136        expected_revision_id: Option<&str>,
137        mailing_list_id: Option<&str>,
138        dry_run: Option<bool>,
139        queued_contact_policy: Option<WorkflowQueuedContactPolicy>,
140    ) -> Result<ChangeWorkflowMailingListResponse> {
141        const ACTION: &str = "change workflow mailing list";
142        let mut body = revision_body(expected_revision_id);
143        body.insert(
144            "mailingListId".to_owned(),
145            mailing_list_id.map_or(Value::Null, Value::from),
146        );
147        if let Some(dry_run) = dry_run {
148            body.insert("dryRun".to_owned(), Value::Bool(dry_run));
149        }
150        if let Some(policy) = queued_contact_policy {
151            body.insert(
152                "queuedContactPolicy".to_owned(),
153                queued_contact_policy_value(&policy),
154            );
155        }
156        let raw = self
157            .send(Route::ChangeWorkflowMailingList, &[workflow_id], |r| {
158                r.json(&body)
159            })
160            .await?;
161        match raw
162            .parse(
163                ACTION,
164                ChangeWorkflowMailingListRequestParams::parse_response,
165            )
166            .await?
167        {
168            ChangeWorkflowMailingListResponseEnum::Ok(response) => Ok(response),
169            _ => Err(raw.unexpected(ACTION)),
170        }
171    }
172
173    /// Delete a workflow. Returns `true` once deleted.
174    ///
175    /// A workflow that is sending or still has queued contacts is not deleted
176    /// on the first attempt: Loops answers 409 saying what stands in the way.
177    /// Retry with `confirm_delete: Some(true)` to delete it, stop sending and
178    /// cancel the queued contacts.
179    pub async fn delete_workflow(
180        &self,
181        workflow_id: &str,
182        expected_revision_id: Option<&str>,
183        confirm_delete: Option<bool>,
184    ) -> Result<bool> {
185        const ACTION: &str = "delete workflow";
186        let mut body = revision_body(expected_revision_id);
187        if let Some(confirm) = confirm_delete {
188            body.insert("confirmDelete".to_owned(), Value::Bool(confirm));
189        }
190        let raw = self
191            .send(Route::DeleteWorkflow, &[workflow_id], |r| r.json(&body))
192            .await?;
193        match raw
194            .parse(ACTION, DeleteWorkflowRequestParams::parse_response)
195            .await?
196        {
197            DeleteWorkflowResponse::NoContent => Ok(true),
198            _ => Err(raw.unexpected(ACTION)),
199        }
200    }
201}
202
203/// A body carrying `expectedRevisionId`, which Loops requires on every
204/// workflow mutation and accepts as `null` for workflows without a revision
205/// yet. The generated models drop a `None` instead of sending `null`, so
206/// these bodies are built as JSON.
207pub(super) fn revision_body(expected_revision_id: Option<&str>) -> Map<String, Value> {
208    let mut body = Map::new();
209    body.insert(
210        "expectedRevisionId".to_owned(),
211        expected_revision_id.map_or(Value::Null, Value::from),
212    );
213    body
214}
215
216pub(super) fn queued_contact_policy_value(policy: &WorkflowQueuedContactPolicy) -> Value {
217    Value::from(match policy {
218        WorkflowQueuedContactPolicy::Fail => "fail",
219        WorkflowQueuedContactPolicy::Discard => "discard",
220    })
221}