1use http::StatusCode;
2use serde_json::{Map, Value};
3
4use super::{
5 ContactFields, ContactId, LoopsClient, check, mailing_lists_value, merge_properties,
6 single_identifier,
7};
8use crate::error::{LoopsError, Result};
9use crate::generated::{
10 ContactProperty, ContactPropertyCreateRequest, ContactPropertyCreateRequestType,
11 ContactRequest, ContactSuccessResponse, ContactSuppressionRemoveResponse,
12 ContactSuppressionStatusResponse, ContactUpdateRequest, CreateContactRequest,
13 CreateContactResponse, FindContactRequestQuery, GetContactSuppressionRequest,
14 GetContactSuppressionRequestQuery, GetContactSuppressionResponse, ListContactPropertiesRequest,
15 ListContactPropertiesResponse, ListDedicatedSendingIpsRequest, ListDedicatedSendingIpsResponse,
16 ListMailingListsRequest, ListMailingListsResponse, MailingList,
17 RemoveContactSuppressionRequest, RemoveContactSuppressionRequestQuery,
18 RemoveContactSuppressionResponse, UpdateContactRequest, UpdateContactResponse,
19};
20use crate::responses::Contact;
21use crate::routes::Route;
22
23impl LoopsClient {
24 pub async fn create_contact(
30 &self,
31 email: &str,
32 user_id: Option<&str>,
33 fields: ContactFields,
34 ) -> Result<ContactSuccessResponse> {
35 const ACTION: &str = "create contact";
36 self.validate_email(Some(email))?;
37 let request = ContactRequest {
38 email: email.to_owned(),
39 first_name: fields.first_name,
40 last_name: fields.last_name,
41 source: fields.source,
42 subscribed: fields.subscribed,
43 user_group: fields.user_group,
44 user_id: user_id.map(str::to_owned),
45 mailing_lists: mailing_lists_value(&fields.mailing_lists),
46 additional_properties: indexmap::IndexMap::new(),
47 };
48 check(&request)?;
49 let body = with_properties(&request, fields.custom_properties, ACTION)?;
50 let raw = self
51 .send(Route::CreateContact, &[], |r| r.json(&body))
52 .await?;
53 if raw.status == StatusCode::CONFLICT {
54 return Err(LoopsError::ContactExists {
55 message: raw
56 .message()
57 .unwrap_or_else(|| "A contact with this email already exists".to_owned()),
58 });
59 }
60 match raw
61 .parse(ACTION, CreateContactRequest::parse_response)
62 .await?
63 {
64 CreateContactResponse::Ok(response) => Ok(response),
65 _ => Err(raw.unexpected(ACTION)),
66 }
67 }
68
69 pub async fn upsert_contact(
74 &self,
75 contact: ContactId,
76 fields: ContactFields,
77 ) -> Result<ContactSuccessResponse> {
78 const ACTION: &str = "upsert contact";
79 self.validate_email(contact.email_address())?;
80 let request = ContactUpdateRequest {
81 email: contact.email_address().map(str::to_owned),
82 first_name: fields.first_name,
83 last_name: fields.last_name,
84 source: fields.source,
85 subscribed: fields.subscribed,
86 user_group: fields.user_group,
87 user_id: contact.user_id_value().map(str::to_owned),
88 mailing_lists: mailing_lists_value(&fields.mailing_lists),
89 additional_properties: indexmap::IndexMap::new(),
90 };
91 let body = with_properties(&request, fields.custom_properties, ACTION)?;
92 let raw = self
93 .send(Route::UpsertContact, &[], |r| r.json(&body))
94 .await?;
95 match raw
96 .parse(ACTION, UpdateContactRequest::parse_response)
97 .await?
98 {
99 UpdateContactResponse::Ok(response) => Ok(response),
100 _ => Err(raw.unexpected(ACTION)),
101 }
102 }
103
104 pub async fn find_contact(&self, contact: ContactId) -> Result<Option<Vec<Contact>>> {
116 const ACTION: &str = "find contact";
117 single_identifier(&contact, ACTION)?;
118 self.validate_email(contact.email_address())?;
119 let query = FindContactRequestQuery {
120 email: contact.email_address().map(str::to_owned),
121 user_id: contact.user_id_value().map(str::to_owned),
122 };
123 let raw = self
124 .send(Route::FindContact, &[], |r| r.query(&query))
125 .await?;
126 if matches!(raw.status, StatusCode::BAD_REQUEST | StatusCode::NOT_FOUND) {
127 return Ok(None);
128 }
129 raw.parse_as(ACTION).map(Some)
132 }
133
134 pub async fn delete_contact(&self, contact: ContactId) -> Result<bool> {
144 const ACTION: &str = "delete contact";
145 let body = match &contact {
146 ContactId::Email(email) => serde_json::json!({ "email": email }),
147 ContactId::UserId(user_id) => serde_json::json!({ "userId": user_id }),
148 ContactId::Both { .. } => {
149 return Err(LoopsError::InvalidInput(
150 "Provide either email or user_id, not both".to_owned(),
151 ));
152 }
153 };
154 self.validate_email(contact.email_address())?;
155 let raw = self
156 .send(Route::DeleteContact, &[], |r| r.json(&body))
157 .await?;
158 if matches!(raw.status, StatusCode::BAD_REQUEST | StatusCode::NOT_FOUND) {
159 return Ok(false);
160 }
161 raw.parse(
162 ACTION,
163 crate::generated::DeleteContactRequest::parse_response,
164 )
165 .await
166 .map(|response| matches!(response, crate::generated::DeleteContactResponse::Ok(_)))
167 }
168
169 pub async fn create_contact_property(
174 &self,
175 name: &str,
176 property_type: ContactPropertyCreateRequestType,
177 ) -> Result<Value> {
178 const ACTION: &str = "create contact property";
179 let body = ContactPropertyCreateRequest {
180 name: name.to_owned(),
181 r#type: property_type,
182 };
183 check(&body)?;
184 let raw = self
185 .send(Route::CreateContactProperty, &[], |r| r.json(&body))
186 .await?;
187 raw.parse_json(ACTION)
188 }
189
190 pub async fn list_contact_properties(&self) -> Result<Vec<ContactProperty>> {
192 const ACTION: &str = "list contact properties";
193 let raw = self.send(Route::ListContactProperties, &[], |r| r).await?;
194 match raw
195 .parse(ACTION, ListContactPropertiesRequest::parse_response)
196 .await?
197 {
198 ListContactPropertiesResponse::Ok(properties) => Ok(properties),
199 _ => Err(raw.unexpected(ACTION)),
200 }
201 }
202
203 pub async fn list_mailing_lists(&self) -> Result<Vec<MailingList>> {
205 const ACTION: &str = "list mailing lists";
206 let raw = self.send(Route::ListMailingLists, &[], |r| r).await?;
207 match raw
208 .parse(ACTION, ListMailingListsRequest::parse_response)
209 .await?
210 {
211 ListMailingListsResponse::Ok(lists) => Ok(lists),
212 _ => Err(raw.unexpected(ACTION)),
213 }
214 }
215
216 pub async fn list_sending_ips(&self) -> Result<Vec<String>> {
218 const ACTION: &str = "list sending IPs";
219 let raw = self.send(Route::ListSendingIps, &[], |r| r).await?;
220 match raw
221 .parse(ACTION, ListDedicatedSendingIpsRequest::parse_response)
222 .await?
223 {
224 ListDedicatedSendingIpsResponse::Ok(ips) => Ok(ips),
225 _ => Err(raw.unexpected(ACTION)),
226 }
227 }
228
229 pub async fn get_contact_suppression(
235 &self,
236 contact: ContactId,
237 ) -> Result<ContactSuppressionStatusResponse> {
238 const ACTION: &str = "get suppression status";
239 single_identifier(&contact, ACTION)?;
240 let query = GetContactSuppressionRequestQuery {
241 email: contact.email_address().map(str::to_owned),
242 user_id: contact.user_id_value().map(str::to_owned),
243 };
244 let raw = self
245 .send(Route::GetContactSuppression, &[], |r| r.query(&query))
246 .await?;
247 match raw
248 .parse(ACTION, GetContactSuppressionRequest::parse_response)
249 .await?
250 {
251 GetContactSuppressionResponse::Ok(status) => Ok(status),
252 _ => Err(raw.unexpected(ACTION)),
253 }
254 }
255
256 pub async fn remove_contact_suppression(
262 &self,
263 contact: ContactId,
264 ) -> Result<ContactSuppressionRemoveResponse> {
265 const ACTION: &str = "remove suppression";
266 single_identifier(&contact, ACTION)?;
267 let query = RemoveContactSuppressionRequestQuery {
268 email: contact.email_address().map(str::to_owned),
269 user_id: contact.user_id_value().map(str::to_owned),
270 };
271 let raw = self
272 .send(Route::RemoveContactSuppression, &[], |r| r.query(&query))
273 .await?;
274 match raw
275 .parse(ACTION, RemoveContactSuppressionRequest::parse_response)
276 .await?
277 {
278 RemoveContactSuppressionResponse::Ok(response) => Ok(response),
279 _ => Err(raw.unexpected(ACTION)),
280 }
281 }
282}
283
284fn with_properties(
288 request: &impl serde::Serialize,
289 properties: Map<String, Value>,
290 action: &str,
291) -> Result<Value> {
292 let Value::Object(mut body) = serde_json::to_value(request)
293 .map_err(|err| LoopsError::InvalidInput(format!("Could not serialize contact: {err}")))?
294 else {
295 unreachable!("contact requests serialize to JSON objects");
296 };
297 merge_properties(&mut body, properties, CONTACT_FIELDS, action)?;
298 Ok(Value::Object(body))
299}
300
301const CONTACT_FIELDS: &[&str] = &[
303 "email",
304 "firstName",
305 "lastName",
306 "source",
307 "subscribed",
308 "userGroup",
309 "userId",
310 "mailingLists",
311];