zero-bounce 2.1.0

Wrapper library over the ZeroBounce API v2
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
pub mod bulk;
pub mod validation;

use std::collections::HashMap;

use chrono::{NaiveDate, Utc};
use serde_json::from_str;

pub use crate::ZeroBounce;
use crate::utility::structures::generic::{FindEmailResponse, FindEmailResponseV2, DomainSearchResponseV2};
use crate::utility::{ZBError, ZBResult, ENDPOINT_EMAIL_FINDER};
use crate::utility::structures::{ActivityData, ApiUsage};
use crate::utility::{ENDPOINT_ACTIVITY_DATA, ENDPOINT_API_USAGE, ENDPOINT_CREDITS};

/// Builder for the `find_email_v2` API call.
/// 
/// # Example
/// ```no_run
/// use zero_bounce::ZeroBounce;
/// use zero_bounce::utility::ZBResult;
/// 
/// # fn main() -> ZBResult<()> {
/// let zb = ZeroBounce::new("your_api_key");
/// let result = zb.find_email_v2()
///     .first_name("John")
///     .domain("example.com")
///     .last_name("Doe")
///     .call()?;
/// # Ok(())
/// # }
/// ```
pub struct FindEmailV2Builder<'a> {
    client: &'a ZeroBounce,
    first_name: Option<&'a str>,
    domain: Option<&'a str>,
    company_name: Option<&'a str>,
    middle_name: Option<&'a str>,
    last_name: Option<&'a str>,
}

/// Builder for the `domain_search_v2` API call.
/// 
/// # Example
/// ```no_run
/// use zero_bounce::ZeroBounce;
/// use zero_bounce::utility::ZBResult;
/// 
/// # fn main() -> ZBResult<()> {
/// let zb = ZeroBounce::new("your_api_key");
/// let result = zb.domain_search_v2()
///     .domain("example.com")
///     .call()?;
/// # Ok(())
/// # }
/// ```
pub struct DomainSearchV2Builder<'a> {
    client: &'a ZeroBounce,
    domain: Option<&'a str>,
    company_name: Option<&'a str>,
}

impl ZeroBounce {

    fn get_credits_from_string(string_value: String) -> ZBResult<i64> {
        from_str::<serde_json::Value>(string_value.as_ref())?
            .get("Credits")
            .and_then(serde_json::Value::as_str)
            .map(str::parse::<i64>)
            .ok_or(ZBError::explicit("credits value not in json"))?
            .map_err(ZBError::IntParseError)
    }

    pub fn get_credits(&self) -> ZBResult<i64> {
        let query_args = HashMap::new();

        let response_content = self.generic_get_request(
            self.url_provider.url_of(ENDPOINT_CREDITS), query_args
        )?;

        Self::get_credits_from_string(response_content)
    }

    pub fn get_api_usage(&self, start_date: NaiveDate, end_date: NaiveDate) -> ZBResult<ApiUsage> {
        let start_date_str = start_date.format("%F").to_string();
        let end_date_str = end_date.format("%F").to_string();
        let query_args = HashMap::from([
            ("start_date", start_date_str.as_str()),
            ("end_date", end_date_str.as_str()),
        ]);

        let response_content = self.generic_get_request(
            self.url_provider.url_of(ENDPOINT_API_USAGE), query_args
        )?;

        let api_usage = from_str::<ApiUsage>(&response_content)?;
        Ok(api_usage)
    }

    pub fn get_api_usage_overall(&self) -> ZBResult<ApiUsage> {
        let start_date = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
        let end_date = Utc::now().naive_local().date();
        self.get_api_usage(start_date, end_date)
    }

    pub fn get_activity_data(&self, email: &str) -> ZBResult<ActivityData> {
        let query_args = HashMap::from([
            ("email", email),
        ]);

        let response_content = self.generic_get_request(
            self.url_provider.url_of(ENDPOINT_ACTIVITY_DATA), query_args
        )?;

        let activity_data = from_str::<ActivityData>(&response_content)?;
        Ok(activity_data)
    }

