makegov-tango 0.3.1

Official Rust SDK for the Tango federal-contracting data 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
//! Entity sub-resources: contracts, IDVs, OTAs, OTIDVs, subawards, LCATs,
//! metrics.
//!
//! Endpoints under `/api/entities/{uei}/…/` that share a common parameter
//! shape. The Go SDK splits these into `EntitySubresourceOptions`,
//! `EntitySubawardsOptions`, and `EntityLcatsOptions`; the Rust port
//! consolidates these behind a single [`EntitySubresourceOptions`] since the
//! surface SDK params for these endpoints are identical (pagination + shape +
//! ordering + search + joiner). Subaward callers should pass `ordering`
//! through verbatim — the server enforces its own allowlist.

use crate::client::Client;
use crate::error::{Error, Result};
use crate::internal::{apply_pagination, push_opt};
use crate::pagination::{FetchFn, Page, PageStream};
use crate::resources::agencies::urlencoding;
use crate::Record;
use bon::Builder;
use std::collections::BTreeMap;
use std::sync::Arc;

/// Options for [`Client::get_entity_budget_flows`].
#[derive(Debug, Clone, Default, Builder, PartialEq, Eq)]
#[non_exhaustive]
pub struct EntityBudgetFlowsOptions {
    /// 1-based page number.
    #[builder(into)]
    pub page: Option<u32>,
    /// Page size (default 25, server caps at 100).
    #[builder(into)]
    pub limit: Option<u32>,
    /// Restrict to one fiscal year (e.g. `2024`).
    pub fiscal_year: Option<u32>,
}

impl EntityBudgetFlowsOptions {
    fn to_query(&self) -> Vec<(String, String)> {
        let mut q = Vec::new();
        apply_pagination(&mut q, self.page, self.limit, None, None, false, false);
        if let Some(fy) = self.fiscal_year {
            q.push(("fiscal_year".into(), fy.to_string()));
        }
        q
    }
}

/// Options shared by every entity sub-resource list endpoint
/// (`/api/entities/{uei}/contracts/`, `/idvs/`, `/otas/`, `/otidvs/`,
/// `/subawards/`, `/lcats/`).
#[derive(Debug, Clone, Default, Builder, PartialEq, Eq)]
#[non_exhaustive]
pub struct EntitySubresourceOptions {
    /// 1-based page number. Mutually exclusive with [`cursor`](Self::cursor).
    #[builder(into)]
    pub page: Option<u32>,
    /// Page size.
    #[builder(into)]
    pub limit: Option<u32>,
    /// Keyset cursor for cursor-paginated endpoints.
    #[builder(into)]
    pub cursor: Option<String>,
    /// Comma-separated field selector.
    #[builder(into)]
    pub shape: Option<String>,
    /// Collapse nested objects into dot-separated keys.
    #[builder(default)]
    pub flat: bool,
    /// When [`flat`](Self::flat) is also true, flatten list-valued fields.
    #[builder(default)]
    pub flat_lists: bool,
    /// Joiner for flattened keys (only sent when `flat=true`).
    #[builder(into)]
    pub joiner: Option<String>,
    /// Server-side sort spec. Endpoint-specific allowlist; prefix `-` for
    /// descending. The subawards endpoint enforces a stricter allowlist than
    /// most — pass values verbatim and let the server validate.
    #[builder(into)]
    pub ordering: Option<String>,
    /// Free-text search filter where supported by the endpoint.
    #[builder(into)]
    pub search: Option<String>,
    /// Escape hatch for filter keys not yet first-classed.
    #[builder(default)]
    pub extra: BTreeMap<String, String>,
}

impl EntitySubresourceOptions {
    pub(crate) fn to_query(&self) -> Vec<(String, String)> {
        let mut q = Vec::new();
        apply_pagination(
            &mut q,
            self.page,
            self.limit,
            self.cursor.as_deref(),
            self.shape.as_deref(),
            self.flat,
            self.flat_lists,
        );
        if self.flat {
            if let Some(j) = self.joiner.as_deref().filter(|s| !s.is_empty()) {
                q.push(("joiner".into(), j.into()));
            }
        }
        push_opt(&mut q, "ordering", self.ordering.as_deref());
        push_opt(&mut q, "search", self.search.as_deref());
        for (k, v) in &self.extra {
            if !v.is_empty() {
                q.push((k.clone(), v.clone()));
            }
        }
        q
    }
}

impl Client {
    /// `GET /api/entities/{uei}/contracts/` — contracts awarded to this entity.
    pub async fn list_entity_contracts(
        &self,
        uei: &str,
        opts: EntitySubresourceOptions,
    ) -> Result<Page<Record>> {
        list_entity_subresource(self, uei, "contracts", opts).await
    }

    /// Stream every contract awarded to `uei`.
    pub fn iterate_entity_contracts(
        &self,
        uei: &str,
        opts: EntitySubresourceOptions,
    ) -> PageStream<Record> {
        iterate_entity_subresource(self, uei.to_string(), "contracts", opts)
    }

