1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use std::sync::Arc;
use serde::Serialize;
use serde_json::{json, Value};
use crate::client::Inner;
use crate::error::Result;
use crate::params;
/// The `automations` resource (multi-step contact journeys). Reached through
/// [`Mailtea::automations`](crate::Mailtea::automations).
///
/// Automations are scoped to a publication — pass `publication_id`. An
/// automation is a graph: `steps` (each `{"key", "type", "label", "config"}`)
/// plus optional `connections` (each `{"from", "to", "branch"}`).
///
/// `connections` is optional: omit it and the server links the steps in array
/// order with `branch: "next"`, rooted at the trigger. A graph containing a
/// `condition` or `wait_for_event` step cannot be inferred that way and is
/// rejected with `connections_required_for_branching` — send its connections
/// explicitly.
///
/// Failures come back as coded `issues[]` rather than schema errors, and for a
/// draft/paused/archived automation they ride along informationally instead of
/// blocking the save.
#[derive(Clone, Debug)]
pub struct Automations {
inner: Arc<Inner>,
}
impl Automations {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
/// `POST /v1/automations/validate` — dry-run a graph without creating
/// anything. Takes `publication_id` and `steps`, plus optional
/// `connections`.
pub async fn validate(&self, params: impl Serialize) -> Result<Value> {
self.inner
.call(
"POST",
"/v1/automations/validate",
crate::params::to_body(params)?,
)
.await
}
/// `POST /v1/automations` — create an automation.
///
/// Takes `publication_id`, `name` and `steps`, plus optional `description`,
/// `connections`, `reentry_policy`
/// (`once`/`once_per_window`/`always` — `once_per_window` requires
/// `reentry_window_seconds`), `on_step_failure` and `validate_only`. With
/// `validate_only: true` nothing is written and an `automation_validation`
/// is returned instead. New automations start as `draft` —
/// [`activate`](Self::activate) starts them.
pub async fn create(&self, params: impl Serialize) -> Result<Value> {
self.inner
.call("POST", "/v1/automations", crate::params::to_body(params)?)
.await
}
/// `GET /v1/automations` — list automations, cursor-paginated. Filters:
/// `publication_id` (required), `status`, `limit`, `after`. List items omit
/// `steps`, `connections`, `valid` and `issues` — use [`get`](Self::get) for
/// the full graph.
pub async fn list(&self, params: impl Serialize) -> Result<Value> {
self.inner
.call(
"GET",
&format!("/v1/automations{}", params::query(params)?),
None,
)
.await
}
/// `GET /v1/automations/:id` — one automation with its live graph and
/// current `issues[]`. Requires `publication_id`.
pub async fn get(&self, id: &str, params: impl Serialize) -> Result<Value> {
self.inner
.call(
"GET",
&format!(
"/v1/automations/{}{}",
crate::params::encode(id),
crate::params::query(params)?
),
None,
)
.await
}
/// `PATCH /v1/automations/:id` — replace the graph or its settings.
///
/// `publication_id` is required and is sent as a query parameter — it is
/// removed from the body, which the endpoint's schema does not accept it in.
/// The graph is replaced wholesale and cuts a new version.
///
/// `validate_only: true` returns an `automation_validation` and writes
/// nothing. A graph change that carries errors saves anyway while the
/// automation is draft/paused/archived. On an `active` one it is a 422
/// `active_graph_invalid` only when it adds an error the live version does
/// not already have; `issues` then lists just those new problems, and
/// older ones come back with `pre_existing: true`. Changing an `active`
/// automation's trigger is a 422 `trigger_locked_while_active`. Either
/// way: pause, save, then start again.
pub async fn update(&self, id: &str, params: impl Serialize) -> Result<Value> {
let mut payload = crate::params::to_value(params)?;
let publication_id = crate::params::take(&mut payload, "publication_id");
self.inner
.call(
"PATCH",
&format!(
"/v1/automations/{}{}",
crate::params::encode(id),
crate::params::query_of_value(&json!({ "publication_id": publication_id }))
),
crate::params::body_from_value(&payload)?,
)
.await
}
/// `DELETE /v1/automations/:id` — delete an automation. Requires
/// `publication_id`.
///
/// Deleting an `active` automation is a 409 `automation_active` — pause or
/// archive it first so its in-flight runs are not dropped silently.
pub async fn delete(&self, id: &str, params: impl Serialize) -> Result<Value> {
self.inner
.call(
"DELETE",
&format!(
"/v1/automations/{}{}",
crate::params::encode(id),
crate::params::query(params)?
),
None,
)
.await
}
/// `POST /v1/automations/:id/activate` — start the automation so new
/// contacts enroll. Requires `publication_id`. A graph with errors is
/// refused with 422 `automation_invalid` and the blocking `issues[]`,
/// except an `unknown_step_ref` at a `config.*` path or a trigger
/// `missing_branch` that the version it last ran on already had
/// (`pre_existing: true`).
pub async fn activate(&self, id: &str, params: impl Serialize) -> Result<Value> {
self.inner
.call(
"POST",
&format!(
"/v1/automations/{}/activate{}",
crate::params::encode(id),
crate::params::query(params)?
),
None,
)
.await
}
/// `POST /v1/automations/:id/pause` — stop new enrollments. Requires
/// `publication_id` (query). Optional `cancel_runs` — it **defaults to
/// false** here, so in-flight runs keep going; pass `cancel_runs: true` to
/// exit them.
pub async fn pause(&self, id: &str, params: impl Serialize) -> Result<Value> {
self.lifecycle(id, "pause", params).await
}
/// `POST /v1/automations/:id/archive` — archive the automation. Requires
/// `publication_id` (query). Optional `cancel_runs` — it **defaults to
/// true** here (the opposite of [`pause`](Self::pause)), so in-flight runs
/// exit with `automation_archived`.
pub async fn archive(&self, id: &str, params: impl Serialize) -> Result<Value> {
self.lifecycle(id, "archive", params).await
}
/// `GET /v1/automations/:id/versions` — list versions, cursor-paginated.
/// Filters: `publication_id` (required), `limit`, `after`. List items carry
/// no `steps`/`connections` — use [`version`](Self::version) for a stored
/// graph.
pub async fn versions(&self, id: &str, params: impl Serialize) -> Result<Value> {
self.inner
.call(
"GET",
&format!(
"/v1/automations/{}/versions{}",
crate::params::encode(id),
crate::params::query(params)?
),
None,
)
.await
}
/// `GET /v1/automations/:id/versions/:version` — one stored version,
/// including its `steps` and `connections`. Requires `publication_id`.
///
/// This is the graph a run of that version is pinned to — editing the
/// automation never rewrites it.
pub async fn version(
&self,
id: &str,
version: impl std::fmt::Display,
params: impl Serialize,
) -> Result<Value> {
self.inner
.call(
"GET",
&format!(
"/v1/automations/{}/versions/{}{}",
crate::params::encode(id),
crate::params::encode(&version.to_string()),
crate::params::query(params)?
),
None,
)
.await
}
/// `GET /v1/automations/:id/metrics` — per-step funnel counts. Filters:
/// `publication_id` (required), `version` (omit to aggregate across ALL
/// versions), `since`, `until`.
///
/// Test runs are always excluded (`excludes_test_runs: true`). Condition
/// steps report `branches: {condition_met, condition_not_met}`,
/// `wait_for_event` steps `{event_received, timeout}`.
pub async fn metrics(&self, id: &str, params: impl Serialize) -> Result<Value> {
self.inner
.call(
"GET",
&format!(
"/v1/automations/{}/metrics{}",
crate::params::encode(id),
crate::params::query(params)?
),
None,
)
.await
}
/// `POST /v1/automations/:id/test` — run the automation once against a real
/// contact.
///
/// `publication_id` is required and is sent as a query parameter; the body
/// takes one of `contact_id` or `email`, plus optional `event_properties` to
/// seed the run's `event.*` namespace.
///
/// A test run **sends real, billed email** to that inbox — it does not
/// bypass any send gate. It is flagged `is_test` and excluded from
/// [`metrics`](Self::metrics). Returns 202 with the queued run.
pub async fn test(&self, id: &str, params: impl Serialize) -> Result<Value> {
let mut payload = crate::params::to_value(params)?;
let publication_id = crate::params::take(&mut payload, "publication_id");
self.inner
.call(
"POST",
&format!(
"/v1/automations/{}/test{}",
crate::params::encode(id),
crate::params::query_of_value(&json!({ "publication_id": publication_id }))
),
crate::params::body_from_value(&payload)?,
)
.await
}
/// `publication_id` goes in the query but `cancel_runs` is read from the
/// body, so the two are split here. No body is sent when the caller omitted
/// `cancel_runs` — or passed it as `null`, which the server's schema would
/// reject — so the per-verb default applies in both cases.
async fn lifecycle(&self, id: &str, verb: &str, params: impl Serialize) -> Result<Value> {
let payload = crate::params::to_value(params)?;
let cancel_runs = payload.get("cancel_runs").cloned().unwrap_or(Value::Null);
let body = if cancel_runs.is_null() {
None
} else {
crate::params::body_from_value(&json!({ "cancel_runs": cancel_runs }))?
};
self.inner
.call(
"POST",
&format!(
"/v1/automations/{}/{verb}{}",
crate::params::encode(id),
crate::params::query_pick(&payload, &["publication_id"])
),
body,
)
.await
}
}