Skip to main content

zero_bounce/utility/structures/
bulk.rs

1use std::fmt::Debug;
2use std::io::Read;
3
4use bytes::Bytes;
5use chrono::{DateTime, FixedOffset};
6use reqwest::blocking::multipart::{Form, Part};
7
8use serde::Deserialize;
9
10use crate::utility::structures::custom_deserialize::{deserialize_date_rfc, deserialize_message_text, null_as_default};
11use crate::utility::structures::custom_deserialize::deserialize_percentage_float;
12use crate::utility::{ZBError, ZBResult};
13
14#[derive(Clone, Debug, Deserialize)]
15pub struct ZBFileFeedback {
16    #[serde(deserialize_with = "null_as_default")]
17    pub success: bool,
18    /// A list of messages from the API is joined with newlines.
19    #[serde(deserialize_with = "deserialize_message_text")]
20    pub message: String,
21    pub file_name: Option<String>,
22    pub file_id: Option<String>,
23}
24
25#[derive(Clone, Debug, Deserialize)]
26pub struct ZBFileStatus {
27    #[serde(deserialize_with = "null_as_default")]
28    pub success: bool,
29    #[serde(deserialize_with = "null_as_default")]
30    pub file_id: String,
31    #[serde(deserialize_with = "null_as_default")]
32    pub file_name: String,
33    #[serde(deserialize_with = "null_as_default")]
34    pub file_status: String,
35    pub error_reason: Option<String>,
36    #[serde(default)]
37    pub file_phase_2_status: Option<String>,
38    pub return_url: Option<String>,
39
40    #[serde(deserialize_with = "deserialize_date_rfc")]
41    pub upload_date: DateTime<FixedOffset>,
42
43    #[serde(deserialize_with = "deserialize_percentage_float")]
44    pub complete_percentage: f32,
45}
46
47/// `download_type` query values for bulk getfile (validation and scoring).
48pub mod zb_download_type {
49    pub const PHASE_1: &str = "phase_1";
50    pub const PHASE_2: &str = "phase_2";
51    pub const COMBINED: &str = "combined";
52}
53
54/// Optional v2 query parameters for bulk getfile.
55#[derive(Clone, Debug, Default)]
56pub struct ZBGetFileOptions {
57    pub download_type: Option<String>,
58    /// Validation getfile only; omitted for AI scoring result fetch.
59    pub activity_data: Option<bool>,
60}
61
62/// Optional columns for bulk email finder `sendfile`.
63///
64/// `first_name_column` or `full_name_column` is required; the API rejects a file
65/// that carries neither. The rest are omitted when `None`, and `Some(0)` is sent.
66#[derive(Clone, Debug, Default)]
67pub struct ZBEmailFinderFileOptions {
68    pub first_name_column: Option<u32>,
69    pub full_name_column: Option<u32>,
70    pub middle_name_column: Option<u32>,
71    pub last_name_column: Option<u32>,
72    pub has_header_row: Option<bool>,
73}
74
75pub enum ZBBulkResponse {
76    Content(Bytes),
77    Feedback(ZBFileFeedback),
78}
79
80impl Debug for ZBBulkResponse {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        match &self {
83            Self::Content(cnt) => {
84                write!(f, "<ZBBulkResponse::Content | size {}>", cnt.len())
85            }
86            Self::Feedback(feedback) => {
87                write!(f, "<ZBBulkResponse::Feedback | {:#?}>", feedback)
88            }
89        }
90    }
91}
92
93#[derive(Debug, Clone)]
94pub enum ZBFileContentType {
95    FilePath(String),
96    RawContent(Vec<u8>),
97    Empty,
98}
99
100impl ZBFileContentType {
101    pub fn is_empty(&self) -> bool {
102        match self {
103            Self::Empty => true,
104            Self::RawContent(vec) => vec.len() == 0,
105            _ => false,
106        }
107    }
108}
109
110pub struct ZBFile {
111    content_type: ZBFileContentType,
112    has_header_row: bool,
113    remove_duplicate: bool,
114    email_address_column: u32,
115    first_name_column: Option<u32>,
116    last_name_column: Option<u32>,
117    gender_column: Option<u32>,
118    ip_address_column: Option<u32>,
119    /// Optional callback URL for when validation/scoring is complete (sendfile APIs).
120    return_url: Option<String>,
121    /// Optional file name for multipart upload; used when content is raw (from_content). Ignored when using file path.
122    file_name: Option<String>,
123    /// Bulk validation sendfile only; not sent for AI scoring sendfile.
124    pub(crate) allow_phase_2: Option<bool>,
125}
126
127impl Default for ZBFile {
128    fn default() -> Self {
129        ZBFile {
130            content_type: ZBFileContentType::Empty,
131            has_header_row: true,
132            remove_duplicate: false,
133            email_address_column: 1,
134            first_name_column: None,
135            last_name_column: None,
136            gender_column: None,
137            ip_address_column: None,
138            return_url: None,
139            file_name: None,
140            allow_phase_2: None,
141        }
142    }
143}
144
145impl ZBFile {
146    pub fn from_path(path_to_file: String) -> ZBFile {
147        ZBFile {
148            content_type: ZBFileContentType::FilePath(path_to_file),
149            ..Default::default()
150        }
151    }
152
153    pub fn from_content(content: Vec<u8>) -> ZBFile {
154        ZBFile {
155            content_type: ZBFileContentType::RawContent(content),
156            ..Default::default()
157        }
158    }
159
160    /// Create a ZBFile from raw bytes with a specific file name (e.g. for stream-based uploads).
161    pub fn from_content_with_filename(content: Vec<u8>, file_name: impl Into<String>) -> ZBFile {
162        ZBFile {
163            content_type: ZBFileContentType::RawContent(content),
164            file_name: Some(file_name.into()),
165            ..Default::default()
166        }
167    }
168
169    /// Create a ZBFile from any reader (e.g. in-memory stream, network stream). Reads the entire content into memory.
170    pub fn from_reader(mut reader: impl Read, file_name: impl Into<String>) -> ZBResult<ZBFile> {
171        let mut content = Vec::new();
172        reader.read_to_end(&mut content)?;
173        Ok(Self::from_content_with_filename(content, file_name))
174    }
175
176    fn file_content_multipart(&self) -> ZBResult<Part> {
177        match self.content_type.clone() {
178            ZBFileContentType::Empty => Err(ZBError::explicit("bulk content cannot be empty")),
179            ZBFileContentType::FilePath(file_path) => Ok(Part::file(file_path.clone())?),
180            ZBFileContentType::RawContent(value) => {
181                let name = self
182                    .file_name
183                    .clone()
184                    .unwrap_or_else(|| "file.csv".to_string());
185                Ok(Part::bytes(value).file_name(name).mime_str("text/csv")?)
186            }
187        }
188    }
189
190    pub fn generate_multipart(&self) -> ZBResult<Form> {
191        self.generate_multipart_with(true)
192    }
193
194    /// `include_person_columns` is true for validation sendfile. Scoring sendfile omits them.
195    pub(crate) fn generate_multipart_with(&self, include_person_columns: bool) -> ZBResult<Form> {
196        let content_part = self.file_content_multipart()?;
197        let mut multipart_form = Form::new()
198            .part("file", content_part)
199            .text("has_header_row", self.has_header_row.to_string())
200            .text("remove_duplicate", self.remove_duplicate.to_string())
201            .text(
202                "email_address_column",
203                self.email_address_column.to_string(),
204            );
205
206        if include_person_columns {
207            if let Some(amount) = self.first_name_column {
208                multipart_form = multipart_form.text("first_name_column", amount.to_string());
209            }
210            if let Some(amount) = self.last_name_column {
211                multipart_form = multipart_form.text("last_name_column", amount.to_string());
212            }
213            if let Some(amount) = self.gender_column {
214                multipart_form = multipart_form.text("gender_column", amount.to_string());
215            }
216            if let Some(amount) = self.ip_address_column {
217                multipart_form = multipart_form.text("ip_address_column", amount.to_string());
218            }
219        }
220        if let Some(url) = &self.return_url {
221            multipart_form = multipart_form.text("return_url", url.clone());
222        }
223
224        Ok(multipart_form)
225    }
226
227    /// Set the callback URL for when validation/scoring is complete (optional).
228    pub fn set_return_url(mut self, return_url: Option<impl Into<String>>) -> Self {
229        self.return_url = return_url.map(Into::into);
230        self
231    }
232
233    /// Set the file name used when uploading raw content (optional; default "file.csv").
234    pub fn set_file_name(mut self, file_name: Option<impl Into<String>>) -> Self {
235        self.file_name = file_name.map(Into::into);
236        self
237    }
238
239    pub fn set_has_header_row(mut self, has_header_row: bool) -> Self {
240        self.has_header_row = has_header_row;
241        self
242    }
243
244    /// The `remove_duplicate` sent with the file. It is always sent; the
245    /// default is `false` (the API's own default, used when the field is
246    /// absent, is true).
247    pub fn set_remove_duplicate(mut self, remove_duplicate: bool) -> Self {
248        self.remove_duplicate = remove_duplicate;
249        self
250    }
251
252    pub fn set_email_address_column(mut self, email_address_column: u32) -> Self {
253        self.email_address_column = email_address_column;
254        self
255    }
256
257    pub fn set_first_name_column(mut self, first_name_column: Option<u32>) -> Self {
258        self.first_name_column = first_name_column;
259        self
260    }
261
262    pub fn set_last_name_column(mut self, last_name_column: Option<u32>) -> Self {
263        self.last_name_column = last_name_column;
264        self
265    }
266
267    pub fn set_gender_column(mut self, gender_column: Option<u32>) -> Self {
268        self.gender_column = gender_column;
269        self
270    }
271
272    pub fn set_ip_address_column(mut self, ip_address_column: Option<u32>) -> Self {
273        self.ip_address_column = ip_address_column;
274        self
275    }
276
277    /// Set `allow_phase_2` for **bulk validation** sendfile only (ignored for AI scoring).
278    pub fn set_allow_phase_2(mut self, allow_phase_2: Option<bool>) -> Self {
279        self.allow_phase_2 = allow_phase_2;
280        self
281    }
282}
283
284#[cfg(test)]
285mod test {
286    use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
287    use serde_json::{from_str, Result as SerdeResult};
288
289    use super::*;
290    use crate::utility::mock_constants::BULK_VALIDATION_DELETE_OK;
291    use crate::utility::mock_constants::BULK_VALIDATION_RESULT_DELETED;
292    use crate::utility::mock_constants::BULK_VALIDATION_STATUS_DELETED;
293    use crate::utility::mock_constants::BULK_VALIDATION_STATUS_OK;
294    use crate::utility::mock_constants::BULK_VALIDATION_SUBMIT_OK;
295
296    #[test]
297    fn test_parsing_file_submit_response_ok() {
298        let validation: SerdeResult<ZBFileFeedback> = from_str(BULK_VALIDATION_SUBMIT_OK);
299        assert!(validation.is_ok());
300
301        let validation_obj = validation.unwrap();
302        assert!(validation_obj.success);
303        assert!(validation_obj.file_id.is_some());
304        assert!(validation_obj.file_name.is_some());
305        assert_eq!(validation_obj.message, "File Accepted");
306    }
307
308    #[test]
309    fn test_parse_file_status_response_ok() {
310        let file_status: SerdeResult<ZBFileStatus> = from_str(BULK_VALIDATION_STATUS_OK);
311        assert!(file_status.is_ok());
312
313        let expected_date_time = NaiveDateTime::new(
314            NaiveDate::from_ymd_opt(2023, 4, 26).unwrap(),
315            NaiveTime::from_hms_opt(17, 52, 23).unwrap(),
316        );
317
318        let file_status_obj = file_status.unwrap();
319        assert!(file_status_obj.success);
320        assert_eq!(file_status_obj.complete_percentage, 100.);
321        assert_eq!(file_status_obj.upload_date.naive_utc(), expected_date_time);
322        assert!(file_status_obj.return_url.is_some());
323        assert!(file_status_obj.error_reason.is_none());
324    }
325
326    #[test]
327    fn test_parse_file_status_response_deleted() {
328        let file_status: SerdeResult<ZBFileStatus> = from_str(BULK_VALIDATION_STATUS_DELETED);
329        assert!(file_status.is_ok());
330
331        let expected_date_time = NaiveDateTime::new(
332            NaiveDate::from_ymd_opt(2023, 4, 26).unwrap(),
333            NaiveTime::from_hms_opt(17, 52, 23).unwrap(),
334        );
335
336        let file_status_obj = file_status.unwrap();
337        assert!(file_status_obj.success);
338        assert_eq!(file_status_obj.complete_percentage, 0.);
339        assert_eq!(file_status_obj.upload_date.naive_utc(), expected_date_time);
340        assert!(file_status_obj.return_url.is_none());
341        assert!(file_status_obj.error_reason.is_some());
342    }
343
344    #[test]
345    fn test_parse_file_result_deleted() {
346        let feedback: SerdeResult<ZBFileFeedback> = from_str(BULK_VALIDATION_RESULT_DELETED);
347        assert!(feedback.is_ok());
348
349        let feedback_obj = feedback.unwrap();
350        assert!(!(feedback_obj.success));
351        assert!(feedback_obj.file_id.is_none());
352        assert!(feedback_obj.file_name.is_none());
353    }
354
355    #[test]
356    fn test_parse_file_delete_ok() {
357        let feedback: SerdeResult<ZBFileFeedback> = from_str(BULK_VALIDATION_DELETE_OK);
358        assert!(feedback.is_ok());
359
360        let feedback_obj = feedback.unwrap();
361        assert!(feedback_obj.success);
362        assert!(feedback_obj.file_id.is_some());
363        assert!(feedback_obj.file_name.is_some());
364        assert_eq!(feedback_obj.message, "File Deleted");
365    }
366}