    /// `GET /api/entities/{uei}/idvs/` — IDVs held by this entity.
    pub async fn list_entity_idvs(
        &self,
        uei: &str,
        opts: EntitySubresourceOptions,
    ) -> Result<Page<Record>> {
        list_entity_subresource(self, uei, "idvs", opts).await
    }

    /// Stream every IDV held by `uei`.
    pub fn iterate_entity_idvs(
        &self,
        uei: &str,
        opts: EntitySubresourceOptions,
    ) -> PageStream<Record> {
        iterate_entity_subresource(self, uei.to_string(), "idvs", opts)
    }

    /// `GET /api/entities/{uei}/otas/` — Other Transaction Awards held by this
    /// entity.
    pub async fn list_entity_otas(
        &self,
        uei: &str,
        opts: EntitySubresourceOptions,
    ) -> Result<Page<Record>> {
        list_entity_subresource(self, uei, "otas", opts).await
    }

    /// Stream every OTA held by `uei`.
    pub fn iterate_entity_otas(
        &self,
        uei: &str,
        opts: EntitySubresourceOptions,
    ) -> PageStream<Record> {
        iterate_entity_subresource(self, uei.to_string(), "otas", opts)
    }

    /// `GET /api/entities/{uei}/otidvs/` — Other Transaction IDVs held by this
    /// entity.
    pub async fn list_entity_otidvs(
        &self,
        uei: &str,
        opts: EntitySubresourceOptions,
    ) -> Result<Page<Record>> {
        list_entity_subresource(self, uei, "otidvs", opts).await
    }

    /// Stream every OTIDV held by `uei`.
    pub fn iterate_entity_otidvs(
        &self,
        uei: &str,
        opts: EntitySubresourceOptions,
    ) -> PageStream<Record> {
        iterate_entity_subresource(self, uei.to_string(), "otidvs", opts)
    }

    /// `GET /api/entities/{uei}/subawards/` — subawards reported against
    /// contracts held by this entity.
    pub async fn list_entity_subawards(
        &self,
        uei: &str,
        opts: EntitySubresourceOptions,
    ) -> Result<Page<Record>> {
        list_entity_subresource(self, uei, "subawards", opts).await
    }

    /// Stream every subaward reported under `uei`.
    pub fn iterate_entity_subawards(
        &self,
        uei: &str,
        opts: EntitySubresourceOptions,
    ) -> PageStream<Record> {
        iterate_entity_subresource(self, uei.to_string(), "subawards", opts)
    }

    /// `GET /api/entities/{uei}/lcats/` — Labor Categories advertised by this
    /// entity.
    pub async fn list_entity_lcats(
        &self,
        uei: &str,
        opts: EntitySubresourceOptions,
    ) -> Result<Page<Record>> {
        list_entity_subresource(self, uei, "lcats", opts).await
    }

    /// Stream every LCAT advertised by `uei`.
    pub fn iterate_entity_lcats(
        &self,
        uei: &str,
        opts: EntitySubresourceOptions,
    ) -> PageStream<Record> {
        iterate_entity_subresource(self, uei.to_string(), "lcats", opts)
    }

    /// `GET /api/entities/{uei}/budget-flows/` — the federal accounts that paid this entity, largest `contract_obligated` first, each with its budget-account context.
    ///
    /// Contract flows only: grant and assistance flows are not in this index.
    pub async fn get_entity_budget_flows(
        &self,
        uei: &str,
        opts: Option<EntityBudgetFlowsOptions>,
    ) -> Result<Page<Record>> {
        if uei.is_empty() {
            return Err(Error::Validation {
                message: "get_entity_budget_flows: uei is required".into(),
                response: None,
            });
        }
        let q = opts.unwrap_or_default().to_query();
        let path = format!("/api/entities/{}/budget-flows/", urlencoding(uei));
        self.get_page(&path, &q).await
    }

    /// `GET /api/entities/{uei}/metrics/{months}/{period_grouping}/` — rolling
    /// windowed metrics for this entity. Mirrors the signature of the sibling
    /// SDKs (Node / Python / Go).
    ///
    /// `months` is the rolling-window length (must be > 0). `period_grouping`
    /// is typically `"month"` or `"quarter"`.
    pub async fn get_entity_metrics(
        &self,
        uei: &str,
        months: u32,
        period_grouping: &str,
    ) -> Result<Record> {
        if uei.is_empty() {
            return Err(Error::Validation {
                message: "get_entity_metrics: uei is required".into(),
                response: None,
            });
        }
        if months == 0 {
            return Err(Error::Validation {
                message: "get_entity_metrics: months must be > 0".into(),
                response: None,
            });
        }
        if period_grouping.is_empty() {
            return Err(Error::Validation {
                message: "get_entity_metrics: period_grouping is required".into(),
                response: None,
            });
        }
        let path = format!(
            "/api/entities/{}/metrics/{}/{}/",
            urlencoding(uei),
            months,
            urlencoding(period_grouping),
        );
        self.get_json::<Record>(&path, &[]).await
    }
}

