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
use crate::api::*;
use crate::{ApiError, ClientConfig, HttpClient, QueryBuilder, RequestOptions};
use crate::{AsyncPaginator, PaginationResult};
use reqwest::Method;
pub struct CustomersClient {
pub http_client: HttpClient,
}
impl CustomersClient {
pub fn new(config: ClientConfig) -> Result<Self, ApiError> {
Ok(Self {
http_client: HttpClient::new(config.clone())?,
})
}
/// Returns a paginated list of customers. Supports filtering by sales owner, customer success manager, tag IDs, active-subscription status, integration IDs, alias, and contact email.
///
/// # Arguments
///
/// * `alias` - Filter by customer alias (external ID)
/// * `csm_id` - Filter by customer success manager user ID (comma-separated to match any)
/// * `email` - Filter by contact email address
/// * `has_active_subscriptions` - Filter by whether the customer has active subscriptions
/// * `integration_ids` - Filter by external integration IDs (comma-separated to match any)
/// * `limit` - Number of items to return per page
/// * `offset` - Number of items to skip
/// * `sales_owner_id` - Filter by sales owner user ID (comma-separated to match any)
/// * `sort` - Sort field and direction in format field:order. Sortable fields: name, created_at
/// * `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
/// .customers
/// .list(
/// &CustomersListQueryRequest {
/// alias: Some("ext_customer_1".to_string()),
/// email: Some("john@example.com".to_string()),
/// limit: Some(20),
/// offset: Some(0),
/// sort: Some("created_at:desc".to_string()),
/// csm_id: vec![],
/// has_active_subscriptions: None,
/// integration_ids: vec![],
/// sales_owner_id: vec![],
/// tag_ids: vec![],
/// },
/// None,
/// )
/// .await;
/// }
/// ```
pub async fn list(
&self,
request: &CustomersListQueryRequest,
options: Option<RequestOptions>,
) -> Result<CustomerListResponse, ApiError> {
self.http_client
.execute_request(
Method::GET,
"customers",
None,
QueryBuilder::new()
.string("alias", request.alias.clone())
.string("csm_id", {
let joined = request
.csm_id
.iter()
.flatten()
.map(|value| value.to_string())
.collect::<Vec<_>>()
.join(",");
if joined.is_empty() {
None
} else {
Some(joined)
}
})
.string("email", request.email.clone())
.bool(
"has_active_subscriptions",
request.has_active_subscriptions.clone(),
)
.string("integration_ids", {
let joined = request
.integration_ids
.iter()
.flatten()
.map(|value| value.to_string())
.collect::<Vec<_>>()
.join(",");
if joined.is_empty() {
None
} else {
Some(joined)
}
})
.int("limit", request.limit.clone())
.int("offset", request.offset.clone())
.string("sales_owner_id", {
let joined = request
.sales_owner_id
.iter()
.flatten()
.map(|value| value.to_string())
.collect::<Vec<_>>()
.join(",");
if joined.is_empty() {
None
} else {
Some(joined)
}
})
.string("sort", request.sort.clone())
.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: &CustomersListQueryRequest,
options: Option<RequestOptions>,
) -> Result<AsyncPaginator<CustomerResponse>, ApiError> {
let http_client = std::sync::Arc::new(self.http_client.clone());
let base_query_params = QueryBuilder::new()
.string("alias", request.alias.clone())
.string("csm_id", {
let joined = request
.csm_id
.iter()
.flatten()
.map(|value| value.to_string())
.collect::<Vec<_>>()
.join(",");
if joined.is_empty() {
None
} else {
Some(joined)
}
})
.string("email", request.email.clone())
.bool(
"has_active_subscriptions",
request.has_active_subscriptions.clone(),
)
.string("integration_ids", {
let joined = request
.integration_ids
.iter()
.flatten()
.map(|value| value.to_string())
.collect::<Vec<_>>()
.join(",");
if joined.is_empty() {
None
} else {
Some(joined)
}
})
.int("limit", request.limit.clone())
.string("sales_owner_id", {
let joined = request
.sales_owner_id
.iter()
.flatten()
.map(|value| value.to_string())
.collect::<Vec<_>>()
.join(",");
if joined.is_empty() {
None
} else {
Some(joined)
}
})
.string("sort", request.sort.clone())
.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,
"customers",
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::<CustomerResponse>)
.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 customer with optional contacts, billing address, aliases, and a required default currency.
///
/// # 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
/// .customers
/// .create(
/// &CreateCustomerRequest {
/// currency: "USD".to_string(),
/// name: "Acme Corp".to_string(),
/// aliases: None,
/// billing_address: None,
/// contacts: None,
/// },
/// None,
/// )
/// .await;
/// }
/// ```
pub async fn create(
&self,
request: &CreateCustomerRequest,
options: Option<RequestOptions>,
) -> Result<CustomerResponse, ApiError> {
self.http_client
.execute_request(
Method::POST,
"customers",
Some(serde_json::to_value(request).map_err(ApiError::Serialization)?),
None,
options,
)
.await
}
/// Resolves an alias to its Alguna customer ID. The `alias` accepts the Alguna account ID, a customer alias, or a connected-account external ID (such as a Stripe customer ID). Returns 404 if no customer in your organization matches. Use this when you hold an external identifier and only need the Alguna ID; to fetch the full customer, use Get a customer instead.
///
/// # Arguments
///
/// * `alias` - Customer alias to resolve — an Alguna account ID, a customer alias, or a connected-account external ID (such as a Stripe customer ID)
/// * `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
/// .customers
/// .lookup(
/// &LookupQueryRequest {
/// alias: "cus_abc123".to_string(),
/// },
/// None,
/// )
/// .await;
/// }
/// ```
pub async fn lookup(
&self,
request: &LookupQueryRequest,
options: Option<RequestOptions>,
) -> Result<CustomerLookupResponse, ApiError> {
self.http_client
.execute_request(
Method::GET,
"customers/lookup",
None,
QueryBuilder::new()
.string("alias", request.alias.clone())
.build(),
options,
)
.await
}
/// Fetches a single customer by ID, including contacts, billing address, and tax details (rate, status, country, type, and taxability reason). The `id` path parameter accepts the Alguna account ID, a customer alias, or a connected-account external ID (such as a Stripe customer ID).
///
/// # Arguments
///
/// * `id` - Unique identifier for the customer
/// * `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.customers.get(&"id".to_string(), None).await;
/// }
/// ```
pub async fn get(
&self,
id: &str,
options: Option<RequestOptions>,
) -> Result<CustomerResponse, ApiError> {
self.http_client
.execute_request(
Method::GET,
&format!("customers/{}", id),
None,
None,
options,
)
.await
}
/// Patches an existing customer. Only the fields provided in the request body are modified. Supplying contacts or aliases replaces the full list. The `id` path parameter accepts the Alguna account ID, a customer alias, or a connected-account external ID (such as a Stripe customer ID).
///
/// # Arguments
///
/// * `id` - Unique identifier for the customer
/// * `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
/// .customers
/// .update(
/// &"id".to_string(),
/// &UpdateCustomerRequest {
/// ..Default::default()
/// },
/// None,
/// )
/// .await;
/// }
/// ```
pub async fn update(
&self,
id: &str,
request: &UpdateCustomerRequest,
options: Option<RequestOptions>,
) -> Result<CustomerResponse, ApiError> {
self.http_client
.execute_request(
Method::PATCH,
&format!("customers/{}", id),
Some(serde_json::to_value(request).map_err(ApiError::Serialization)?),
None,
options,
)
.await
}
/// Returns the customer's accounts in connected external systems (for example a Stripe customer or a HubSpot company), including the integration each link belongs to, the account's identifier in the external system, and a link to it where available. The `id` path parameter accepts the Alguna account ID, a customer alias, or a connected-account external ID (such as a Stripe customer ID).
///
/// # Arguments
///
/// * `id` - Unique identifier for the customer
/// * `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
/// .customers
/// .list_connected_accounts(&"id".to_string(), None)
/// .await;
/// }
/// ```
pub async fn list_connected_accounts(
&self,
id: &str,
options: Option<RequestOptions>,
) -> Result<ConnectedAccountListResponse, ApiError> {
self.http_client
.execute_request(
Method::GET,
&format!("customers/{}/connected-accounts", id),
None,
None,
options,
)
.await
}
/// Links the customer to an account in an external system by recording the integration and the account's identifier in that system. This records the mapping only: it does not create anything in the external system and does not trigger a sync of any data in either direction. The `id` path parameter accepts the Alguna account ID, a customer alias, or an existing connected-account external ID.
///
/// # Arguments
///
/// * `id` - Unique identifier for the customer
/// * `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
/// .customers
/// .create_connected_account(
/// &"id".to_string(),
/// &ConnectedAccountCreateRequest {
/// external_id: "cus_abc123".to_string(),
/// integration_id: "intg_abc123".to_string(),
/// },
/// None,
/// )
/// .await;
/// }
/// ```
pub async fn create_connected_account(
&self,
id: &str,
request: &ConnectedAccountCreateRequest,
options: Option<RequestOptions>,
) -> Result<ConnectedAccountResponse, ApiError> {
self.http_client
.execute_request(
Method::POST,
&format!("customers/{}/connected-accounts", id),
Some(serde_json::to_value(request).map_err(ApiError::Serialization)?),
None,
options,
)
.await
}
/// Removes the link between the customer and an external-system account. This removes the mapping only: it does not delete anything in the external system and does not trigger a sync. The `id` path parameter accepts the Alguna account ID, a customer alias, or an existing connected-account external ID.
///
/// # Arguments
///
/// * `id` - Unique identifier for the customer
/// * `connected_account_id` - Unique identifier for the connected-account
/// * `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
/// .customers
/// .delete_connected_account(&"id".to_string(), &"connectedAccountId".to_string(), None)
/// .await;
/// }
/// ```
pub async fn delete_connected_account(
&self,
id: &str,
connected_account_id: &str,
options: Option<RequestOptions>,
) -> Result<(), ApiError> {
self.http_client
.execute_request(
Method::DELETE,
&format!(
"customers/{}/connected-accounts/{}",
id, connected_account_id
),
None,
None,
options,
)
.await
}
/// Returns the flattened list of active entitlements across all of the customer's active subscriptions. Each entry is a single entitlement on the current published version of one active subscription. Use the `subscription_id` field on each entry to see which subscription the entitlement comes from. The `id` path parameter accepts the Alguna account ID, a customer alias, or a connected-account external ID (such as a Stripe customer ID).
///
/// # Arguments
///
/// * `id` - Unique identifier for the customer
/// * `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
/// .customers
/// .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!("customers/{}/entitlements", id),
None,
None,
options,
)
.await
}
}