    /// Deprecated: Use `find_email_v2` instead.
    /// 
    /// This function is kept for backward compatibility but will be removed in a future version.
    #[deprecated(
        since = "1.2.0",
        note = "Use `find_email_v2` instead. The new version supports both domain and company_name parameters."
    )]
    pub fn find_email(&self, domain: &str, first_name: &str, middle_name: &str, last_name: &str) -> ZBResult<FindEmailResponse> {
        let mut query_args = HashMap::from([
            ("domain", domain),
        ]);
        if !first_name.is_empty() {
            query_args.insert("first_name", first_name);
        }
        if !middle_name.is_empty() {
            query_args.insert("middle_name", middle_name);
        }
        if !last_name.is_empty() {
            query_args.insert("last_name", last_name);
        }

        let response_content = self.generic_get_request(
            self.url_provider.url_of(ENDPOINT_EMAIL_FINDER), query_args
        )?;

        let activity_data = from_str::<FindEmailResponse>(&response_content)?;
        Ok(activity_data)
    }

    /// Find an email address using either a domain or company name.
    /// 
    /// Returns a builder that allows you to set parameters using method chaining.
    /// 
    /// # Requirements
    /// - `first_name` is mandatory
    /// - Exactly one of `domain` or `company_name` must be provided (XOR requirement)
    /// 
    /// # Example
    /// ```no_run
    /// use zero_bounce::ZeroBounce;
    /// use zero_bounce::utility::ZBResult;
    /// 
    /// # fn main() -> ZBResult<()> {
    /// let zb = ZeroBounce::new("your_api_key");
    /// // Using domain
    /// let result = zb.find_email_v2()
    ///     .first_name("John")
    ///     .domain("example.com")
    ///     .last_name("Doe")
    ///     .call()?;
    /// // Or using company name
    /// let result = zb.find_email_v2()
    ///     .first_name("John")
    ///     .company_name("Example Inc")
    ///     .last_name("Doe")
    ///     .call()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn find_email_v2(&self) -> FindEmailV2Builder<'_> {
        FindEmailV2Builder {
            client: self,
            first_name: None,
            domain: None,
            company_name: None,
            middle_name: None,
            last_name: None,
        }
    }

    /// Deprecated: Use `domain_search_v2` instead.
    /// 
    /// This function is kept for backward compatibility but will be removed in a future version.
    #[deprecated(
        since = "1.2.0",
        note = "Use `domain_search_v2` instead. The new version supports both domain and company_name parameters."
    )]
    #[allow(deprecated)] // This method uses deprecated find_email, which is expected
    pub fn domain_search(&self, domain: &str) -> ZBResult<FindEmailResponse> {
        self.find_email(domain, "", "", "")
    }

    /// Search for email formats using either a domain or company name.
    /// 
    /// Returns a builder that allows you to set parameters using method chaining.
    /// 
    /// # Requirements
    /// Exactly one of `domain` or `company_name` must be provided (XOR requirement).
    /// 
    /// # Example
    /// ```no_run
    /// use zero_bounce::ZeroBounce;
    /// use zero_bounce::utility::ZBResult;
    /// 
    /// # fn main() -> ZBResult<()> {
    /// let zb = ZeroBounce::new("your_api_key");
    /// // Using domain
    /// let result = zb.domain_search_v2()
    ///     .domain("example.com")
    ///     .call()?;
    /// // Or using company name
    /// let result = zb.domain_search_v2()
    ///     .company_name("Example Inc")
    ///     .call()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn domain_search_v2(&self) -> DomainSearchV2Builder<'_> {
        DomainSearchV2Builder {
            client: self,
            domain: None,
            company_name: None,
        }
    }

}

impl<'a> FindEmailV2Builder<'a> {
    /// Set the first name (mandatory).
    pub fn first_name(mut self, name: &'a str) -> Self {
        self.first_name = Some(name);
        self
    }

    /// Set the domain name (exactly one of domain or company_name must be provided).
    pub fn domain(mut self, domain: &'a str) -> Self {
        self.domain = Some(domain);
        self
    }

    /// Set the company name (exactly one of domain or company_name must be provided).
    pub fn company_name(mut self, company: &'a str) -> Self {
        self.company_name = Some(company);
        self
    }

    /// Set the middle name (optional).
    pub fn middle_name(mut self, name: &'a str) -> Self {
        self.middle_name = Some(name);
        self
    }

    /// Set the last name (optional).
    pub fn last_name(mut self, name: &'a str) -> Self {
        self.last_name = Some(name);
        self
    }

