babelforce-manager-sdk 0.42.2

Rust SDK for the babelforce manager APIs — auth, user & agent management, call reporting, metrics, and task automations.
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
use std::sync::Arc;

use crate::error::{map_manager_err, ManagerError};
use crate::gen::manager::apis::configuration::Configuration;
use crate::gen::manager::apis::{call_api, manager_api, queue_api, reporting_call_api};
use crate::gen::manager::models;
use crate::http::{collect_all, fetch_page, Page};
use crate::resources::raw::{get_json, page_parts, post_json};
use crate::retry::{with_retry, RetryPolicy};

/// Filters for the detailed call report (`/api/v2/calls/reporting`). String-typed on purpose —
/// values are validated against the API's enums on use, so a bad value is an
/// [`ManagerError::InvalidArgument`] naming the field, never a silent mismatch.
#[derive(Debug, Clone, Default)]
pub struct CallReportFilter {
    /// Caller number (E.164 or fragment).
    pub from_number: Option<String>,
    /// Dialed number.
    pub to_number: Option<String>,
    /// Unix seconds, inclusive lower bound.
    pub time_start: Option<i32>,
    /// Unix seconds, exclusive upper bound.
    pub time_end: Option<i32>,
    /// Only calls handled by this agent (UUID).
    pub agent_id: Option<String>,
    /// Call state, e.g. `completed` | `no-answer` | `busy`.
    pub state: Option<String>,
    /// Call type, e.g. `inbound` | `outbound`.
    pub r#type: Option<String>,
    /// Why the call ended.
    pub finish_reason: Option<String>,
    /// Free-text search.
    pub q: Option<String>,
}

/// Parse a string into a serde-renamed API enum (e.g. `"completed"` → `CallState::Completed`),
/// mapping failure to an [`ManagerError::InvalidArgument`] naming the field.
fn parse_enum<T: serde::de::DeserializeOwned>(field: &str, value: &str) -> Result<T, ManagerError> {
    serde_json::from_value(serde_json::Value::String(value.to_string()))
        .map_err(|_| ManagerError::InvalidArgument(format!("{field}: unknown value '{value}'")))
}

