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