Skip to main content

tango/resources/
idv_subresources.rs

1//! IDV sub-resources: awards, child IDVs, transactions, LCATs.
2//!
3//! Endpoints under `/api/idvs/{key}/…/` that share a common parameter shape.
4//! The Go SDK uses a mix of `ListIDVsOptions` (awards/child-idvs),
5//! `ListOptions` (transactions), and `EntityLcatsOptions`
6//! (lcats); the Rust port consolidates these behind a single
7//! [`IdvSubresourceOptions`] (pagination + shape + ordering + search + joiner)
8//! since the surface server-side params for these endpoints are identical at
9//! the SDK level.
10
11use crate::client::Client;
12use crate::error::{Error, Result};
13use crate::internal::{apply_pagination, push_opt};
14use crate::pagination::{FetchFn, Page, PageStream};
15use crate::resources::agencies::urlencoding;
16use crate::Record;
17use bon::Builder;
18use std::collections::BTreeMap;
19use std::sync::Arc;
20
21/// Options shared by every IDV sub-resource list endpoint
22/// (`/api/idvs/{key}/awards/`, `/child-idvs/`, `/transactions/`,
23/// `/lcats/`).
24///
25/// Carries pagination + shape + ordering + search + joiner. Use the `extra`
26/// field to forward filters not yet first-classed on this struct.
27#[derive(Debug, Clone, Default, Builder, PartialEq, Eq)]
28#[non_exhaustive]
29pub struct IdvSubresourceOptions {
30    /// 1-based page number. Mutually exclusive with [`cursor`](Self::cursor).
31    #[builder(into)]
32    pub page: Option<u32>,
33    /// Page size.
34    #[builder(into)]
35    pub limit: Option<u32>,
36    /// Keyset cursor for cursor-paginated endpoints.
37    #[builder(into)]
38    pub cursor: Option<String>,
39    /// Comma-separated field selector.
40    #[builder(into)]
41    pub shape: Option<String>,
42    /// Collapse nested objects into dot-separated keys.
43    #[builder(default)]
44    pub flat: bool,
45    /// When [`flat`](Self::flat) is also true, flatten list-valued fields.
46    #[builder(default)]
47    pub flat_lists: bool,
48    /// Joiner for flattened keys (only sent when `flat=true`).
49    #[builder(into)]
50    pub joiner: Option<String>,
51    /// Server-side sort spec (prefix `-` for descending).
52    #[builder(into)]
53    pub ordering: Option<String>,
54    /// Free-text search filter.
55    #[builder(into)]
56    pub search: Option<String>,
57    /// Escape hatch for filter keys not yet first-classed.
58    #[builder(default)]
59    pub extra: BTreeMap<String, String>,
60}
61
62impl IdvSubresourceOptions {
63    pub(crate) fn to_query(&self) -> Vec<(String, String)> {
64        let mut q = Vec::new();
65        apply_pagination(
66            &mut q,
67            self.page,
68            self.limit,
69            self.cursor.as_deref(),
70            self.shape.as_deref(),
71            self.flat,
72            self.flat_lists,
73        );
74        if self.flat {
75            if let Some(j) = self.joiner.as_deref().filter(|s| !s.is_empty()) {
76                q.push(("joiner".into(), j.into()));
77            }
78        }
79        push_opt(&mut q, "ordering", self.ordering.as_deref());
80        push_opt(&mut q, "search", self.search.as_deref());
81        for (k, v) in &self.extra {
82            if !v.is_empty() {
83                q.push((k.clone(), v.clone()));
84            }
85        }
86        q
87    }
88}
89
90impl Client {
91    /// `GET /api/idvs/{key}/awards/` — task-order awards under a parent IDV.
92    pub async fn list_idv_awards(
93        &self,
94        key: &str,
95        opts: IdvSubresourceOptions,
96    ) -> Result<Page<Record>> {
97        list_idv_subresource(self, key, "awards", opts).await
98    }
99
100    /// Stream every task-order award under `key`.
101    pub fn iterate_idv_awards(&self, key: &str, opts: IdvSubresourceOptions) -> PageStream<Record> {
102        iterate_idv_subresource(self, key.to_string(), "awards", opts)
103    }
104
105    /// `GET /api/idvs/{key}/idvs/` — child IDVs nested under a parent IDV.
106    pub async fn list_idv_child_idvs(
107        &self,
108        key: &str,
109        opts: IdvSubresourceOptions,
110    ) -> Result<Page<Record>> {
111        list_idv_subresource(self, key, "idvs", opts).await
112    }
113
114    /// Stream every child IDV under `key`.
115    pub fn iterate_idv_child_idvs(
116        &self,
117        key: &str,
118        opts: IdvSubresourceOptions,
119    ) -> PageStream<Record> {
120        iterate_idv_subresource(self, key.to_string(), "idvs", opts)
121    }
122
123    /// `GET /api/idvs/{key}/transactions/` — raw transaction history backing
124    /// an IDV.
125    pub async fn list_idv_transactions(
126        &self,
127        key: &str,
128        opts: IdvSubresourceOptions,
129    ) -> Result<Page<Record>> {
130        list_idv_subresource(self, key, "transactions", opts).await
131    }
132
133    /// Stream every transaction backing `key`.
134    pub fn iterate_idv_transactions(
135        &self,
136        key: &str,
137        opts: IdvSubresourceOptions,
138    ) -> PageStream<Record> {
139        iterate_idv_subresource(self, key.to_string(), "transactions", opts)
140    }
141
142    /// `GET /api/idvs/{key}/lcats/` — Labor Categories (LCATs) under an IDV.
143    pub async fn list_idv_lcats(
144        &self,
145        key: &str,
146        opts: IdvSubresourceOptions,
147    ) -> Result<Page<Record>> {
148        list_idv_subresource(self, key, "lcats", opts).await
149    }
150
151    /// Stream every LCAT under `key`.
152    pub fn iterate_idv_lcats(&self, key: &str, opts: IdvSubresourceOptions) -> PageStream<Record> {
153        iterate_idv_subresource(self, key.to_string(), "lcats", opts)
154    }
155}
156
157async fn list_idv_subresource(
158    client: &Client,
159    key: &str,
160    segment: &str,
161    opts: IdvSubresourceOptions,
162) -> Result<Page<Record>> {
163    if key.is_empty() {
164        return Err(Error::Validation {
165            message: "IDV sub-resource: key is required".into(),
166            response: None,
167        });
168    }
169    let q = opts.to_query();
170    let path = format!("/api/idvs/{}/{segment}/", urlencoding(key));
171    let bytes = client.get_bytes(&path, &q).await?;
172    Page::decode(&bytes)
173}
174
175fn iterate_idv_subresource(
176    client: &Client,
177    key: String,
178    segment: &'static str,
179    opts: IdvSubresourceOptions,
180) -> PageStream<Record> {
181    let opts = Arc::new(opts);
182    let key = Arc::new(key);
183    let fetch: FetchFn<Record> = Box::new(move |client, page, cursor| {
184        let mut next = (*opts).clone();
185        next.page = page;
186        next.cursor = cursor;
187        let key = key.clone();
188        Box::pin(async move { list_idv_subresource(&client, &key, segment, next).await })
189    });
190    PageStream::new(client.clone(), fetch)
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    fn get_q(q: &[(String, String)], k: &str) -> Option<String> {
198        q.iter().find(|(kk, _)| kk == k).map(|(_, v)| v.clone())
199    }
200
201    #[test]
202    fn options_emit_pagination_and_search() {
203        let opts = IdvSubresourceOptions::builder()
204            .limit(10u32)
205            .ordering("-award_date")
206            .search("software")
207            .build();
208        let q = opts.to_query();
209        assert_eq!(get_q(&q, "limit").as_deref(), Some("10"));
210        assert_eq!(get_q(&q, "ordering").as_deref(), Some("-award_date"));
211        assert_eq!(get_q(&q, "search").as_deref(), Some("software"));
212    }
213
214    #[test]
215    fn joiner_only_when_flat() {
216        let opts = IdvSubresourceOptions::builder()
217            .joiner("__".to_string())
218            .build();
219        let q = opts.to_query();
220        assert!(!q.iter().any(|(k, _)| k == "joiner"));
221
222        let opts = IdvSubresourceOptions::builder()
223            .flat(true)
224            .joiner("__".to_string())
225            .build();
226        let q = opts.to_query();
227        assert!(q.contains(&("joiner".into(), "__".into())));
228    }
229
230    #[test]
231    fn extra_forwards_arbitrary_params() {
232        let mut extra = BTreeMap::new();
233        extra.insert("region".to_string(), "west".to_string());
234        let opts = IdvSubresourceOptions::builder().extra(extra).build();
235        let q = opts.to_query();
236        assert!(q.contains(&("region".into(), "west".into())));
237    }
238
239    #[tokio::test]
240    async fn list_idv_awards_empty_key_returns_validation() {
241        let client = Client::builder().api_key("x").build().expect("build");
242        let err = client
243            .list_idv_awards("", IdvSubresourceOptions::default())
244            .await
245            .expect_err("must error");
246        match err {
247            Error::Validation { message, .. } => assert!(message.contains("key")),
248            other => panic!("expected Validation, got {other:?}"),
249        }
250    }
251
252    #[tokio::test]
253    async fn list_idv_lcats_empty_key_returns_validation() {
254        let client = Client::builder().api_key("x").build().expect("build");
255        let err = client
256            .list_idv_lcats("", IdvSubresourceOptions::default())
257            .await
258            .expect_err("must error");
259        match err {
260            Error::Validation { message, .. } => assert!(message.contains("key")),
261            other => panic!("expected Validation, got {other:?}"),
262        }
263    }
264}