makegov-tango 0.4.0

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
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
//! `/api/budget/accounts/` — federal-account x fiscal-year budget rollups.
//!
//! One row per `(federal_account_symbol, fiscal_year)` covering the full
//! budget lifecycle (requested → enacted → apportioned → obligated →
//! outlayed), pre-computed ratios + trends, the contract/assistance/unlinked
//! breakdown, and request-vs-actual contract spend. The schema is wide
//! (~63 fields) and shape-driven, so every method returns the untyped
//! [`Record`] map like the other resource families.
//! The `source_anomalies` list in each row decodes with
//! [`BudgetSourceAnomaly::from_record`](crate::models::BudgetSourceAnomaly::from_record),
//! and [`budget_data_through_period`](crate::models::budget_data_through_period) reads `data_through_period`.

use crate::client::Client;
use crate::error::{Error, Result};
use crate::internal::{apply_pagination, push_opt, push_opt_bool, ListOptions};
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::list_budget_accounts`] and [`Client::iterate_budget_accounts`].
///
/// The API rejects an unknown filter name with a 400 rather than ignoring it.
/// The exact, `__gte` and `__lte` range filters on the numeric lifecycle and ratio fields (e.g. `enacted_ba__gte`), and the `__in` multi-value variants other than [`account_category_in`](Self::account_category_in), are reachable via the [`extra`](Self::extra) map.
/// There is no filter on `source_anomalies`; it is in the default shape, so every row already carries it.
#[derive(Debug, Clone, Default, Builder, PartialEq, Eq)]
#[non_exhaustive]
pub struct ListBudgetAccountsOptions {
    // ----- Pagination + shape -----
    /// 1-based page number. Mutually exclusive with [`cursor`](Self::cursor).
    #[builder(into)]
    pub page: Option<u32>,
    /// Page size (server caps at 100).
    #[builder(into)]
    pub limit: Option<u32>,
    /// Keyset cursor.
    #[builder(into)]
    pub cursor: Option<String>,
    /// Comma-separated field selector. Use
    /// [`SHAPE_BUDGET_ACCOUNTS_MINIMAL`](crate::SHAPE_BUDGET_ACCOUNTS_MINIMAL)
    /// or roll your own.
    #[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,

    // ----- Resource filters -----
    /// Federal account symbol filter (exact, e.g. `"097-0100"`).
    #[builder(into)]
    pub federal_account_symbol: Option<String>,
    /// `fiscal_year` filter (exact).
    #[builder(into)]
    pub fiscal_year: Option<String>,
    /// Lower bound for `fiscal_year` (inclusive).
    #[builder(into)]
    pub fiscal_year_gte: Option<String>,
    /// Upper bound for `fiscal_year` (inclusive).
    #[builder(into)]
    pub fiscal_year_lte: Option<String>,
    /// `data_through_period` filter (exact): the File A fiscal period (1-12) the account-year's figures run through.
    #[builder(into)]
    pub data_through_period: Option<String>,
    /// Lower bound for `data_through_period` (inclusive).
    #[builder(into)]
    pub data_through_period_gte: Option<String>,
    /// Upper bound for `data_through_period` (inclusive).
    #[builder(into)]
    pub data_through_period_lte: Option<String>,
    /// `Some(true)` keeps only rows with no File A data (null `data_through_period`), `Some(false)` only rows with it (sent as `data_through_period__isnull`).
    pub data_through_period_isnull: Option<bool>,
    /// A Tango agency name, abbreviation, code or organization key (e.g. `EPA`), matched against the account's resolved organization. Matches by name, abbreviation, or code (CGAC, FPDS, Federal Hierarchy key or AAC) and includes every sub-agency and office beneath it; OR several with `|`. A token that does not resolve falls back to an exact match on `agency_code`.
    #[builder(into)]
    pub agency: Option<String>,
    /// Agency code filter (exact).
    #[builder(into)]
    pub agency_code: Option<String>,
    /// Bureau name filter (exact).
    #[builder(into)]
    pub bureau_name: Option<String>,
    /// Case-insensitive substring match on the account title (sent as `account_title__icontains`).
    #[builder(into)]
    pub account_title: Option<String>,
    /// Budget subfunction code filter (exact).
    #[builder(into)]
    pub subfunction_code: Option<String>,
    /// Bureau of Economic Analysis category filter (exact).
    #[builder(into)]
    pub bea_category: Option<String>,
    /// On/off-budget flag filter (exact).
    #[builder(into)]
    pub on_off_budget: Option<String>,
    /// Account category filter (exact): `budgetary` or `credit_financing` today.
    /// Credit financing accounts have no enacted budget authority (`enacted_ba` is null) and are left out of organization budget totals.
    #[builder(into)]
    pub account_category: Option<String>,
    /// Several account categories, comma-separated (sent as `account_category__in`).
    #[builder(into)]
    pub account_category_in: Option<String>,
    /// Free-text search filter.
    #[builder(into)]
    pub search: Option<String>,
    /// Server-side sort spec (prefix `-` for descending).
    /// The default is latest fiscal year first, then largest `enacted_ba`, with null `enacted_ba` last and `id` breaking ties.
    #[builder(into)]
    pub ordering: Option<String>,

    /// Escape hatch for filter keys not yet first-classed on this struct
    /// (e.g. the `*_gte` / `*_lte` range filters on the numeric metrics).
    #[builder(default)]
    pub extra: BTreeMap<String, String>,
}

impl ListBudgetAccountsOptions {
    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,
        );
        push_opt(
            &mut q,
            "federal_account_symbol",
            self.federal_account_symbol.as_deref(),
        );
        push_opt(&mut q, "fiscal_year", self.fiscal_year.as_deref());
        push_opt(&mut q, "fiscal_year__gte", self.fiscal_year_gte.as_deref());
        push_opt(&mut q, "fiscal_year__lte", self.fiscal_year_lte.as_deref());
        push_opt(
            &mut q,
            "data_through_period",
            self.data_through_period.as_deref(),
        );
        push_opt(
            &mut q,
            "data_through_period__gte",
            self.data_through_period_gte.as_deref(),
        );
        push_opt(
            &mut q,
            "data_through_period__lte",
            self.data_through_period_lte.as_deref(),
        );
        push_opt_bool(
            &mut q,
            "data_through_period__isnull",
            self.data_through_period_isnull,
        );
        push_opt(&mut q, "agency", self.agency.as_deref());
        push_opt(&mut q, "agency_code", self.agency_code.as_deref());
        push_opt(&mut q, "bureau_name", self.bureau_name.as_deref());
        push_opt(
            &mut q,
            "account_title__icontains",
            self.account_title.as_deref(),
        );
        push_opt(&mut q, "subfunction_code", self.subfunction_code.as_deref());
        push_opt(&mut q, "bea_category", self.bea_category.as_deref());
        push_opt(&mut q, "on_off_budget", self.on_off_budget.as_deref());
        push_opt(&mut q, "account_category", self.account_category.as_deref());
        push_opt(
            &mut q,
            "account_category__in",
            self.account_category_in.as_deref(),
        );
        push_opt(&mut q, "search", self.search.as_deref());
        push_opt(&mut q, "ordering", self.ordering.as_deref());
        for (k, v) in &self.extra {
            if !v.is_empty() {
                q.push((k.clone(), v.clone()));
            }
        }
        q
    }
}

/// Options for [`Client::get_budget_account_quarters`].
#[derive(Debug, Clone, Default, Builder, PartialEq, Eq)]
#[non_exhaustive]
pub struct BudgetAccountQuartersOptions {
    /// 1-based page number.
    #[builder(into)]
    pub page: Option<u32>,
    /// Page size (default 25, server caps at 100).
    #[builder(into)]
    pub limit: Option<u32>,
    /// Narrow to a single Treasury Account Symbol. Omit to get every TAS that rolls up under the federal account.
    #[builder(into)]
    pub tas: Option<String>,
}

impl BudgetAccountQuartersOptions {
    fn to_query(&self) -> Vec<(String, String)> {
        let mut q = Vec::new();
        apply_pagination(&mut q, self.page, self.limit, None, None, false, false);
        push_opt(&mut q, "tas", self.tas.as_deref());
        q
    }
}

/// Options for [`Client::get_budget_account_recipients`].
#[derive(Debug, Clone, Default, Builder, PartialEq, Eq)]
#[non_exhaustive]
pub struct BudgetAccountRecipientsOptions {
    /// 1-based page number.
    #[builder(into)]
    pub page: Option<u32>,
    /// Page size (default 25, server caps at 100).
    #[builder(into)]
    pub limit: Option<u32>,
    /// Narrow to a single funding office (an organization UUID).
    #[builder(into)]
    pub funding_organization_id: Option<String>,
}

impl BudgetAccountRecipientsOptions {
    fn to_query(&self) -> Vec<(String, String)> {
        let mut q = Vec::new();
        apply_pagination(&mut q, self.page, self.limit, None, None, false, false);
        push_opt(
            &mut q,
            "funding_organization_id",
            self.funding_organization_id.as_deref(),
        );
        q
    }
}

impl Client {
    /// `GET /api/budget/accounts/` — one page of budget-account rollups.
    pub async fn list_budget_accounts(
        &self,
        opts: ListBudgetAccountsOptions,
    ) -> Result<Page<Record>> {
        let q = opts.to_query();
        self.get_page("/api/budget/accounts/", &q).await
    }

    /// Stream every budget-account rollup matching `opts`.
    pub fn iterate_budget_accounts(&self, opts: ListBudgetAccountsOptions) -> PageStream<Record> {
        let opts = Arc::new(opts);
        let fetch: FetchFn<Record> = Box::new(move |client, page, cursor| {
            let mut next = (*opts).clone();
            next.page = page;
            next.cursor = cursor;
            Box::pin(async move { client.list_budget_accounts(next).await })
        });
        PageStream::new(self.clone(), fetch)
    }

    /// `GET /api/budget/accounts/{id}/` — a single budget-account rollup by its numeric `id` (from a list row's `id` field).
    pub async fn get_budget_account(&self, id: &str, opts: Option<ListOptions>) -> Result<Record> {
        if id.is_empty() {
            return Err(Error::Validation {
                message: "get_budget_account: id is required".into(),
                response: None,
            });
        }
        let mut q = Vec::new();
        opts.unwrap_or_default().apply(&mut q);
        let path = format!("/api/budget/accounts/{}/", urlencoding(id));
        self.get_json::<Record>(&path, &q).await
    }

    /// `GET /api/budget/accounts/{id}/quarters/` — one row per (TAS, quarter) of obligation and outlay flow for a single account-year.
    ///
    /// Coverage starts at FY2021; earlier years return an empty page.
    /// The envelope also carries `federal_account_symbol` and `fiscal_year`, which [`Page`] does not surface.
    pub async fn get_budget_account_quarters(
        &self,
        id: &str,
        opts: Option<BudgetAccountQuartersOptions>,
    ) -> Result<Page<Record>> {
        if id.is_empty() {
            return Err(Error::Validation {
                message: "get_budget_account_quarters: id is required".into(),
                response: None,
            });
        }
        let q = opts.unwrap_or_default().to_query();
        let path = format!("/api/budget/accounts/{}/quarters/", urlencoding(id));
        self.get_page(&path, &q).await
    }

    /// `GET /api/budget/accounts/{id}/recipients/` — funding-office x recipient contract flows for a single account-year, largest `contract_obligated` first.
    ///
    /// Contract flows only. Each row carries the resolved `funding_office` and `recipient`, plus a capped `contracts` list; a row that hits the cap sets `contracts_truncated`.
    /// The envelope also carries `federal_account_symbol` and `fiscal_year`, which [`Page`] does not surface.
    pub async fn get_budget_account_recipients(
        &self,
        id: &str,
        opts: Option<BudgetAccountRecipientsOptions>,
    ) -> Result<Page<Record>> {
        if id.is_empty() {
            return Err(Error::Validation {
                message: "get_budget_account_recipients: id is required".into(),
                response: None,
            });
        }
        let q = opts.unwrap_or_default().to_query();
        let path = format!("/api/budget/accounts/{}/recipients/", urlencoding(id));
        self.get_page(&path, &q).await
    }
}

#[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_all_filters() {
        let opts = ListBudgetAccountsOptions::builder()
            .federal_account_symbol("097-0100")
            .fiscal_year("2024")
            .fiscal_year_gte("2020")
            .fiscal_year_lte("2025")
            .data_through_period("9")
            .data_through_period_gte("3")
            .data_through_period_lte("11")
            .data_through_period_isnull(false)
            .agency_code("9700")
            .bureau_name("Operation and Maintenance")
            .account_title("readiness")
            .subfunction_code("051")
            .bea_category("discretionary")
            .on_off_budget("on")
            .account_category("credit_financing")
            .account_category_in("budgetary,credit_financing")
            .search("operations")
            .ordering("-enacted_ba")
            .build();
        let q = opts.to_query();
        assert_eq!(
            get_q(&q, "federal_account_symbol").as_deref(),
            Some("097-0100")
        );
        assert_eq!(get_q(&q, "fiscal_year").as_deref(), Some("2024"));
        assert_eq!(get_q(&q, "fiscal_year__gte").as_deref(), Some("2020"));
        assert_eq!(get_q(&q, "fiscal_year__lte").as_deref(), Some("2025"));
        assert_eq!(get_q(&q, "data_through_period").as_deref(), Some("9"));
        assert_eq!(get_q(&q, "data_through_period__gte").as_deref(), Some("3"));
        assert_eq!(get_q(&q, "data_through_period__lte").as_deref(), Some("11"));
        assert_eq!(
            get_q(&q, "data_through_period__isnull").as_deref(),
            Some("false")
        );
        assert_eq!(get_q(&q, "agency_code").as_deref(), Some("9700"));
        assert_eq!(
            get_q(&q, "bureau_name").as_deref(),
            Some("Operation and Maintenance")
        );
        assert_eq!(
            get_q(&q, "account_title__icontains").as_deref(),
            Some("readiness")
        );
        assert_eq!(get_q(&q, "subfunction_code").as_deref(), Some("051"));
        assert_eq!(get_q(&q, "bea_category").as_deref(), Some("discretionary"));
        assert_eq!(get_q(&q, "on_off_budget").as_deref(), Some("on"));
        assert_eq!(
            get_q(&q, "account_category").as_deref(),
            Some("credit_financing")
        );
        assert_eq!(
            get_q(&q, "account_category__in").as_deref(),
            Some("budgetary,credit_financing")
        );
        assert_eq!(get_q(&q, "search").as_deref(), Some("operations"));
        assert_eq!(get_q(&q, "ordering").as_deref(), Some("-enacted_ba"));
    }

    #[test]
    fn pagination_and_shape_emit() {
        let opts = ListBudgetAccountsOptions::builder()
            .page(2u32)
            .limit(50u32)
            .shape(crate::SHAPE_BUDGET_ACCOUNTS_MINIMAL)
            .build();
        let q = opts.to_query();
        assert_eq!(get_q(&q, "page").as_deref(), Some("2"));
        assert_eq!(get_q(&q, "limit").as_deref(), Some("50"));
        assert_eq!(
            get_q(&q, "shape").as_deref(),
            Some(crate::SHAPE_BUDGET_ACCOUNTS_MINIMAL)
        );
    }

    #[test]
    fn minimal_shape_carries_category_and_anomalies() {
        let fields: Vec<&str> = crate::SHAPE_BUDGET_ACCOUNTS_MINIMAL.split(',').collect();
        assert!(fields.contains(&"account_category"));
        assert!(fields.contains(&"source_anomalies"));
    }

    #[test]
    fn minimal_shape_puts_data_through_period_after_fiscal_year() {
        let fields: Vec<&str> = crate::SHAPE_BUDGET_ACCOUNTS_MINIMAL.split(',').collect();
        let fy = fields.iter().position(|f| *f == "fiscal_year").unwrap();
        assert_eq!(fields[fy + 1], "data_through_period");
    }

    #[test]
    fn extra_forwards_range_filters() {
        let mut extra = BTreeMap::new();
        extra.insert("enacted_ba__gte".to_string(), "1000000".to_string());
        let opts = ListBudgetAccountsOptions::builder().extra(extra).build();
        let q = opts.to_query();
        assert_eq!(get_q(&q, "enacted_ba__gte").as_deref(), Some("1000000"));
    }

    #[test]
    fn quarters_options_emit_tas_and_pagination() {
        let q = BudgetAccountQuartersOptions::builder()
            .page(2u32)
            .limit(50u32)
            .tas("097-2020/2021-0100")
            .build()
            .to_query();
        assert_eq!(get_q(&q, "page").as_deref(), Some("2"));
        assert_eq!(get_q(&q, "limit").as_deref(), Some("50"));
        assert_eq!(get_q(&q, "tas").as_deref(), Some("097-2020/2021-0100"));
        assert_eq!(q.len(), 3);
    }

    #[test]
    fn recipients_options_emit_funding_organization_id() {
        let q = BudgetAccountRecipientsOptions::builder()
            .funding_organization_id("0b7e4c1e-0000-4000-8000-000000000000")
            .build()
            .to_query();
        assert_eq!(
            q,
            vec![(
                "funding_organization_id".to_string(),
                "0b7e4c1e-0000-4000-8000-000000000000".to_string()
            )]
        );
    }

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

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

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

    #[test]
    fn list_budget_accounts_agency_filter_emits() {
        let q = ListBudgetAccountsOptions::builder()
            .agency("EPA")
            .build()
            .to_query();
        assert_eq!(get_q(&q, "agency").as_deref(), Some("EPA"));
    }
}