impl CallReportFilter {
    #[allow(clippy::type_complexity)]
    fn to_params(
        &self,
    ) -> Result<
        (
            Option<models::ListReportingCallsTypeParameter>,
            Option<models::ListReportingCallsToParameter>,
            Option<models::ListReportingCallsIdParameter>,
            Option<models::ListReportingCallsStateParameter>,
            Option<models::ListReportingCallsFinishReasonParameter>,
        ),
        ManagerError,
    > {
        let r#type = self
            .r#type
            .as_deref()
            .map(|v| parse_enum::<models::CallType>("type", v))
            .transpose()?
            .map(models::ListReportingCallsTypeParameter::CallType);
        let to_number = self
            .to_number
            .clone()
            .map(models::ListReportingCallsToParameter::ReportingNumberFilter);
        let agent_id = self
            .agent_id
            .as_deref()
            .map(|v| {
                uuid::Uuid::parse_str(v)
                    .map_err(|e| ManagerError::InvalidArgument(format!("agent_id: {e}")))
            })
            .transpose()?
            .map(models::ListReportingCallsIdParameter::ObjectUuid);
        let state = self
            .state
            .as_deref()
            .map(|v| parse_enum::<models::CallState>("state", v))
            .transpose()?
            .map(models::ListReportingCallsStateParameter::CallState);
        let finish_reason = self
            .finish_reason
            .as_deref()
            .map(|v| parse_enum::<models::CallFinishReason>("finish_reason", v))
            .transpose()?
            .map(models::ListReportingCallsFinishReasonParameter::CallFinishReason);
        Ok((r#type, to_number, agent_id, state, finish_reason))
    }
}

/// Call reporting and call control — `/api/v2/calls`, with a nested `reporting` sub-resource.
pub struct CallsResource {
    pub(crate) cfg: Arc<Configuration>,
    pub(crate) retry: RetryPolicy,
    /// Call reporting — `/api/v2/calls/reporting`.
    pub reporting: ReportingResource,
}

impl CallsResource {
    /// Get a single call by id as **raw JSON** (the full item-response envelope). The typed
    /// [`Self::get`] can fail on real payloads — the generated models are stricter than the live
    /// API (e.g. `bridged.queueId` is a required UUID in the model but null for agent-bridged calls).
    pub async fn get_raw(&self, id: &str) -> Result<serde_json::Value, ManagerError> {
        let path = format!("/api/v2/calls/{}", crate::gen::manager::apis::urlencode(id));
        with_retry(&self.retry, true, || get_json(self.cfg.as_ref(), &path)).await
    }

    /// Get a single call by id.
    pub async fn get(&self, id: &str) -> Result<models::CallItemResponse, ManagerError> {
        with_retry(&self.retry, true, || {
            call_api::get_call(self.cfg.as_ref(), id)
        })
        .await
        .map_err(map_manager_err)
    }

    /// Hang up a live call; returns the updated call.
    pub async fn hangup(&self, id: &str) -> Result<models::CallItemResponse, ManagerError> {
        with_retry(&self.retry, false, || {
            manager_api::hangup_call(self.cfg.as_ref(), id)
        })
        .await
        .map_err(map_manager_err)
    }

    /// Hang up a live call; returns the updated call as **raw JSON**. The typed [`Self::hangup`]
    /// decodes `CallItemResponse`, which breaks on live agent-bridged calls (`bridged.queueId` is
    /// a required UUID in the model but null in production) — and a just-hung-up bridged call is
    /// the common case for this endpoint.
    pub async fn hangup_raw(&self, id: &str) -> Result<serde_json::Value, ManagerError> {
        let path = format!(
            "/api/v2/calls/{}/hangup",
            crate::gen::manager::apis::urlencode(id)
        );
        // Non-idempotent action → no retry on ambiguous failures.
        with_retry(&self.retry, false, || post_json(self.cfg.as_ref(), &path)).await
    }

    /// Create an inbound test call.
    pub async fn create_test_call(
        &self,
        body: models::CreateTestCallRequest,
    ) -> Result<models::CallItemResponse, ManagerError> {
        with_retry(&self.retry, false, || {
            call_api::create_inbound_test_call(self.cfg.as_ref(), body.clone())
        })
        .await
        .map_err(map_manager_err)
    }

    /// Set session variables on a call.
    pub async fn set_session_variables(
        &self,
        id: &str,
        variables: models::SetCallSessionVariablesRequest,
    ) -> Result<models::SetCallSessionVariablesResponse, ManagerError> {
        with_retry(&self.retry, false, || {
            manager_api::set_call_session_variables(self.cfg.as_ref(), id, Some(variables.clone()))
        })
        .await
        .map_err(map_manager_err)
    }

    /// Cancel a queued or scheduled call; returns the updated call.
    pub async fn cancel(&self, id: &str) -> Result<models::CallItemResponse, ManagerError> {
        with_retry(&self.retry, false, || {
            manager_api::cancel_call(self.cfg.as_ref(), id)
        })
        .await
        .map_err(map_manager_err)
    }

    /// List the calls waiting in a queue, collecting every call across pages.
    pub async fn list_queued(
        &self,
        queue_id: &str,
    ) -> Result<Vec<models::QueuedCall>, ManagerError> {
        collect_all(&self.retry, map_manager_err, |page| async move {
            let r =
                queue_api::list_queued_calls(self.cfg.as_ref(), queue_id, Some(page), None).await?;
            let (pages, current) = r
                .pagination
                .as_ref()
                .map(|p| (p.pages, p.current))
                .unwrap_or((1, 1));
            Ok((r.items, pages, current))
        })
        .await
    }

    /// Request a callback for a caller waiting in a queue.
    pub async fn queue_callback(
        &self,
        queue_id: &str,
        body: models::QueueCallbackRequest,
    ) -> Result<models::QueueCallbackResponse, ManagerError> {
        with_retry(&self.retry, false, || {
            queue_api::queue_callback(self.cfg.as_ref(), queue_id, body.clone())
        })
        .await
        .map_err(map_manager_err)
    }
}

/// Call reporting — `/api/v2/calls/reporting`.
pub struct ReportingResource {
    pub(crate) cfg: Arc<Configuration>,
    pub(crate) retry: RetryPolicy,
}

impl ReportingResource {
    /// The detailed call report, collecting every call across pages.
    pub async fn list_all(&self) -> Result<Vec<models::Call>, ManagerError> {
        collect_all(&self.retry, map_manager_err, |page| async move {
            let r = call_api::list_reporting_calls(
                self.cfg.as_ref(),
                Some(page),
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .await?;
            Ok((r.items, r.pagination.pages, r.pagination.current))
        })
        .await
    }

    /// One page of the detailed call report as **raw JSON rows** (no typed decode), narrowed by
    /// [`CallReportFilter`] (still validated: bad enum values are `InvalidArgument` before any
    /// request). The generated `Call` model is stricter than the live API — e.g.
    /// `bridged.queueId`/`queueName` are required in the model but null whenever a call bridged
    /// to an **agent** rather than a queue — so the typed [`Self::list_page`] fails to decode
    /// real production pages. Consumers that only re-serialize rows read raw and lose nothing.
    pub async fn list_page_raw(
        &self,
        page: i32,
        per_page: Option<i32>,
        filter: &CallReportFilter,
    ) -> Result<Page<serde_json::Value>, ManagerError> {
        // Validate + convert exactly like the typed path, then mirror the generated client's wire
        // format: plain values for strings/ints, JSON-encoded values for the oneOf enum params.
        let (r#type, to_number, agent_id, state, finish_reason) = filter.to_params()?;
        use crate::gen::manager::apis::urlencode as enc;
        let mut q = vec![format!("page={page}")];
        if let Some(max) = per_page {
            q.push(format!("max={max}"));
        }
        if let Some(v) = &filter.from_number {
            q.push(format!("fromNumber={}", enc(v)));
        }
        if let Some(v) = filter.time_start {
            q.push(format!("time.start={v}"));
        }
        if let Some(v) = filter.time_end {
            q.push(format!("time.end={v}"));
        }
        if let Some(v) = &filter.q {
            q.push(format!("q={}", enc(v)));
        }
        if let Some(v) = &to_number {
            let s = serde_json::to_string(v).unwrap_or_default();
            q.push(format!("toNumber={}", enc(&s)));
        }
        if let Some(v) = &agent_id {
            let s = serde_json::to_string(v).unwrap_or_default();
            q.push(format!("agentId={}", enc(&s)));
        }
        if let Some(v) = &state {
            let s = serde_json::to_string(v).unwrap_or_default();
            q.push(format!("state={}", enc(&s)));
        }
        if let Some(v) = &r#type {
            let s = serde_json::to_string(v).unwrap_or_default();
            q.push(format!("type={}", enc(&s)));
        }
        if let Some(v) = &finish_reason {
            let s = serde_json::to_string(v).unwrap_or_default();
            q.push(format!("finishReason={}", enc(&s)));
        }
        let path = format!("/api/v2/calls/reporting?{}", q.join("&"));
        fetch_page(
            &self.retry,
            |e| e,
            || async {
                let v = get_json(self.cfg.as_ref(), &path).await?;
                Ok(page_parts(v, page))
            },
        )
        .await
    }

    /// One page of the simple (timing-metrics) call report as **raw JSON rows** — same
    /// stricter-than-reality rationale as [`Self::list_page_raw`].
    pub async fn simple_page_raw(
        &self,
        page: i32,
        per_page: Option<i32>,
    ) -> Result<Page<serde_json::Value>, ManagerError> {
        let mut q = vec![format!("page={page}")];
        if let Some(max) = per_page {
            q.push(format!("max={max}"));
        }
        let path = format!("/api/v2/calls/reporting/simple?{}", q.join("&"));
        fetch_page(
            &self.retry,
            |e| e,
            || async {
                let v = get_json(self.cfg.as_ref(), &path).await?;
                Ok(page_parts(v, page))
            },
        )
        .await
    }

    /// One page of the detailed call report, narrowed by [`CallReportFilter`].
    pub async fn list_page(
        &self,
        page: i32,
        per_page: Option<i32>,
        filter: &CallReportFilter,
    ) -> Result<Page<models::Call>, ManagerError> {
        let (r#type, to_number, agent_id, state, finish_reason) = filter.to_params()?;
        fetch_page(&self.retry, map_manager_err, || {
            let (r#type, to_number, agent_id, state, finish_reason) = (
                r#type.clone(),
                to_number.clone(),
                agent_id.clone(),
                state.clone(),
                finish_reason.clone(),
            );
            async move {
                let r = call_api::list_reporting_calls(
                    self.cfg.as_ref(),
                    Some(page),
                    per_page,
                    None,
                    None,
                    None,
                    None,
                    r#type,
                    None,
                    filter.from_number.as_deref(),
                    None,
                    to_number,
                    filter.time_start,
                    filter.time_end,
                    agent_id,
                    filter.q.as_deref(),
                    state,
                    None,
                    None,
                    finish_reason,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                )
                .await?;
                Ok((
                    r.items,
                    r.pagination.pages,
                    r.pagination.current,
                    Some(r.pagination.total),
                ))
            }
        })
        .await
    }

    /// One page of the simple (timing-metrics) call report.
    pub async fn simple_page(
        &self,
        page: i32,
        per_page: Option<i32>,
    ) -> Result<Page<models::ReportingCall>, ManagerError> {
        fetch_page(&self.retry, map_manager_err, || async move {
            let r = reporting_call_api::list_all_simple_reporting_calls(
                self.cfg.as_ref(),
                Some(page),
                per_page,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .await?;
            Ok((
                r.items,
                r.pagination.pages,
                r.pagination.current,
                Some(r.pagination.total),
            ))
        })
        .await
    }

    /// The simple call report across all report types, collecting every call across pages.
    pub async fn simple_all(&self) -> Result<Vec<models::ReportingCall>, ManagerError> {
        collect_all(&self.retry, map_manager_err, |page| async move {
            let r = reporting_call_api::list_all_simple_reporting_calls(
                self.cfg.as_ref(),
                Some(page),
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .await?;
            Ok((r.items, r.pagination.pages, r.pagination.current))
        })
        .await
    }

    /// The simple inbound call report, collecting every call across pages.
    pub async fn inbound_simple_all(&self) -> Result<Vec<models::ReportingCall>, ManagerError> {
        collect_all(&self.retry, map_manager_err, |page| async move {
            let r = reporting_call_api::list_inbound_simple_reporting_calls(
                self.cfg.as_ref(),
                Some(page),
                None,
            )
            .await?;
            Ok((r.items, r.pagination.pages, r.pagination.current))
        })
        .await
    }
}