lago_client/queries/
invoice.rs

1use lago_types::{
2    error::{LagoError, Result},
3    requests::invoice::{GetInvoiceRequest, InvoicePreviewRequest, ListInvoicesRequest},
4    responses::invoice::{GetInvoiceResponse, InvoicePreviewResponse, ListInvoicesResponse},
5};
6use url::Url;
7
8use crate::client::LagoClient;
9
10/// Invoice-related operations for the Lago client
11impl LagoClient {
12    /// Retrieves a list of invoices with optional filtering parameters
13    ///
14    /// # Arguments
15    /// * `request` - Optional filtering parameters for the invoice list
16    ///
17    /// # Returns
18    /// A `Result` containing the list of invoices or an error
19    pub async fn list_invoices(
20        &self,
21        request: Option<ListInvoicesRequest>,
22    ) -> Result<ListInvoicesResponse> {
23        let request = request.unwrap_or_default();
24        let region = self.config.region()?;
25        let mut url = Url::parse(&format!("{}/invoices", region.endpoint()))
26            .map_err(|e| LagoError::Configuration(format!("Invalid URL: {e}")))?;
27
28        let query_params = request.to_query_params();
29
30        if !query_params.is_empty() {
31            let query_string = query_params
32                .iter()
33                .map(|(k, v)| format!("{k}={v}"))
34                .collect::<Vec<_>>()
35                .join("&");
36            url.set_query(Some(&query_string));
37        }
38
39        self.make_request("GET", url.as_str(), None::<&()>).await
40    }
41
42    /// Retrieves a specific invoice by its ID
43    ///
44    /// # Arguments
45    /// * `request` - The request containing the invoice ID to retrieve
46    ///
47    /// # Returns
48    /// A `Result` containing the invoice data or an error
49    pub async fn get_invoice(&self, request: GetInvoiceRequest) -> Result<GetInvoiceResponse> {
50        let region = self.config.region()?;
51        let url = format!("{}/invoices/{}", region.endpoint(), request.invoice_id);
52        self.make_request("GET", &url, None::<&()>).await
53    }
54
55    /// Previews an invoice without creating it
56    ///
57    /// This endpoint allows you to retrieve an estimated invoice before finalization.
58    /// It can be used to preview invoices for new subscriptions or existing customers.
59    ///
60    /// # Arguments
61    /// * `request` - The invoice preview request containing customer and subscription details
62    ///
63    /// # Returns
64    /// A `Result` containing the previewed invoice or an error
65    pub async fn preview_invoice(
66        &self,
67        request: InvoicePreviewRequest,
68    ) -> Result<InvoicePreviewResponse> {
69        let region = self.config.region()?;
70        let url = format!("{}/invoices/preview", region.endpoint());
71        self.make_request("POST", &url, Some(&request)).await
72    }
73}