Skip to main content

loops_so/client/
params.rs

1use std::collections::BTreeMap;
2
3use serde_json::{Map, Value};
4
5use crate::generated::{CreateWorkflowNodeTypeName, WorkflowQueuedContactPolicy};
6
7/// How a contact is identified: by email, by user ID, or both.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum ContactId {
10    /// The contact's email address.
11    Email(String),
12    /// The contact's user ID.
13    UserId(String),
14    /// Both. On upsert, Loops matches either value and updates the other.
15    Both {
16        /// The contact's email address.
17        email: String,
18        /// The contact's user ID.
19        user_id: String,
20    },
21}
22
23impl ContactId {
24    /// Identify the contact by email.
25    pub fn email(email: impl Into<String>) -> Self {
26        Self::Email(email.into())
27    }
28
29    /// Identify the contact by user ID.
30    pub fn user_id(user_id: impl Into<String>) -> Self {
31        Self::UserId(user_id.into())
32    }
33
34    /// Identify the contact by email and user ID.
35    pub fn both(email: impl Into<String>, user_id: impl Into<String>) -> Self {
36        Self::Both {
37            email: email.into(),
38            user_id: user_id.into(),
39        }
40    }
41
42    /// The email address, when one was given.
43    pub fn email_address(&self) -> Option<&str> {
44        match self {
45            Self::Email(email) | Self::Both { email, .. } => Some(email),
46            Self::UserId(_) => None,
47        }
48    }
49
50    /// The user ID, when one was given.
51    pub fn user_id_value(&self) -> Option<&str> {
52        match self {
53            Self::UserId(user_id) | Self::Both { user_id, .. } => Some(user_id),
54            Self::Email(_) => None,
55        }
56    }
57}
58
59/// Contact fields for `create_contact` and `upsert_contact`. Unset fields are
60/// left out of the request.
61#[derive(Debug, Clone, Default, PartialEq)]
62#[non_exhaustive]
63#[must_use]
64pub struct ContactFields {
65    /// First name.
66    pub first_name: Option<String>,
67    /// Last name.
68    pub last_name: Option<String>,
69    /// Custom source value replacing the default `"API"`.
70    pub source: Option<String>,
71    /// Subscription status. On upsert, `Some(true)` re-subscribes a contact
72    /// that unsubscribed; leave it unset unless that is the intent.
73    pub subscribed: Option<bool>,
74    /// User group.
75    pub user_group: Option<String>,
76    /// Mailing list IDs mapped to whether the contact should be on that list.
77    pub mailing_lists: BTreeMap<String, bool>,
78    /// Custom contact properties, sent as top-level keys.
79    pub custom_properties: Map<String, Value>,
80}
81
82impl ContactFields {
83    /// No fields set.
84    pub fn new() -> Self {
85        Self::default()
86    }
87
88    /// Set the first name.
89    pub fn first_name(mut self, value: impl Into<String>) -> Self {
90        self.first_name = Some(value.into());
91        self
92    }
93
94    /// Set the last name.
95    pub fn last_name(mut self, value: impl Into<String>) -> Self {
96        self.last_name = Some(value.into());
97        self
98    }
99
100    /// Set the source.
101    pub fn source(mut self, value: impl Into<String>) -> Self {
102        self.source = Some(value.into());
103        self
104    }
105
106    /// Set the subscription status.
107    pub fn subscribed(mut self, value: bool) -> Self {
108        self.subscribed = Some(value);
109        self
110    }
111
112    /// Set the user group.
113    pub fn user_group(mut self, value: impl Into<String>) -> Self {
114        self.user_group = Some(value.into());
115        self
116    }
117
118    /// Add the contact to (`true`) or remove it from (`false`) a mailing list.
119    pub fn mailing_list(mut self, list_id: impl Into<String>, subscribed: bool) -> Self {
120        self.mailing_lists.insert(list_id.into(), subscribed);
121        self
122    }
123
124    /// Set a custom contact property (string, number, boolean or date).
125    pub fn property(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
126        self.custom_properties.insert(key.into(), value.into());
127        self
128    }
129}
130
131/// Pagination for the list endpoints.
132#[derive(Debug, Clone, Default, PartialEq, Eq)]
133#[non_exhaustive]
134#[must_use]
135pub struct Page {
136    /// Results per page, 10 to 50. Loops defaults to 20.
137    pub per_page: Option<u32>,
138    /// The `pagination.nextCursor` of the previous page.
139    pub cursor: Option<String>,
140}
141
142impl Page {
143    /// The first page at the default size.
144    pub fn first() -> Self {
145        Self::default()
146    }
147
148    /// Set the page size.
149    pub fn per_page(mut self, per_page: u32) -> Self {
150        self.per_page = Some(per_page);
151        self
152    }
153
154    /// Continue from a cursor.
155    pub fn cursor(mut self, cursor: impl Into<String>) -> Self {
156        self.cursor = Some(cursor.into());
157        self
158    }
159
160    pub(crate) fn per_page_param(&self) -> Option<String> {
161        self.per_page.map(|per_page| per_page.to_string())
162    }
163}
164
165/// Optional parts of `send_event`.
166#[derive(Debug, Clone, Default, PartialEq)]
167#[non_exhaustive]
168#[must_use]
169pub struct EventOptions {
170    /// Event properties, available in emails the event sends.
171    pub event_properties: Map<String, Value>,
172    /// Mailing list IDs mapped to whether the contact should be on that list.
173    pub mailing_lists: BTreeMap<String, bool>,
174    /// Contact properties to update, sent as top-level keys.
175    pub contact_properties: Map<String, Value>,
176    /// Idempotency key, up to 100 characters. A UUID v4 is generated when unset.
177    pub idempotency_key: Option<String>,
178}
179
180impl EventOptions {
181    /// No options set.
182    pub fn new() -> Self {
183        Self::default()
184    }
185
186    /// Set an event property.
187    pub fn event_property(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
188        self.event_properties.insert(key.into(), value.into());
189        self
190    }
191
192    /// Add the contact to (`true`) or remove it from (`false`) a mailing list.
193    pub fn mailing_list(mut self, list_id: impl Into<String>, subscribed: bool) -> Self {
194        self.mailing_lists.insert(list_id.into(), subscribed);
195        self
196    }
197
198    /// Update a contact property.
199    pub fn contact_property(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
200        self.contact_properties.insert(key.into(), value.into());
201        self
202    }
203
204    /// Set the idempotency key.
205    pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
206        self.idempotency_key = Some(key.into());
207        self
208    }
209}
210
211/// Optional parts of `send_transactional_email`.
212#[derive(Debug, Clone, Default, PartialEq)]
213#[non_exhaustive]
214#[must_use]
215pub struct TransactionalOptions {
216    /// Values for the template's data variables (strings, numbers, or arrays
217    /// for array blocks).
218    pub data_variables: Map<String, Value>,
219    /// File attachments. Loops support must enable attachments first.
220    pub attachments: Vec<crate::generated::TransactionalRequestAttachment>,
221    /// Create the contact in your audience if it does not exist yet.
222    pub add_to_audience: Option<bool>,
223    /// Idempotency key, up to 100 characters. A UUID v4 is generated when unset.
224    pub idempotency_key: Option<String>,
225}
226
227impl TransactionalOptions {
228    /// No options set.
229    pub fn new() -> Self {
230        Self::default()
231    }
232
233    /// Set a data variable.
234    pub fn data_variable(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
235        self.data_variables.insert(key.into(), value.into());
236        self
237    }
238
239    /// Attach a file. `data` is the base64-encoded file content.
240    pub fn attachment(
241        mut self,
242        filename: impl Into<String>,
243        content_type: impl Into<String>,
244        data: impl Into<String>,
245    ) -> Self {
246        self.attachments
247            .push(crate::generated::TransactionalRequestAttachment {
248                filename: filename.into(),
249                content_type: content_type.into(),
250                data: data.into(),
251            });
252        self
253    }
254
255    /// Set whether to create the contact.
256    pub fn add_to_audience(mut self, add: bool) -> Self {
257        self.add_to_audience = Some(add);
258        self
259    }
260
261    /// Set the idempotency key.
262    pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
263        self.idempotency_key = Some(key.into());
264        self
265    }
266}
267
268/// How an email message renders.
269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
270pub enum EmailFormat {
271    /// Plain text.
272    Plain,
273    /// Styled HTML.
274    Styled,
275}
276
277/// Changes for `update_email_message`. Unset fields are left unchanged.
278///
279/// The three fallback maps merge per key on the server: `Some(value)` sets a
280/// fallback, `None` deletes it, and keys left out are unchanged.
281#[derive(Debug, Clone, Default, PartialEq, Eq)]
282#[non_exhaustive]
283#[must_use]
284pub struct EmailMessageUpdate {
285    /// Subject line.
286    pub subject: Option<String>,
287    /// Preview text shown in the inbox.
288    pub preview_text: Option<String>,
289    /// Sender display name.
290    pub from_name: Option<String>,
291    /// Sender username, without `@` or domain; the team domain is appended.
292    pub from_email: Option<String>,
293    /// Reply-to address (empty or a valid email).
294    pub reply_to_email: Option<String>,
295    /// Body as LMX, with styles in a `<Style />` tag.
296    pub lmx: Option<String>,
297    /// Optimistic concurrency token; a stale value fails with 409.
298    pub expected_revision_id: Option<String>,
299    /// CC address. Needs CC/BCC enabled for the team; not for campaign
300    /// emails. Checked against safe mode.
301    pub cc_email: Option<String>,
302    /// BCC address. Same requirements as `cc_email`.
303    pub bcc_email: Option<String>,
304    /// ISO 639-1 language code, e.g. `"en"`.
305    pub language_code: Option<String>,
306    /// Rendering format.
307    pub email_format: Option<EmailFormat>,
308    /// Fallbacks keyed by contact property name.
309    pub contact_properties_fallbacks: Option<BTreeMap<String, Option<String>>>,
310    /// Fallbacks keyed by event property name.
311    pub event_properties_fallbacks: Option<BTreeMap<String, Option<String>>>,
312    /// Fallbacks keyed by data variable name.
313    pub data_variables_fallbacks: Option<BTreeMap<String, Option<String>>>,
314}
315
316impl EmailMessageUpdate {
317    /// No changes.
318    pub fn new() -> Self {
319        Self::default()
320    }
321
322    /// Set the subject.
323    pub fn subject(mut self, value: impl Into<String>) -> Self {
324        self.subject = Some(value.into());
325        self
326    }
327
328    /// Set the preview text.
329    pub fn preview_text(mut self, value: impl Into<String>) -> Self {
330        self.preview_text = Some(value.into());
331        self
332    }
333
334    /// Set the sender display name.
335    pub fn from_name(mut self, value: impl Into<String>) -> Self {
336        self.from_name = Some(value.into());
337        self
338    }
339
340    /// Set the sender username.
341    pub fn from_email(mut self, value: impl Into<String>) -> Self {
342        self.from_email = Some(value.into());
343        self
344    }
345
346    /// Set the reply-to address.
347    pub fn reply_to_email(mut self, value: impl Into<String>) -> Self {
348        self.reply_to_email = Some(value.into());
349        self
350    }
351
352    /// Set the LMX body.
353    pub fn lmx(mut self, value: impl Into<String>) -> Self {
354        self.lmx = Some(value.into());
355        self
356    }
357
358    /// Set the expected revision.
359    pub fn expected_revision_id(mut self, value: impl Into<String>) -> Self {
360        self.expected_revision_id = Some(value.into());
361        self
362    }
363
364    /// Set the CC address.
365    pub fn cc_email(mut self, value: impl Into<String>) -> Self {
366        self.cc_email = Some(value.into());
367        self
368    }
369
370    /// Set the BCC address.
371    pub fn bcc_email(mut self, value: impl Into<String>) -> Self {
372        self.bcc_email = Some(value.into());
373        self
374    }
375
376    /// Set the language code.
377    pub fn language_code(mut self, value: impl Into<String>) -> Self {
378        self.language_code = Some(value.into());
379        self
380    }
381
382    /// Set the rendering format.
383    pub fn email_format(mut self, value: EmailFormat) -> Self {
384        self.email_format = Some(value);
385        self
386    }
387
388    /// Set (`Some`) or delete (`None`) a contact property fallback.
389    pub fn contact_property_fallback(
390        mut self,
391        key: impl Into<String>,
392        value: Option<&str>,
393    ) -> Self {
394        self.contact_properties_fallbacks
395            .get_or_insert_with(BTreeMap::new)
396            .insert(key.into(), value.map(str::to_owned));
397        self
398    }
399
400    /// Set (`Some`) or delete (`None`) an event property fallback.
401    pub fn event_property_fallback(mut self, key: impl Into<String>, value: Option<&str>) -> Self {
402        self.event_properties_fallbacks
403            .get_or_insert_with(BTreeMap::new)
404            .insert(key.into(), value.map(str::to_owned));
405        self
406    }
407
408    /// Set (`Some`) or delete (`None`) a data variable fallback.
409    pub fn data_variable_fallback(mut self, key: impl Into<String>, value: Option<&str>) -> Self {
410        self.data_variables_fallbacks
411            .get_or_insert_with(BTreeMap::new)
412            .insert(key.into(), value.map(str::to_owned));
413        self
414    }
415}
416
417/// Values used to render `preview_email_message`.
418#[derive(Debug, Clone, Default, PartialEq)]
419#[non_exhaustive]
420#[must_use]
421pub struct PreviewOptions {
422    /// Contact property values.
423    pub contact_properties: Map<String, Value>,
424    /// Event property values.
425    pub event_properties: Map<String, Value>,
426    /// Data variable values.
427    pub data_variables: Map<String, Value>,
428}
429
430impl PreviewOptions {
431    /// No values.
432    pub fn new() -> Self {
433        Self::default()
434    }
435
436    /// Set a contact property value.
437    pub fn contact_property(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
438        self.contact_properties.insert(key.into(), value.into());
439        self
440    }
441
442    /// Set an event property value.
443    pub fn event_property(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
444        self.event_properties.insert(key.into(), value.into());
445        self
446    }
447
448    /// Set a data variable value.
449    pub fn data_variable(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
450        self.data_variables.insert(key.into(), value.into());
451        self
452    }
453}
454
455/// Where `create_workflow_node` inserts the new node.
456#[derive(Debug, Clone, PartialEq, Eq)]
457pub enum NodePlacement {
458    /// Into the edge from `from_node_id` to `to_node_id`.
459    Between {
460        /// Source of the edge.
461        from_node_id: String,
462        /// Target of the edge.
463        to_node_id: String,
464    },
465    /// Ahead of `to_node_id`, which needs at least one incoming parent and
466    /// cannot be a trigger.
467    Before {
468        /// The node to insert ahead of.
469        to_node_id: String,
470    },
471    /// Behind `from_node_id`, which must have exactly one outgoing node. Use
472    /// [`Between`](Self::Between) when it has several.
473    After {
474        /// The node to insert behind.
475        from_node_id: String,
476    },
477}
478
479impl NodePlacement {
480    /// Insert into the edge between two nodes.
481    pub fn between(from_node_id: impl Into<String>, to_node_id: impl Into<String>) -> Self {
482        Self::Between {
483            from_node_id: from_node_id.into(),
484            to_node_id: to_node_id.into(),
485        }
486    }
487
488    /// Insert ahead of a node.
489    pub fn before(to_node_id: impl Into<String>) -> Self {
490        Self::Before {
491            to_node_id: to_node_id.into(),
492        }
493    }
494
495    /// Insert behind a node.
496    pub fn after(from_node_id: impl Into<String>) -> Self {
497        Self::After {
498            from_node_id: from_node_id.into(),
499        }
500    }
501}
502
503/// Optional parts of `delete_workflow_node`.
504#[derive(Debug, Clone, Default, PartialEq, Eq)]
505#[non_exhaustive]
506#[must_use]
507pub struct DeleteNodeOptions {
508    /// Report what would be deleted without deleting it.
509    pub dry_run: Option<bool>,
510    /// What to do with contacts queued at the node. Loops defaults to `Fail`.
511    pub queued_contact_policy: Option<WorkflowQueuedContactPolicy>,
512    /// Also delete everything downstream of the node, instead of re-linking
513    /// its edge.
514    pub recursive: bool,
515}
516
517impl DeleteNodeOptions {
518    /// Delete the single node.
519    pub fn new() -> Self {
520        Self::default()
521    }
522
523    /// Set dry-run mode.
524    pub fn dry_run(mut self, dry_run: bool) -> Self {
525        self.dry_run = Some(dry_run);
526        self
527    }
528
529    /// Set the queued-contact policy.
530    pub fn queued_contact_policy(mut self, policy: WorkflowQueuedContactPolicy) -> Self {
531        self.queued_contact_policy = Some(policy);
532        self
533    }
534
535    /// Delete the node's whole downstream subtree.
536    pub fn recursive(mut self, recursive: bool) -> Self {
537        self.recursive = recursive;
538        self
539    }
540}
541
542pub(crate) fn node_type_name(node_type: &CreateWorkflowNodeTypeName) -> Value {
543    serde_json::to_value(node_type).unwrap_or(Value::Null)
544}