async fn list_entity_subresource(
    client: &Client,
    uei: &str,
    segment: &str,
    opts: EntitySubresourceOptions,
) -> Result<Page<Record>> {
    if uei.is_empty() {
        return Err(Error::Validation {
            message: "entity sub-resource: uei is required".into(),
            response: None,
        });
    }
    let q = opts.to_query();
    let path = format!("/api/entities/{}/{segment}/", urlencoding(uei));
    client.get_page(&path, &q).await
}

fn iterate_entity_subresource(
    client: &Client,
    uei: String,
    segment: &'static str,
    opts: EntitySubresourceOptions,
) -> PageStream<Record> {
    let opts = Arc::new(opts);
    let uei = Arc::new(uei);
    let fetch: FetchFn<Record> = Box::new(move |client, page, cursor| {
        let mut next = (*opts).clone();
        next.page = page;
        next.cursor = cursor;
        let uei = uei.clone();
        Box::pin(async move { list_entity_subresource(&client, &uei, segment, next).await })
    });
    PageStream::new(client.clone(), fetch)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn get_q(q: &[(String, String)], k: &str) -> Option<String> {
        q.iter().find(|(kk, _)| kk == k).map(|(_, v)| v.clone())
    }

    #[test]
    fn options_emit_pagination_shape_and_search() {
        let opts = EntitySubresourceOptions::builder()
            .limit(10u32)
            .shape("contracts(minimal)")
            .ordering("-award_date")
            .search("software")
            .build();
        let q = opts.to_query();
        assert_eq!(get_q(&q, "limit").as_deref(), Some("10"));
        assert_eq!(get_q(&q, "shape").as_deref(), Some("contracts(minimal)"));
        assert_eq!(get_q(&q, "ordering").as_deref(), Some("-award_date"));
        assert_eq!(get_q(&q, "search").as_deref(), Some("software"));
        assert!(!q.iter().any(|(k, _)| k == "joiner"));
    }

    #[test]
    fn joiner_only_when_flat() {
        let opts = EntitySubresourceOptions::builder()
            .joiner("__".to_string())
            .build();
        let q = opts.to_query();
        assert!(!q.iter().any(|(k, _)| k == "joiner"));

        let opts = EntitySubresourceOptions::builder()
            .flat(true)
            .joiner("__".to_string())
            .build();
        let q = opts.to_query();
        assert!(q.contains(&("joiner".into(), "__".into())));
    }

    #[test]
    fn extra_forwards_arbitrary_params() {
        let mut extra = BTreeMap::new();
        extra.insert("custom_x".to_string(), "val".to_string());
        let opts = EntitySubresourceOptions::builder().extra(extra).build();
        let q = opts.to_query();
        assert!(q.contains(&("custom_x".into(), "val".into())));
    }

    #[tokio::test]
    async fn list_entity_contracts_empty_uei_returns_validation() {
        let client = Client::builder().api_key("x").build().expect("build");
        let err = client
            .list_entity_contracts("", EntitySubresourceOptions::default())
            .await
            .expect_err("must error");
        match err {
            Error::Validation { message, .. } => assert!(message.contains("uei")),
            other => panic!("expected Validation, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn list_entity_subawards_empty_uei_returns_validation() {
        let client = Client::builder().api_key("x").build().expect("build");
        let err = client
            .list_entity_subawards("", EntitySubresourceOptions::default())
            .await
            .expect_err("must error");
        match err {
            Error::Validation { message, .. } => assert!(message.contains("uei")),
            other => panic!("expected Validation, got {other:?}"),
        }
    }

    #[test]
    fn budget_flows_options_emit_fiscal_year() {
        let q = EntityBudgetFlowsOptions::builder()
            .fiscal_year(2024u32)
            .limit(10u32)
            .build()
            .to_query();
        assert_eq!(
            q,
            vec![
                ("limit".to_string(), "10".to_string()),
                ("fiscal_year".to_string(), "2024".to_string())
            ]
        );
    }

    #[tokio::test]
    async fn get_entity_budget_flows_empty_uei_returns_validation() {
        let client = Client::builder().api_key("x").build().expect("build");
        let err = client
            .get_entity_budget_flows("", None)
            .await
            .expect_err("must error");
        match err {
            Error::Validation { message, .. } => assert!(message.contains("uei")),
            other => panic!("expected Validation, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn get_entity_metrics_empty_uei_returns_validation() {
        let client = Client::builder().api_key("x").build().expect("build");
        let err = client
            .get_entity_metrics("", 12, "month")
            .await
            .expect_err("must error");
        match err {
            Error::Validation { message, .. } => assert!(message.contains("uei")),
            other => panic!("expected Validation, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn get_entity_metrics_zero_months_returns_validation() {
        let client = Client::builder().api_key("x").build().expect("build");
        let err = client
            .get_entity_metrics("ABC123DEF456", 0, "month")
            .await
            .expect_err("must error");
        assert!(matches!(err, Error::Validation { .. }));
    }

    #[tokio::test]
    async fn get_entity_metrics_empty_period_grouping_returns_validation() {
        let client = Client::builder().api_key("x").build().expect("build");
        let err = client
            .get_entity_metrics("ABC123DEF456", 12, "")
            .await
            .expect_err("must error");
        assert!(matches!(err, Error::Validation { .. }));
    }
}