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