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
use serde::Deserialize;

use crate::client::Mpesa;
use crate::constants::Invoice;
use crate::environment::ApiEnvironment;
use crate::errors::{MpesaError, MpesaResult};

#[derive(Clone, Debug, Deserialize)]
pub struct BulkInvoiceResponse {
    #[serde(rename(deserialize = "rescode"))]
    pub response_code: String,
    #[serde(rename(deserialize = "resmsg"))]
    pub response_message: String,
    #[serde(rename(deserialize = "Status_Message"))]
    pub status_message: String,
}

#[derive(Debug)]
pub struct BulkInvoiceBuilder<'mpesa, Env: ApiEnvironment> {
    client: &'mpesa Mpesa<Env>,
    invoices: Vec<Invoice<'mpesa>>,
}

impl<'mpesa, Env: ApiEnvironment> BulkInvoiceBuilder<'mpesa, Env> {
    /// Creates a new Bill Manager Bulk Invoice builder
    pub fn new(client: &'mpesa Mpesa<Env>) -> BulkInvoiceBuilder<'mpesa, Env> {
        BulkInvoiceBuilder {
            client,
            invoices: vec![],
        }
    }

    /// Adds a single `invoice`
    pub fn invoice(mut self, invoice: Invoice<'mpesa>) -> BulkInvoiceBuilder<'mpesa, Env> {
        self.invoices.push(invoice);
        self
    }

    /// Adds multiple `invoices`
    pub fn invoices(
        mut self,
        mut invoices: Vec<Invoice<'mpesa>>,
    ) -> BulkInvoiceBuilder<'mpesa, Env> {
        self.invoices.append(&mut invoices);
        self
    }

    /// Bill Manager Bulk Invoice API
    ///
    /// Sends invoices to your customers in bulk
    ///
    /// # Errors
    /// Returns an `MpesaError` on failure.
    #[allow(clippy::unnecessary_lazy_evaluations)]
    pub async fn send(self) -> MpesaResult<BulkInvoiceResponse> {
        let url = format!(
            "{}/v1/billmanager-invoice/bulk-invoicing",
            self.client.environment.base_url()
        );

        if self.invoices.is_empty() {
            return Err(MpesaError::Message("invoices cannot be empty"));
        }

        let response = self
            .client
            .http_client
            .post(&url)
            .bearer_auth(self.client.auth().await?)
            .json(&self.invoices)
            .send()
            .await?;

        if response.status().is_success() {
            let value = response.json().await?;
            return Ok(value);
        }

        let value = response.json().await?;
        Err(MpesaError::BulkInvoiceError(value))
    }
}