front_api/
contacts.rs

1use anyhow::Result;
2
3use crate::Client;
4#[derive(Clone, Debug)]
5pub struct Contacts {
6    pub client: Client,
7}
8
9impl Contacts {
10    #[doc(hidden)]
11    pub fn new(client: Client) -> Self {
12        Self { client }
13    }
14
15    #[doc = "List contacts\n\nList the contacts of the company.\n\n**Parameters:**\n\n- `limit: Option<i64>`: Max number of results per page\n- `page_token: Option<String>`: Token to use to request the next page\n- `q: Option<String>`: Search query object with the optional properties `updated_after` and `updated_before`, whose value should be a timestamp in seconds with up to 3 decimal places.\n- `sort_by: Option<String>`: Field used to sort the records\n- `sort_order: Option<crate::types::SortOrder>`: Order by which results should be sorted\n\n```rust,no_run\nasync fn example_contacts_list() -> anyhow::Result<()> {\n    let client = front_api::Client::new_from_env();\n    let result: front_api::types::ListContactsResponse = client\n        .contacts()\n        .list(\n            Some(4 as i64),\n            Some(\"some-string\".to_string()),\n            Some(\"some-string\".to_string()),\n            Some(\"some-string\".to_string()),\n            Some(front_api::types::SortOrder::Asc),\n        )\n        .await?;\n    println!(\"{:?}\", result);\n    Ok(())\n}\n```"]
16    #[tracing::instrument]
17    pub async fn list<'a>(
18        &'a self,
19        limit: Option<i64>,
20        page_token: Option<String>,
21        q: Option<String>,
22        sort_by: Option<String>,
23        sort_order: Option<crate::types::SortOrder>,
24    ) -> Result<crate::types::ListContactsResponse, crate::types::error::Error> {
25        let mut req = self.client.client.request(
26            http::Method::GET,
27            &format!("{}/{}", self.client.base_url, "contacts"),
28        );
29        req = req.bearer_auth(&self.client.token);
30        let mut query_params = Vec::new();
31        if let Some(p) = limit {
32            query_params.push(("limit", format!("{}", p)));
33        }
34
35        if let Some(p) = page_token {
36            query_params.push(("page_token", p));
37        }
38
39        if let Some(p) = q {
40            query_params.push(("q", p));
41        }
42
43        if let Some(p) = sort_by {
44            query_params.push(("sort_by", p));
45        }
46
47        if let Some(p) = sort_order {
48            query_params.push(("sort_order", format!("{}", p)));
49        }
50
51        req = req.query(&query_params);
52        let resp = req.send().await?;
53        let status = resp.status();
54        if status.is_success() {
55            let text = resp.text().await.unwrap_or_default();
56            serde_json::from_str(&text).map_err(|err| {
57                crate::types::error::Error::from_serde_error(
58                    format_serde_error::SerdeError::new(text.to_string(), err),
59                    status,
60                )
61            })
62        } else {
63            Err(crate::types::error::Error::UnexpectedResponse(resp))
64        }
65    }
66
67    #[doc = "Create contact\n\nCreate a new contact.\n\n```rust,no_run\nasync fn example_contacts_create() -> anyhow::Result<()> {\n    let client = front_api::Client::new_from_env();\n    let result: front_api::types::ContactResponse = client\n        .contacts()\n        .create(&front_api::types::CreateContact {\n            name: Some(\"some-string\".to_string()),\n            description: Some(\"some-string\".to_string()),\n            avatar: Some(bytes::Bytes::from(\"some-string\")),\n            is_spammer: Some(true),\n            links: Some(vec![\"some-string\".to_string()]),\n            group_names: Some(vec![\"some-string\".to_string()]),\n            custom_fields: Some(std::collections::HashMap::from([(\n                \"some-key\".to_string(),\n                \"some-string\".to_string(),\n            )])),\n            handles: Some(vec![front_api::types::ContactHandle {\n                handle: \"some-string\".to_string(),\n                source: front_api::types::Source::Intercom,\n            }]),\n        })\n        .await?;\n    println!(\"{:?}\", result);\n    Ok(())\n}\n```"]
68    #[tracing::instrument]
69    pub async fn create<'a>(
70        &'a self,
71        body: &crate::types::CreateContact,
72    ) -> Result<crate::types::ContactResponse, crate::types::error::Error> {
73        let mut req = self.client.client.request(
74            http::Method::POST,
75            &format!("{}/{}", self.client.base_url, "contacts"),
76        );
77        req = req.bearer_auth(&self.client.token);
78        req = req.json(body);
79        let resp = req.send().await?;
80        let status = resp.status();
81        if status.is_success() {
82            let text = resp.text().await.unwrap_or_default();
83            serde_json::from_str(&text).map_err(|err| {
84                crate::types::error::Error::from_serde_error(
85                    format_serde_error::SerdeError::new(text.to_string(), err),
86                    status,
87                )
88            })
89        } else {
90            Err(crate::types::error::Error::UnexpectedResponse(resp))
91        }
92    }
93
94    #[doc = "List team contacts\n\nList the contacts of a team.\n\n**Parameters:**\n\n- `limit: Option<i64>`: Max number of results per page\n- `page_token: Option<String>`: Token to use to request the next page\n- `q: Option<String>`: Search query object with the optional properties `updated_after` and `updated_before`, whose value should be a timestamp in seconds with up to 3 decimal places.\n- `sort_by: Option<String>`: Field used to sort the records\n- `sort_order: Option<crate::types::SortOrder>`: Order by which results should be sorted\n- `team_id: &'astr`: The team ID (required)\n\n```rust,no_run\nasync fn example_contacts_list_team() -> anyhow::Result<()> {\n    let client = front_api::Client::new_from_env();\n    let result: front_api::types::ListTeamContactsResponse = client\n        .contacts()\n        .list_team(\n            Some(4 as i64),\n            Some(\"some-string\".to_string()),\n            Some(\"some-string\".to_string()),\n            Some(\"some-string\".to_string()),\n            Some(front_api::types::SortOrder::Asc),\n            \"some-string\",\n        )\n        .await?;\n    println!(\"{:?}\", result);\n    Ok(())\n}\n```"]
95    #[tracing::instrument]
96    pub async fn list_team<'a>(
97        &'a self,
98        limit: Option<i64>,
99        page_token: Option<String>,
100        q: Option<String>,
101        sort_by: Option<String>,
102        sort_order: Option<crate::types::SortOrder>,
103        team_id: &'a str,
104    ) -> Result<crate::types::ListTeamContactsResponse, crate::types::error::Error> {
105        let mut req = self.client.client.request(
106            http::Method::GET,
107            &format!(
108                "{}/{}",
109                self.client.base_url,
110                "teams/{team_id}/contacts".replace("{team_id}", team_id)
111            ),
112        );
113        req = req.bearer_auth(&self.client.token);
114        let mut query_params = Vec::new();
115        if let Some(p) = limit {
116            query_params.push(("limit", format!("{}", p)));
117        }
118
119        if let Some(p) = page_token {
120            query_params.push(("page_token", p));
121        }
122
123        if let Some(p) = q {
124            query_params.push(("q", p));
125        }
126
127        if let Some(p) = sort_by {
128            query_params.push(("sort_by", p));
129        }
130
131        if let Some(p) = sort_order {
132            query_params.push(("sort_order", format!("{}", p)));
133        }
134
135        req = req.query(&query_params);
136        let resp = req.send().await?;
137        let status = resp.status();
138        if status.is_success() {
139            let text = resp.text().await.unwrap_or_default();
140            serde_json::from_str(&text).map_err(|err| {
141                crate::types::error::Error::from_serde_error(
142                    format_serde_error::SerdeError::new(text.to_string(), err),
143                    status,
144                )
145            })
146        } else {
147            Err(crate::types::error::Error::UnexpectedResponse(resp))
148        }
149    }
150
151    #[doc = "Create team contact\n\nCreate a contact for a team.\n\n**Parameters:**\n\n- `team_id: &'astr`: The team ID (required)\n\n```rust,no_run\nasync fn example_contacts_create_team() -> anyhow::Result<()> {\n    let client = front_api::Client::new_from_env();\n    let result: front_api::types::ContactResponse = client\n        .contacts()\n        .create_team(\n            \"some-string\",\n            &front_api::types::CreateContact {\n                name: Some(\"some-string\".to_string()),\n                description: Some(\"some-string\".to_string()),\n                avatar: Some(bytes::Bytes::from(\"some-string\")),\n                is_spammer: Some(false),\n                links: Some(vec![\"some-string\".to_string()]),\n                group_names: Some(vec![\"some-string\".to_string()]),\n                custom_fields: Some(std::collections::HashMap::from([(\n                    \"some-key\".to_string(),\n                    \"some-string\".to_string(),\n                )])),\n                handles: Some(vec![front_api::types::ContactHandle {\n                    handle: \"some-string\".to_string(),\n                    source: front_api::types::Source::Custom,\n                }]),\n            },\n        )\n        .await?;\n    println!(\"{:?}\", result);\n    Ok(())\n}\n```"]
152    #[tracing::instrument]
153    pub async fn create_team<'a>(
154        &'a self,
155        team_id: &'a str,
156        body: &crate::types::CreateContact,
157    ) -> Result<crate::types::ContactResponse, crate::types::error::Error> {
158        let mut req = self.client.client.request(
159            http::Method::POST,
160            &format!(
161                "{}/{}",
162                self.client.base_url,
163                "teams/{team_id}/contacts".replace("{team_id}", team_id)
164            ),
165        );
166        req = req.bearer_auth(&self.client.token);
167        req = req.json(body);
168        let resp = req.send().await?;
169        let status = resp.status();
170        if status.is_success() {
171            let text = resp.text().await.unwrap_or_default();
172            serde_json::from_str(&text).map_err(|err| {
173                crate::types::error::Error::from_serde_error(
174                    format_serde_error::SerdeError::new(text.to_string(), err),
175                    status,
176                )
177            })
178        } else {
179            Err(crate::types::error::Error::UnexpectedResponse(resp))
180        }
181    }
182
183    #[doc = "List teammate contacts\n\nList the contacts of a teammate.\n\n**Parameters:**\n\n- `limit: Option<i64>`: Max number of results per page\n- `page_token: Option<String>`: Token to use to request the next page\n- `q: Option<String>`: Search query object with the optional properties `updated_after` and `updated_before`, whose value should be a timestamp in seconds with up to 3 decimal places.\n- `sort_by: Option<String>`: Field used to sort the records\n- `sort_order: Option<crate::types::SortOrder>`: Order by which results should be sorted\n- `teammate_id: &'astr`: The teammate ID (required)\n\n```rust,no_run\nasync fn example_contacts_list_teammate() -> anyhow::Result<()> {\n    let client = front_api::Client::new_from_env();\n    let result: front_api::types::ListTeammateContactsResponse = client\n        .contacts()\n        .list_teammate(\n            Some(4 as i64),\n            Some(\"some-string\".to_string()),\n            Some(\"some-string\".to_string()),\n            Some(\"some-string\".to_string()),\n            Some(front_api::types::SortOrder::Asc),\n            \"some-string\",\n        )\n        .await?;\n    println!(\"{:?}\", result);\n    Ok(())\n}\n```"]
184    #[tracing::instrument]
185    pub async fn list_teammate<'a>(
186        &'a self,
187        limit: Option<i64>,
188        page_token: Option<String>,
189        q: Option<String>,
190        sort_by: Option<String>,
191        sort_order: Option<crate::types::SortOrder>,
192        teammate_id: &'a str,
193    ) -> Result<crate::types::ListTeammateContactsResponse, crate::types::error::Error> {
194        let mut req = self.client.client.request(
195            http::Method::GET,
196            &format!(
197                "{}/{}",
198                self.client.base_url,
199                "teammates/{teammate_id}/contacts".replace("{teammate_id}", teammate_id)
200            ),
201        );
202        req = req.bearer_auth(&self.client.token);
203        let mut query_params = Vec::new();
204        if let Some(p) = limit {
205            query_params.push(("limit", format!("{}", p)));
206        }
207
208        if let Some(p) = page_token {
209            query_params.push(("page_token", p));
210        }
211
212        if let Some(p) = q {
213            query_params.push(("q", p));
214        }
215
216        if let Some(p) = sort_by {
217            query_params.push(("sort_by", p));
218        }
219
220        if let Some(p) = sort_order {
221            query_params.push(("sort_order", format!("{}", p)));
222        }
223
224        req = req.query(&query_params);
225        let resp = req.send().await?;
226        let status = resp.status();
227        if status.is_success() {
228            let text = resp.text().await.unwrap_or_default();
229            serde_json::from_str(&text).map_err(|err| {
230                crate::types::error::Error::from_serde_error(
231                    format_serde_error::SerdeError::new(text.to_string(), err),
232                    status,
233                )
234            })
235        } else {
236            Err(crate::types::error::Error::UnexpectedResponse(resp))
237        }
238    }
239
240    #[doc = "Create teammate contact\n\nCreate a contact for a teammate.\n\n**Parameters:**\n\n- `teammate_id: &'astr`: The teammate ID (required)\n\n```rust,no_run\nasync fn example_contacts_create_teammate() -> anyhow::Result<()> {\n    let client = front_api::Client::new_from_env();\n    let result: front_api::types::ContactResponse = client\n        .contacts()\n        .create_teammate(\n            \"some-string\",\n            &front_api::types::CreateContact {\n                name: Some(\"some-string\".to_string()),\n                description: Some(\"some-string\".to_string()),\n                avatar: Some(bytes::Bytes::from(\"some-string\")),\n                is_spammer: Some(false),\n                links: Some(vec![\"some-string\".to_string()]),\n                group_names: Some(vec![\"some-string\".to_string()]),\n                custom_fields: Some(std::collections::HashMap::from([(\n                    \"some-key\".to_string(),\n                    \"some-string\".to_string(),\n                )])),\n                handles: Some(vec![front_api::types::ContactHandle {\n                    handle: \"some-string\".to_string(),\n                    source: front_api::types::Source::Twitter,\n                }]),\n            },\n        )\n        .await?;\n    println!(\"{:?}\", result);\n    Ok(())\n}\n```"]
241    #[tracing::instrument]
242    pub async fn create_teammate<'a>(
243        &'a self,
244        teammate_id: &'a str,
245        body: &crate::types::CreateContact,
246    ) -> Result<crate::types::ContactResponse, crate::types::error::Error> {
247        let mut req = self.client.client.request(
248            http::Method::POST,
249            &format!(
250                "{}/{}",
251                self.client.base_url,
252                "teammates/{teammate_id}/contacts".replace("{teammate_id}", teammate_id)
253            ),
254        );
255        req = req.bearer_auth(&self.client.token);
256        req = req.json(body);
257        let resp = req.send().await?;
258        let status = resp.status();
259        if status.is_success() {
260            let text = resp.text().await.unwrap_or_default();
261            serde_json::from_str(&text).map_err(|err| {
262                crate::types::error::Error::from_serde_error(
263                    format_serde_error::SerdeError::new(text.to_string(), err),
264                    status,
265                )
266            })
267        } else {
268            Err(crate::types::error::Error::UnexpectedResponse(resp))
269        }
270    }
271
272    #[doc = "Get contact\n\nFetch a contact.\n\n**Parameters:**\n\n- `contact_id: &'astr`: The \
273             contact ID (required)\n\n```rust,no_run\nasync fn example_contacts_get() -> \
274             anyhow::Result<()> {\n    let client = front_api::Client::new_from_env();\n    let \
275             result: front_api::types::ContactResponse = \
276             client.contacts().get(\"some-string\").await?;\n    println!(\"{:?}\", result);\n    \
277             Ok(())\n}\n```"]
278    #[tracing::instrument]
279    pub async fn get<'a>(
280        &'a self,
281        contact_id: &'a str,
282    ) -> Result<crate::types::ContactResponse, crate::types::error::Error> {
283        let mut req = self.client.client.request(
284            http::Method::GET,
285            &format!(
286                "{}/{}",
287                self.client.base_url,
288                "contacts/{contact_id}".replace("{contact_id}", contact_id)
289            ),
290        );
291        req = req.bearer_auth(&self.client.token);
292        let resp = req.send().await?;
293        let status = resp.status();
294        if status.is_success() {
295            let text = resp.text().await.unwrap_or_default();
296            serde_json::from_str(&text).map_err(|err| {
297                crate::types::error::Error::from_serde_error(
298                    format_serde_error::SerdeError::new(text.to_string(), err),
299                    status,
300                )
301            })
302        } else {
303            Err(crate::types::error::Error::UnexpectedResponse(resp))
304        }
305    }
306
307    #[doc = "Delete a contact\n\nDelete a contact.\n\n**Parameters:**\n\n- `contact_id: &'astr`: \
308             The contact ID (required)\n\n```rust,no_run\nasync fn example_contacts_delete() -> \
309             anyhow::Result<()> {\n    let client = front_api::Client::new_from_env();\n    \
310             client.contacts().delete(\"some-string\").await?;\n    Ok(())\n}\n```"]
311    #[tracing::instrument]
312    pub async fn delete<'a>(
313        &'a self,
314        contact_id: &'a str,
315    ) -> Result<(), crate::types::error::Error> {
316        let mut req = self.client.client.request(
317            http::Method::DELETE,
318            &format!(
319                "{}/{}",
320                self.client.base_url,
321                "contacts/{contact_id}".replace("{contact_id}", contact_id)
322            ),
323        );
324        req = req.bearer_auth(&self.client.token);
325        let resp = req.send().await?;
326        let status = resp.status();
327        if status.is_success() {
328            Ok(())
329        } else {
330            Err(crate::types::error::Error::UnexpectedResponse(resp))
331        }
332    }
333
334    #[doc = "Update a contact\n\nUpdates a contact.\n\n**Parameters:**\n\n- `contact_id: &'astr`: The contact ID (required)\n\n```rust,no_run\nasync fn example_contacts_update() -> anyhow::Result<()> {\n    let client = front_api::Client::new_from_env();\n    client\n        .contacts()\n        .update(\n            \"some-string\",\n            &front_api::types::Contact {\n                name: Some(\"some-string\".to_string()),\n                description: Some(\"some-string\".to_string()),\n                avatar: Some(bytes::Bytes::from(\"some-string\")),\n                is_spammer: Some(true),\n                links: Some(vec![\"some-string\".to_string()]),\n                group_names: Some(vec![\"some-string\".to_string()]),\n                custom_fields: Some(std::collections::HashMap::from([(\n                    \"some-key\".to_string(),\n                    \"some-string\".to_string(),\n                )])),\n            },\n        )\n        .await?;\n    Ok(())\n}\n```"]
335    #[tracing::instrument]
336    pub async fn update<'a>(
337        &'a self,
338        contact_id: &'a str,
339        body: &crate::types::Contact,
340    ) -> Result<(), crate::types::error::Error> {
341        let mut req = self.client.client.request(
342            http::Method::PATCH,
343            &format!(
344                "{}/{}",
345                self.client.base_url,
346                "contacts/{contact_id}".replace("{contact_id}", contact_id)
347            ),
348        );
349        req = req.bearer_auth(&self.client.token);
350        req = req.json(body);
351        let resp = req.send().await?;
352        let status = resp.status();
353        if status.is_success() {
354            Ok(())
355        } else {
356            Err(crate::types::error::Error::UnexpectedResponse(resp))
357        }
358    }
359
360    #[doc = "Merge contacts\n\nMerges the contacts specified into a single contact, deleting the merged-in contacts.\nIf a target contact ID is supplied, the other contacts will be merged into that one.\nOtherwise, some contact in the contact ID list will be treated as the target contact.\nMerge conflicts will be resolved in the following ways:\n  * name will prioritize manually-updated and non-private contact names\n  * descriptions will be concatenated and separated by newlines in order from\n    oldest to newest with the (optional) target contact's description first\n  * all handles, groups, links, and notes will be preserved\n  * other conflicts will use the most recently updated contact's value\n\n\n```rust,no_run\nasync fn example_contacts_merge() -> anyhow::Result<()> {\n    let client = front_api::Client::new_from_env();\n    let result: front_api::types::ContactResponse = client\n        .contacts()\n        .merge(&serde_json::Value::String(\"some-string\".to_string()))\n        .await?;\n    println!(\"{:?}\", result);\n    Ok(())\n}\n```"]
361    #[tracing::instrument]
362    pub async fn merge<'a>(
363        &'a self,
364        body: &crate::types::MergeContacts,
365    ) -> Result<crate::types::ContactResponse, crate::types::error::Error> {
366        let mut req = self.client.client.request(
367            http::Method::POST,
368            &format!("{}/{}", self.client.base_url, "contacts/merge"),
369        );
370        req = req.bearer_auth(&self.client.token);
371        req = req.json(body);
372        let resp = req.send().await?;
373        let status = resp.status();
374        if status.is_success() {
375            let text = resp.text().await.unwrap_or_default();
376            serde_json::from_str(&text).map_err(|err| {
377                crate::types::error::Error::from_serde_error(
378                    format_serde_error::SerdeError::new(text.to_string(), err),
379                    status,
380                )
381            })
382        } else {
383            Err(crate::types::error::Error::UnexpectedResponse(resp))
384        }
385    }
386
387    #[doc = "List contact conversations\n\nList the conversations for a contact in reverse chronological order (newest first). For more advanced filtering, see the [search endpoint](https://dev.frontapp.com/reference/conversations#search-conversations).\n> ⚠\u{fe0f} Deprecated field included\n>\n> This endpoint returns a deprecated `last_message` field in the top-level conversation bodies listed. Please use the\n> `_links.related.last_message` field instead.\n\n\n**Parameters:**\n\n- `contact_id: &'astr`: The Contact ID (required)\n- `limit: Option<i64>`: Max number of results per page\n- `page_token: Option<String>`: Token to use to request the next page\n- `q: Option<String>`: Search query object with a property `statuses`, whose value should be a list of conversation statuses (`assigned`, `unassigned`, `archived`, or `deleted`).\n\n```rust,no_run\nasync fn example_contacts_list_conversations() -> anyhow::Result<()> {\n    let client = front_api::Client::new_from_env();\n    let result: front_api::types::ListContactConversationsResponse = client\n        .contacts()\n        .list_conversations(\n            \"some-string\",\n            Some(4 as i64),\n            Some(\"some-string\".to_string()),\n            Some(\"some-string\".to_string()),\n        )\n        .await?;\n    println!(\"{:?}\", result);\n    Ok(())\n}\n```"]
388    #[tracing::instrument]
389    pub async fn list_conversations<'a>(
390        &'a self,
391        contact_id: &'a str,
392        limit: Option<i64>,
393        page_token: Option<String>,
394        q: Option<String>,
395    ) -> Result<crate::types::ListContactConversationsResponse, crate::types::error::Error> {
396        let mut req = self.client.client.request(
397            http::Method::GET,
398            &format!(
399                "{}/{}",
400                self.client.base_url,
401                "contacts/{contact_id}/conversations".replace("{contact_id}", contact_id)
402            ),
403        );
404        req = req.bearer_auth(&self.client.token);
405        let mut query_params = Vec::new();
406        if let Some(p) = limit {
407            query_params.push(("limit", format!("{}", p)));
408        }
409
410        if let Some(p) = page_token {
411            query_params.push(("page_token", p));
412        }
413
414        if let Some(p) = q {
415            query_params.push(("q", p));
416        }
417
418        req = req.query(&query_params);
419        let resp = req.send().await?;
420        let status = resp.status();
421        if status.is_success() {
422            let text = resp.text().await.unwrap_or_default();
423            serde_json::from_str(&text).map_err(|err| {
424                crate::types::error::Error::from_serde_error(
425                    format_serde_error::SerdeError::new(text.to_string(), err),
426                    status,
427                )
428            })
429        } else {
430            Err(crate::types::error::Error::UnexpectedResponse(resp))
431        }
432    }
433}