alguna 0.1.0

Rust SDK for the Alguna billing API
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
use crate::api::*;
use crate::{ApiError, ByteStream, ClientConfig, HttpClient, QueryBuilder, RequestOptions};
use crate::{AsyncPaginator, PaginationResult};
use reqwest::Method;

pub struct SubscriptionsClient {
    pub http_client: HttpClient,
}

impl SubscriptionsClient {
    pub fn new(config: ClientConfig) -> Result<Self, ApiError> {
        Ok(Self {
            http_client: HttpClient::new(config.clone())?,
        })
    }

    /// Returns a paginated list of subscriptions. Supports filtering by status, customer ID, and tag IDs.
    ///
    /// # Arguments
    ///
    /// * `customer_id` - Filter by customer ID
    /// * `limit` - Number of items per page
    /// * `offset` - Number of items to skip
    /// * `sort` - Sort field and direction in format field:order. Sortable fields: name, status, created_at, activated_at, ended_at, updated_at, contract_start_date, contract_end_date
    /// * `status` - Filter by subscription status. Pass a comma-separated list to match any.
    /// * `tag_ids` - Filter by tag IDs (comma-separated to match any)
    /// * `options` - Additional request options such as headers, timeout, etc.
    ///
    /// # Returns
    ///
    /// JSON response from the API
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use alguna::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let config = ClientConfig {
    ///         api_key: Some("<token>".to_string()),
    ///         ..Default::default()
    ///     };
    ///     let client = Alguna::new(config).expect("Failed to build client");
    ///     client
    ///         .subscriptions
    ///         .list(
    ///             &SubscriptionsListQueryRequest {
    ///                 customer_id: Some("cust_abc123".to_string()),
    ///                 limit: Some(20),
    ///                 offset: Some(0),
    ///                 sort: Some("created_at:desc".to_string()),
    ///                 status: vec![],
    ///                 tag_ids: vec![],
    ///             },
    ///             None,
    ///         )
    ///         .await;
    /// }
    /// ```
    pub async fn list(
        &self,
        request: &SubscriptionsListQueryRequest,
        options: Option<RequestOptions>,
    ) -> Result<SubscriptionListResponse, ApiError> {
        self.http_client
            .execute_request(
                Method::GET,
                "subscriptions",
                None,
                QueryBuilder::new()
                    .string("customer_id", request.customer_id.clone())
                    .int("limit", request.limit.clone())
                    .int("offset", request.offset.clone())
                    .string("sort", request.sort.clone())
                    .string("status", {
                        let joined = request
                            .status
                            .iter()
                            .flatten()
                            .map(|value| value.to_string())
                            .collect::<Vec<_>>()
                            .join(",");
                        if joined.is_empty() {
                            None
                        } else {
                            Some(joined)
                        }
                    })
                    .string("tag_ids", {
                        let joined = request
                            .tag_ids
                            .iter()
                            .flatten()
                            .map(|value| value.to_string())
                            .collect::<Vec<_>>()
                            .join(",");
                        if joined.is_empty() {
                            None
                        } else {
                            Some(joined)
                        }
                    })
                    .build(),
                options,
            )
            .await
    }

    pub async fn list_paginated(
        &self,
        request: &SubscriptionsListQueryRequest,
        options: Option<RequestOptions>,
    ) -> Result<AsyncPaginator<SubscriptionResponse>, ApiError> {
        let http_client = std::sync::Arc::new(self.http_client.clone());
        let base_query_params = QueryBuilder::new()
            .string("customer_id", request.customer_id.clone())
            .int("limit", request.limit.clone())
            .string("sort", request.sort.clone())
            .string("status", {
                let joined = request
                    .status
                    .iter()
                    .flatten()
                    .map(|value| value.to_string())
                    .collect::<Vec<_>>()
                    .join(",");
                if joined.is_empty() {
                    None
                } else {
                    Some(joined)
                }
            })
            .string("tag_ids", {
                let joined = request
                    .tag_ids
                    .iter()
                    .flatten()
                    .map(|value| value.to_string())
                    .collect::<Vec<_>>()
                    .join(",");
                if joined.is_empty() {
                    None
                } else {
                    Some(joined)
                }
            })
            .build();
        let options_clone = options.clone();

        AsyncPaginator::new(
            http_client,
            move |client, page_token| {
                let mut query_params: Vec<(String, String)> =
                    base_query_params.clone().unwrap_or_default();

                // Use page_token as offset/page number (start from 0 if None)
                let current_page = page_token.unwrap_or_else(|| "0".to_string());
                query_params.push(("offset".to_string(), current_page.clone()));
                let page_size: Option<i64> = query_params
                    .iter()
                    .find(|(name, _)| name == "limit")
                    .and_then(|(_, value)| value.parse::<i64>().ok());

                let options_for_request = options_clone.clone();

                // Clone captured variables to move into the async block

                Box::pin(async move {
                    let raw_response = client
                        .execute_request_raw::<serde_json::Value>(
                            Method::GET,
                            "subscriptions",
                            None,
                            Some(query_params),
                            options_for_request,
                        )
                        .await?;
                    let response = raw_response.body;

                    // Extract pagination info from response
                    // Generic field extraction for offset pagination
                    let items: Vec<serde_json::Value> = response
                        .get("data")
                        .and_then(|v| v.as_array())
                        .map(|arr| arr.clone())
                        .unwrap_or_default();

                    let has_next_page = match page_size {
                        Some(size) => items.len() as i64 >= size.min(100),
                        None => !items.is_empty(),
                    };
                    let next_cursor: Option<String> = if has_next_page {
                        let current_offset: i64 = current_page.parse().unwrap_or(0);
                        Some((current_offset + items.len() as i64).to_string())
                    } else {
                        None
                    };

                    let items = items
                        .into_iter()
                        .map(serde_json::from_value::<SubscriptionResponse>)
                        .collect::<Result<Vec<_>, _>>()
                        .map_err(ApiError::Serialization)?;
                    Ok(PaginationResult {
                        items,
                        next_cursor,
                        has_next_page,
                        response: Some(response),
                        status_code: raw_response.status_code,
                        headers: raw_response.headers,
                    })
                })
            },
            request.offset.map(|offset| offset.to_string()),
        )
    }

    /// Creates a new subscription for a customer. Supports three creation patterns: raw pricing in the request body, from a plan, or from a plan with per-customer overrides. Subscriptions are created in `draft` status and must be activated unless `auto_activate: true` is set. See the [Creating a Subscription](https://alguna.com/docs/api-reference/v2/examples/creating-a-subscription) examples for concrete request bodies and the bundle variants.
    ///
    /// # Arguments
    ///
    /// * `options` - Additional request options such as headers, timeout, etc.
    ///
    /// # Returns
    ///
    /// JSON response from the API
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use alguna::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let config = ClientConfig {
    ///         api_key: Some("<token>".to_string()),
    ///         ..Default::default()
    ///     };
    ///     let client = Alguna::new(config).expect("Failed to build client");
    ///     client
    ///         .subscriptions
    ///         .create(
    ///             &CreateSubscriptionRequest {
    ///                 customer_id: "cust_abc123".to_string(),
    ///                 auto_activate: None,
    ///                 billing: None,
    ///                 contract: None,
    ///                 currency: None,
    ///                 items: None,
    ///                 metadata: None,
    ///                 name: None,
    ///                 plan_id: None,
    ///                 renewal: None,
    ///             },
    ///             None,
    ///         )
    ///         .await;
    /// }
    /// ```
    pub async fn create(
        &self,
        request: &CreateSubscriptionRequest,
        options: Option<RequestOptions>,
    ) -> Result<SubscriptionResponse, ApiError> {
        self.http_client
            .execute_request(
                Method::POST,
                "subscriptions",
                Some(serde_json::to_value(request).map_err(ApiError::Serialization)?),
                None,
                options,
            )
            .await
    }

    /// Fetches a single subscription by ID, including the current active version reference and any pending future versions.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the subscription
    /// * `options` - Additional request options such as headers, timeout, etc.
    ///
    /// # Returns
    ///
    /// JSON response from the API
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use alguna::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let config = ClientConfig {
    ///         api_key: Some("<token>".to_string()),
    ///         ..Default::default()
    ///     };
    ///     let client = Alguna::new(config).expect("Failed to build client");
    ///     client.subscriptions.get(&"id".to_string(), None).await;
    /// }
    /// ```
    pub async fn get(
        &self,
        id: &str,
        options: Option<RequestOptions>,
    ) -> Result<SubscriptionResponse, ApiError> {
        self.http_client
            .execute_request(
                Method::GET,
                &format!("subscriptions/{}", id),
                None,
                None,
                options,
            )
            .await
    }

    /// Permanently deletes a draft subscription. Only draft subscriptions can be deleted. Use cancel for subscriptions that have already been activated.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the subscription
    /// * `options` - Additional request options such as headers, timeout, etc.
    ///
    /// # Returns
    ///
    /// Empty response
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use alguna::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let config = ClientConfig {
    ///         api_key: Some("<token>".to_string()),
    ///         ..Default::default()
    ///     };
    ///     let client = Alguna::new(config).expect("Failed to build client");
    ///     client.subscriptions.delete(&"id".to_string(), None).await;
    /// }
    /// ```
    pub async fn delete(&self, id: &str, options: Option<RequestOptions>) -> Result<(), ApiError> {
        self.http_client
            .execute_request(
                Method::DELETE,
                &format!("subscriptions/{}", id),
                None,
                None,
                options,
            )
            .await
    }

    /// Patches metadata on a subscription: name, description, trial period, billing flags, subscription-level discount, spending thresholds, price escalation, and tags. This endpoint does not modify the priced item set. To change items, see the [Updating a Subscription](https://alguna.com/docs/api-reference/v2/examples/updating-a-subscription) examples.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the subscription
    /// * `options` - Additional request options such as headers, timeout, etc.
    ///
    /// # Returns
    ///
    /// JSON response from the API
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use alguna::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let config = ClientConfig {
    ///         api_key: Some("<token>".to_string()),
    ///         ..Default::default()
    ///     };
    ///     let client = Alguna::new(config).expect("Failed to build client");
    ///     client
    ///         .subscriptions
    ///         .update(
    ///             &"id".to_string(),
    ///             &UpdateSubscriptionRequest {
    ///                 ..Default::default()
    ///             },
    ///             None,
    ///         )
    ///         .await;
    /// }
    /// ```
    pub async fn update(
        &self,
        id: &str,
        request: &UpdateSubscriptionRequest,
        options: Option<RequestOptions>,
    ) -> Result<SubscriptionResponse, ApiError> {
        self.http_client
            .execute_request(
                Method::PATCH,
                &format!("subscriptions/{}", id),
                Some(serde_json::to_value(request).map_err(ApiError::Serialization)?),
                None,
                options,
            )
            .await
    }

    /// Transitions a draft subscription to `active` so it becomes effective for the customer. Idempotent: activating an already-active subscription returns the current state. See the [Creating a Subscription](https://alguna.com/docs/api-reference/v2/examples/creating-a-subscription) examples for the full creation flow.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the subscription
    /// * `options` - Additional request options such as headers, timeout, etc.
    ///
    /// # Returns
    ///
    /// JSON response from the API
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use alguna::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let config = ClientConfig {
    ///         api_key: Some("<token>".to_string()),
    ///         ..Default::default()
    ///     };
    ///     let client = Alguna::new(config).expect("Failed to build client");
    ///     client.subscriptions.activate(&"id".to_string(), None).await;
    /// }
    /// ```
    pub async fn activate(
        &self,
        id: &str,
        options: Option<RequestOptions>,
    ) -> Result<SubscriptionResponse, ApiError> {
        self.http_client
            .execute_request(
                Method::POST,
                &format!("subscriptions/{}/activate", id),
                None,
                None,
                options,
            )
            .await
    }

    /// Returns the current billing cycle range, the list of valid dates for on-cycle version starts, the valid date range for mid-cycle changes, the contract end date, and the next renewal date. Use this to drive date pickers in UI flows that schedule future changes.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the subscription
    /// * `options` - Additional request options such as headers, timeout, etc.
    ///
    /// # Returns
    ///
    /// JSON response from the API
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use alguna::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let config = ClientConfig {
    ///         api_key: Some("<token>".to_string()),
    ///         ..Default::default()
    ///     };
    ///     let client = Alguna::new(config).expect("Failed to build client");
    ///     client
    ///         .subscriptions
    ///         .get_billing_dates(&"id".to_string(), None)
    ///         .await;
    /// }
    /// ```
    pub async fn get_billing_dates(
        &self,
        id: &str,
        options: Option<RequestOptions>,
    ) -> Result<BillingDatesResponse, ApiError> {
        self.http_client
            .execute_request(
                Method::GET,
                &format!("subscriptions/{}/billing-dates", id),
                None,
                None,
                options,
            )
            .await
    }

    /// Schedules a cancellation for a subscription. The `effective` timing can be a keyword (e.g. `immediate`, `end_of_term`) or a specific date. A cancellation reason code is required and a free-text note is optional.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the subscription
    /// * `options` - Additional request options such as headers, timeout, etc.
    ///
    /// # Returns
    ///
    /// JSON response from the API
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use alguna::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let config = ClientConfig {
    ///         api_key: Some("<token>".to_string()),
    ///         ..Default::default()
    ///     };
    ///     let client = Alguna::new(config).expect("Failed to build client");
    ///     client
    ///         .subscriptions
    ///         .cancel(
    ///             &"id".to_string(),
    ///             &CancelSubscriptionRequest {
    ///                 reason: SubscriptionCancelationReason::NoLongerRequired,
    ///                 effective: None,
    ///                 reason_description: None,
    ///             },
    ///             None,
    ///         )
    ///         .await;
    /// }
    /// ```
    pub async fn cancel(
        &self,
        id: &str,
        request: &CancelSubscriptionRequest,
        options: Option<RequestOptions>,
    ) -> Result<SubscriptionResponse, ApiError> {
        self.http_client
            .execute_request(
                Method::POST,
                &format!("subscriptions/{}/cancel", id),
                Some(serde_json::to_value(request).map_err(ApiError::Serialization)?),
                None,
                options,
            )
            .await
    }

    /// Returns the customer's monetary credit balance applicable to this subscription, evaluated at the `as_of` timestamp (defaults to now). Expired grants are excluded from the returned balance.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the subscription
    /// * `as_of` - Point in time to evaluate the balance at (RFC3339). Defaults to now.
    /// * `options` - Additional request options such as headers, timeout, etc.
    ///
    /// # Returns
    ///
    /// JSON response from the API
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use alguna::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let config = ClientConfig {
    ///         api_key: Some("<token>".to_string()),
    ///         ..Default::default()
    ///     };
    ///     let client = Alguna::new(config).expect("Failed to build client");
    ///     client
    ///         .subscriptions
    ///         .get_credit_balance(
    ///             &"id".to_string(),
    ///             &GetCreditBalanceQueryRequest {
    ///                 as_of: Some(DateTime::parse_from_rfc3339("2026-04-01T00:00:00Z").unwrap()),
    ///                 ..Default::default()
    ///             },
    ///             None,
    ///         )
    ///         .await;
    /// }
    /// ```
    pub async fn get_credit_balance(
        &self,
        id: &str,
        request: &GetCreditBalanceQueryRequest,
        options: Option<RequestOptions>,
    ) -> Result<SubscriptionCreditBalanceResponse, ApiError> {
        self.http_client
            .execute_request(
                Method::GET,
                &format!("subscriptions/{}/credits/balance", id),
                None,
                QueryBuilder::new()
                    .datetime("as_of", request.as_of.clone())
                    .build(),
                options,
            )
            .await
    }

    /// Creates a monetary API-granted credit on a subscription. The grant is immediately available for consumption.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the subscription
    /// * `options` - Additional request options such as headers, timeout, etc.
    ///
    /// # Returns
    ///
    /// JSON response from the API
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use alguna::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let config = ClientConfig {
    ///         api_key: Some("<token>".to_string()),
    ///         ..Default::default()
    ///     };
    ///     let client = Alguna::new(config).expect("Failed to build client");
    ///     client
    ///         .subscriptions
    ///         .create_credit_grant(
    ///             &"id".to_string(),
    ///             &CreditGrantRequest {
    ///                 amount: "100.00".to_string(),
    ///                 reason: "API promotional credit".to_string(),
    ///                 credit_type: None,
    ///                 expires_at: None,
    ///             },
    ///             None,
    ///         )
    ///         .await;
    /// }
    /// ```
    pub async fn create_credit_grant(
        &self,
        id: &str,
        request: &CreditGrantRequest,
        options: Option<RequestOptions>,
    ) -> Result<CreditGrantResponse, ApiError> {
        self.http_client
            .execute_request(
                Method::POST,
                &format!("subscriptions/{}/credits/grant", id),
                Some(serde_json::to_value(request).map_err(ApiError::Serialization)?),
                None,
                options,
            )
            .await
    }

    /// Returns every entitlement active on the subscription's current published version, including static boolean/number/string entitlements and grant-based credit allocations.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the subscription
    /// * `options` - Additional request options such as headers, timeout, etc.
    ///
    /// # Returns
    ///
    /// JSON response from the API
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use alguna::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let config = ClientConfig {
    ///         api_key: Some("<token>".to_string()),
    ///         ..Default::default()
    ///     };
    ///     let client = Alguna::new(config).expect("Failed to build client");
    ///     client
    ///         .subscriptions
    ///         .list_entitlements(&"id".to_string(), None)
    ///         .await;
    /// }
    /// ```
    pub async fn list_entitlements(
        &self,
        id: &str,
        options: Option<RequestOptions>,
    ) -> Result<EntitlementListResponse, ApiError> {
        self.http_client
            .execute_request(
                Method::GET,
                &format!("subscriptions/{}/entitlements", id),
                None,
                None,
                options,
            )
            .await
    }

    /// Fetches a single active entitlement on a subscription by its entitlement key.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the subscription
    /// * `key` - Unique identifier for the entitlement
    /// * `options` - Additional request options such as headers, timeout, etc.
    ///
    /// # Returns
    ///
    /// JSON response from the API
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use alguna::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let config = ClientConfig {
    ///         api_key: Some("<token>".to_string()),
    ///         ..Default::default()
    ///     };
    ///     let client = Alguna::new(config).expect("Failed to build client");
    ///     client
    ///         .subscriptions
    ///         .get_entitlement(&"id".to_string(), &"key".to_string(), None)
    ///         .await;
    /// }
    /// ```
    pub async fn get_entitlement(
        &self,
        id: &str,
        key: &str,
        options: Option<RequestOptions>,
    ) -> Result<EntitlementResponse, ApiError> {
        self.http_client
            .execute_request(
                Method::GET,
                &format!("subscriptions/{}/entitlements/{}", id, key),
                None,
                None,
                options,
            )
            .await
    }

    /// Returns the signed contract PDF for a subscription as a binary `application/pdf` response. The document reflects the contract as it was agreed upon with the customer at the point of signing. Returns `404` if the order form was not signed through Alguna and no PDF exists.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the subscription
    /// * `options` - Additional request options such as headers, timeout, etc.
    ///
    /// # Returns
    ///
    /// Streaming file download (use .into_bytes() to collect or stream chunks)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use alguna::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let config = ClientConfig {
    ///         api_key: Some("<token>".to_string()),
    ///         ..Default::default()
    ///     };
    ///     let client = Alguna::new(config).expect("Failed to build client");
    ///     client
    ///         .subscriptions
    ///         .download_pdf(&"id".to_string(), None)
    ///         .await;
    /// }
    /// ```
    pub async fn download_pdf(
        &self,
        id: &str,
        options: Option<RequestOptions>,
    ) -> Result<ByteStream, ApiError> {
        self.http_client
            .execute_stream_request(
                Method::GET,
                &format!("subscriptions/{}/pdf", id),
                None,
                None,
                options,
            )
            .await
    }

    /// Returns the monthly recurring revenue (MRR), annual recurring revenue (ARR), and annual contract value (ACV) for the subscription's current active version.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the subscription
    /// * `options` - Additional request options such as headers, timeout, etc.
    ///
    /// # Returns
    ///
    /// JSON response from the API
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use alguna::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let config = ClientConfig {
    ///         api_key: Some("<token>".to_string()),
    ///         ..Default::default()
    ///     };
    ///     let client = Alguna::new(config).expect("Failed to build client");
    ///     client
    ///         .subscriptions
    ///         .get_revenue(&"id".to_string(), None)
    ///         .await;
    /// }
    /// ```
    pub async fn get_revenue(
        &self,
        id: &str,
        options: Option<RequestOptions>,
    ) -> Result<SubscriptionRevenueResponse, ApiError> {
        self.http_client
            .execute_request(
                Method::GET,
                &format!("subscriptions/{}/revenue", id),
                None,
                None,
                options,
            )
            .await
    }
}