    /// Execute the API call and return the result.
    pub fn call(self) -> ZBResult<FindEmailResponseV2> {
        let first_name = self.first_name.ok_or_else(|| ZBError::explicit("first_name is mandatory and must be set"))?;
        
        if first_name.is_empty() {
            return Err(ZBError::explicit("first_name cannot be empty"));
        }

        // Validate XOR requirement: exactly one of domain or company_name must be provided
        match (self.domain, self.company_name) {
            (Some(d), None) => {
                if d.is_empty() {
                    return Err(ZBError::explicit("domain cannot be empty"));
                }
            }
            (None, Some(c)) => {
                if c.is_empty() {
                    return Err(ZBError::explicit("company_name cannot be empty"));
                }
            }
            (Some(_), Some(_)) => {
                return Err(ZBError::explicit("exactly one of domain or company_name must be provided, not both"));
            }
            (None, None) => {
                return Err(ZBError::explicit("either domain or company_name must be provided"));
            }
        }

        let mut query_args = HashMap::from([
            ("first_name", first_name),
        ]);

        if let Some(d) = self.domain {
            query_args.insert("domain", d);
        }

        if let Some(c) = self.company_name {
            query_args.insert("company_name", c);
        }

        if let Some(middle) = self.middle_name {
            if !middle.is_empty() {
                query_args.insert("middle_name", middle);
            }
        }

        if let Some(last) = self.last_name {
            if !last.is_empty() {
                query_args.insert("last_name", last);
            }
        }

        let response_content = self.client.generic_get_request(
            self.client.url_provider.url_of(ENDPOINT_EMAIL_FINDER), query_args
        )?;

        let find_email_response = from_str::<FindEmailResponseV2>(&response_content)?;
        Ok(find_email_response)
    }
}

impl<'a> DomainSearchV2Builder<'a> {
    /// Set the domain name (exactly one of domain or company_name must be provided).
    pub fn domain(mut self, domain: &'a str) -> Self {
        self.domain = Some(domain);
        self
    }

    /// Set the company name (exactly one of domain or company_name must be provided).
    pub fn company_name(mut self, company: &'a str) -> Self {
        self.company_name = Some(company);
        self
    }

    /// Execute the API call and return the result.
    pub fn call(self) -> ZBResult<DomainSearchResponseV2> {
        // Validate XOR requirement: exactly one of domain or company_name must be provided
        match (self.domain, self.company_name) {
            (Some(d), None) => {
                if d.is_empty() {
                    return Err(ZBError::explicit("domain cannot be empty"));
                }
            }
            (None, Some(c)) => {
                if c.is_empty() {
                    return Err(ZBError::explicit("company_name cannot be empty"));
                }
            }
            (Some(_), Some(_)) => {
                return Err(ZBError::explicit("exactly one of domain or company_name must be provided, not both"));
            }
            (None, None) => {
                return Err(ZBError::explicit("either domain or company_name must be provided"));
            }
        }

        let mut query_args = HashMap::new();

        if let Some(d) = self.domain {
            query_args.insert("domain", d);
        }

        if let Some(c) = self.company_name {
            query_args.insert("company_name", c);
        }

        let response_content = self.client.generic_get_request(
            self.client.url_provider.url_of(ENDPOINT_EMAIL_FINDER), query_args
        )?;

        let domain_search_response = from_str::<DomainSearchResponseV2>(&response_content)?;
        Ok(domain_search_response)
    }
}

#[cfg(test)]
mod tests {
    use crate::utility::mock_constants::CREDITS_RESPONSE_OK;
    use crate::utility::mock_constants::CREDITS_RESPONSE_NEGATIVE;

    use super::*;

    #[test]
    fn test_credits_negative() {
        let credits = ZeroBounce::get_credits_from_string(CREDITS_RESPONSE_NEGATIVE.to_string());
        assert!(credits.is_ok());

        let amount = credits.unwrap();
        assert_eq!(amount, -1);
    }

    #[test]
    fn test_credits_ok() {
        let credits = ZeroBounce::get_credits_from_string(CREDITS_RESPONSE_OK.to_string());
        assert!(credits.is_ok());

        let amount = credits.unwrap();
        assert_eq!(amount, 123456);
    }

}