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
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
//! `/api/opportunities/`, `/api/notices/`, `/api/forecasts/`, `/api/grants/`,
//! and the opportunity-attachment semantic-search endpoint.

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;

// ---------------------------------------------------------------------------
// Opportunities
// ---------------------------------------------------------------------------

/// Options for [`Client::list_opportunities`] and
/// [`Client::iterate_opportunities`]. Mirrors `ListOpportunitiesOptions`
/// in the Go SDK.
#[derive(Debug, Clone, Default, Builder, PartialEq, Eq)]
#[non_exhaustive]
pub struct ListOpportunitiesOptions {
    // ----- Pagination + shape -----
    /// 1-based page number.
    #[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.
    #[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,

    // ----- Filters -----
    /// Tri-state: `Some(true)`/`Some(false)` to filter; `None` to omit.
    #[builder(into)]
    pub active: Option<bool>,
    /// Whether the opportunity has an award, either posted on it or linked to it from a separate award notice (Tango API 5.5.0). Searches every opportunity rather than only active ones, so pair it with [`active`](Self::active) to narrow to open opportunities. `Some(false)` reaches the server as a filter value.
    pub awarded: Option<bool>,
    /// The awardee's UEI, case-insensitive; OR several with `|` (Tango API 5.5.0). Searches every opportunity rather than only active ones.
    #[builder(into)]
    pub awardee_uei: Option<String>,
    /// Awarding agency CGAC code.
    #[builder(into)]
    pub agency: Option<String>,
    /// Lower bound for first-notice date (inclusive, ISO `YYYY-MM-DD`).
    #[builder(into)]
    pub first_notice_date_after: Option<String>,
    /// Upper bound for first-notice date (inclusive).
    #[builder(into)]
    pub first_notice_date_before: Option<String>,
    /// Lower bound for last-notice date (inclusive).
    #[builder(into)]
    pub last_notice_date_after: Option<String>,
    /// Upper bound for last-notice date (inclusive).
    #[builder(into)]
    pub last_notice_date_before: Option<String>,
    /// NAICS code filter.
    #[builder(into)]
    pub naics: Option<String>,
    /// Notice-type filter (e.g. `"PRESOL"`).
    #[builder(into)]
    pub notice_type: Option<String>,
    /// Server-side sort spec (prefix with `-` for descending).
    #[builder(into)]
    pub ordering: Option<String>,
    /// Place of performance filter (state code, etc.).
    #[builder(into)]
    pub place_of_performance: Option<String>,
    /// PSC code filter.
    #[builder(into)]
    pub psc: Option<String>,
    /// Lower bound for response deadline.
    #[builder(into)]
    pub response_deadline_after: Option<String>,
    /// Upper bound for response deadline.
    #[builder(into)]
    pub response_deadline_before: Option<String>,
    /// Free-text search filter.
    #[builder(into)]
    pub search: Option<String>,
    /// Set-aside filter.
    #[builder(into)]
    pub set_aside: Option<String>,
    /// Solicitation number filter.
    #[builder(into)]
    pub solicitation_number: Option<String>,

    /// Opportunity ID filter.
    #[builder(into)]
    pub opportunity_id: Option<String>,

    /// Escape hatch for filter keys not yet first-classed on this struct.
    #[builder(default)]
    pub extra: BTreeMap<String, String>,
}

impl ListOpportunitiesOptions {
    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_bool(&mut q, "active", self.active);
        push_opt_bool(&mut q, "awarded", self.awarded);
        push_opt(&mut q, "awardee_uei", self.awardee_uei.as_deref());
        push_opt(&mut q, "agency", self.agency.as_deref());
        push_opt(
            &mut q,
            "first_notice_date_after",
            self.first_notice_date_after.as_deref(),
        );
        push_opt(
            &mut q,
            "first_notice_date_before",
            self.first_notice_date_before.as_deref(),
        );
        push_opt(
            &mut q,
            "last_notice_date_after",
            self.last_notice_date_after.as_deref(),
        );
        push_opt(
            &mut q,
            "last_notice_date_before",
            self.last_notice_date_before.as_deref(),
        );
        push_opt(&mut q, "naics", self.naics.as_deref());
        push_opt(&mut q, "notice_type", self.notice_type.as_deref());
        push_opt(&mut q, "ordering", self.ordering.as_deref());
        push_opt(
            &mut q,
            "place_of_performance",
            self.place_of_performance.as_deref(),
        );
        push_opt(&mut q, "psc", self.psc.as_deref());
        push_opt(
            &mut q,
            "response_deadline_after",
            self.response_deadline_after.as_deref(),
        );
        push_opt(
            &mut q,
            "response_deadline_before",
            self.response_deadline_before.as_deref(),
        );
        push_opt(&mut q, "search", self.search.as_deref());
        push_opt(&mut q, "opportunity_id", self.opportunity_id.as_deref());
        push_opt(&mut q, "set_aside", self.set_aside.as_deref());
        push_opt(
            &mut q,
            "solicitation_number",
            self.solicitation_number.as_deref(),
        );
        for (k, v) in &self.extra {
            if !v.is_empty() {
                q.push((k.clone(), v.clone()));
            }
        }
        q
    }
}

// ---------------------------------------------------------------------------
// Notices
// ---------------------------------------------------------------------------

/// Options for [`Client::list_notices`] and [`Client::iterate_notices`].
/// Mirrors `ListNoticesOptions` in the Go SDK. The server rejects every
/// `?ordering=` value on this endpoint, so the field is intentionally
/// omitted.
#[derive(Debug, Clone, Default, Builder, PartialEq, Eq)]
#[non_exhaustive]
pub struct ListNoticesOptions {
    /// 1-based page number.
    #[builder(into)]
    pub page: Option<u32>,
    /// Page size.
    #[builder(into)]
    pub limit: Option<u32>,
    /// Keyset cursor.
    #[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,

    /// Tri-state active/inactive filter.
    #[builder(into)]
    pub active: Option<bool>,
    /// Awarding agency CGAC code.
    #[builder(into)]
    pub agency: Option<String>,
    /// NAICS code filter.
    #[builder(into)]
    pub naics: Option<String>,
    /// Notice-type filter.
    #[builder(into)]
    pub notice_type: Option<String>,
    /// Lower bound for posted date (inclusive).
    #[builder(into)]
    pub posted_date_after: Option<String>,
    /// Upper bound for posted date (inclusive).
    #[builder(into)]
    pub posted_date_before: Option<String>,
    /// PSC code filter.
    #[builder(into)]
    pub psc: Option<String>,
    /// Lower bound for response deadline.
    #[builder(into)]
    pub response_deadline_after: Option<String>,
    /// Upper bound for response deadline.
    #[builder(into)]
    pub response_deadline_before: Option<String>,
    /// Free-text search filter.
    #[builder(into)]
    pub search: Option<String>,
    /// Set-aside filter.
    #[builder(into)]
    pub set_aside: Option<String>,
    /// Solicitation number filter.
    #[builder(into)]
    pub solicitation_number: Option<String>,

    /// Notice ID filter.
    #[builder(into)]
    pub notice_id: Option<String>,

    /// Department filter: a name, abbreviation or code, with `|` for multiple values.
    #[builder(into)]
    pub department: Option<String>,

    /// Contracting office filter: a name, abbreviation or code, with `|` for multiple values.
    #[builder(into)]
    pub office: Option<String>,

    /// Escape hatch for filter keys not yet first-classed on this struct.
    #[builder(default)]
    pub extra: BTreeMap<String, String>,
}

impl ListNoticesOptions {
    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_bool(&mut q, "active", self.active);
        push_opt(&mut q, "agency", self.agency.as_deref());
        push_opt(&mut q, "naics", self.naics.as_deref());
        push_opt(&mut q, "notice_type", self.notice_type.as_deref());
        push_opt(
            &mut q,
            "posted_date_after",
            self.posted_date_after.as_deref(),
        );
        push_opt(
            &mut q,
            "posted_date_before",
            self.posted_date_before.as_deref(),
        );
        push_opt(&mut q, "psc", self.psc.as_deref());
        push_opt(
            &mut q,
            "response_deadline_after",
            self.response_deadline_after.as_deref(),
        );
        push_opt(
            &mut q,
            "response_deadline_before",
            self.response_deadline_before.as_deref(),
        );
        push_opt(&mut q, "search", self.search.as_deref());
        push_opt(&mut q, "office", self.office.as_deref());
        push_opt(&mut q, "department", self.department.as_deref());
        push_opt(&mut q, "notice_id", self.notice_id.as_deref());
        push_opt(&mut q, "set_aside", self.set_aside.as_deref());
        push_opt(
            &mut q,
            "solicitation_number",
            self.solicitation_number.as_deref(),
        );
        for (k, v) in &self.extra {
            if !v.is_empty() {
                q.push((k.clone(), v.clone()));
            }
        }
        q
    }
}

// ---------------------------------------------------------------------------
// Forecasts
// ---------------------------------------------------------------------------

/// Options for [`Client::list_forecasts`] and [`Client::iterate_forecasts`].
/// Mirrors `ListForecastsOptions` in the Go SDK.
#[derive(Debug, Clone, Default, Builder, PartialEq, Eq)]
#[non_exhaustive]
pub struct ListForecastsOptions {
    /// 1-based page number.
    #[builder(into)]
    pub page: Option<u32>,
    /// Page size.
    #[builder(into)]
    pub limit: Option<u32>,
    /// Keyset cursor.
    #[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,

    /// Awarding agency CGAC code.
    #[builder(into)]
    pub agency: Option<String>,
    /// Lower bound for award date.
    #[builder(into)]
    pub award_date_after: Option<String>,
    /// Upper bound for award date.
    #[builder(into)]
    pub award_date_before: Option<String>,
    /// `fiscal_year` filter.
    #[builder(into)]
    pub fiscal_year: Option<String>,
    /// Lower bound for `fiscal_year`.
    #[builder(into)]
    pub fiscal_year_gte: Option<String>,
    /// Upper bound for `fiscal_year`.
    #[builder(into)]
    pub fiscal_year_lte: Option<String>,
    /// Lower bound for last-modified timestamp.
    #[builder(into)]
    pub modified_after: Option<String>,
    /// Upper bound for last-modified timestamp.
    #[builder(into)]
    pub modified_before: Option<String>,
    /// NAICS code filter (exact).
    #[builder(into)]
    pub naics_code: Option<String>,
    /// NAICS prefix filter.
    #[builder(into)]
    pub naics_starts_with: Option<String>,
    /// Server-side sort spec.
    #[builder(into)]
    pub ordering: Option<String>,
    /// Free-text search filter.
    #[builder(into)]
    pub search: Option<String>,
    /// Source-system filter (e.g. `"SAM"`).
    #[builder(into)]
    pub source_system: Option<String>,
    /// Status filter (e.g. `"active"`).
    #[builder(into)]
    pub status: Option<String>,

    /// Forecast ID filter.
    #[builder(into)]
    pub id: Option<String>,

    /// Escape hatch for filter keys not yet first-classed on this struct.
    #[builder(default)]
    pub extra: BTreeMap<String, String>,
}

impl ListForecastsOptions {
    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, "agency", self.agency.as_deref());
        push_opt(&mut q, "award_date_after", self.award_date_after.as_deref());
        push_opt(
            &mut q,
            "award_date_before",
            self.award_date_before.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, "modified_after", self.modified_after.as_deref());
        push_opt(&mut q, "modified_before", self.modified_before.as_deref());
        push_opt(&mut q, "naics_code", self.naics_code.as_deref());
        push_opt(
            &mut q,
            "naics_starts_with",
            self.naics_starts_with.as_deref(),
        );
        push_opt(&mut q, "ordering", self.ordering.as_deref());
        push_opt(&mut q, "search", self.search.as_deref());
        push_opt(&mut q, "id", self.id.as_deref());
        push_opt(&mut q, "source_system", self.source_system.as_deref());
        push_opt(&mut q, "status", self.status.as_deref());
        for (k, v) in &self.extra {
            if !v.is_empty() {
                q.push((k.clone(), v.clone()));
            }
        }
        q
    }
}

// ---------------------------------------------------------------------------
// Grants
// ---------------------------------------------------------------------------

/// Options for [`Client::list_grants`] and [`Client::iterate_grants`].
/// Mirrors `ListGrantsOptions` in the Go SDK.
#[derive(Debug, Clone, Default, Builder, PartialEq, Eq)]
#[non_exhaustive]
pub struct ListGrantsOptions {
    /// 1-based page number.
    #[builder(into)]
    pub page: Option<u32>,
    /// Page size.
    #[builder(into)]
    pub limit: Option<u32>,
    /// Keyset cursor.
    #[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,

    /// Awarding agency filter.
    #[builder(into)]
    pub agency: Option<String>,
    /// Applicant-types filter (CSV of grants.gov codes).
    #[builder(into)]
    pub applicant_types: Option<String>,
    /// CFDA number filter.
    #[builder(into)]
    pub cfda_number: Option<String>,
    /// Grant identifier filter (exact match on `grant_id`).
    #[builder(into)]
    pub grant_id: Option<String>,
    /// Funding-categories filter (CSV).
    #[builder(into)]
    pub funding_categories: Option<String>,
    /// Funding-instruments filter (CSV).
    #[builder(into)]
    pub funding_instruments: Option<String>,
    /// Opportunity number filter.
    #[builder(into)]
    pub opportunity_number: Option<String>,
    /// Server-side sort spec.
    #[builder(into)]
    pub ordering: Option<String>,
    /// Lower bound for posted date.
    #[builder(into)]
    pub posted_date_after: Option<String>,
    /// Upper bound for posted date.
    #[builder(into)]
    pub posted_date_before: Option<String>,
    /// Lower bound for response date.
    #[builder(into)]
    pub response_date_after: Option<String>,
    /// Upper bound for response date.
    #[builder(into)]
    pub response_date_before: Option<String>,
    /// Free-text search filter.
    #[builder(into)]
    pub search: Option<String>,
    /// Status filter (e.g. `"posted"`).
    #[builder(into)]
    pub status: Option<String>,

    /// Escape hatch for filter keys not yet first-classed on this struct.
    #[builder(default)]
    pub extra: BTreeMap<String, String>,
}

impl ListGrantsOptions {
    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, "agency", self.agency.as_deref());
        push_opt(&mut q, "applicant_types", self.applicant_types.as_deref());
        push_opt(&mut q, "cfda_number", self.cfda_number.as_deref());
        push_opt(&mut q, "grant_id", self.grant_id.as_deref());
        push_opt(
            &mut q,
            "funding_categories",
            self.funding_categories.as_deref(),
        );
        push_opt(
            &mut q,
            "funding_instruments",
            self.funding_instruments.as_deref(),
        );
        push_opt(
            &mut q,
            "opportunity_number",
            self.opportunity_number.as_deref(),
        );
        push_opt(&mut q, "ordering", self.ordering.as_deref());
        push_opt(
            &mut q,
            "posted_date_after",
            self.posted_date_after.as_deref(),
        );
        push_opt(
            &mut q,
            "posted_date_before",
            self.posted_date_before.as_deref(),
        );
        push_opt(
            &mut q,
            "response_date_after",
            self.response_date_after.as_deref(),
        );
        push_opt(
            &mut q,
            "response_date_before",
            self.response_date_before.as_deref(),
        );
        push_opt(&mut q, "search", self.search.as_deref());
        push_opt(&mut q, "status", self.status.as_deref());
        for (k, v) in &self.extra {
            if !v.is_empty() {
                q.push((k.clone(), v.clone()));
            }
        }
        q
    }
}

// ---------------------------------------------------------------------------
// Client methods
// ---------------------------------------------------------------------------

impl Client {
    /// `GET /api/opportunities/` — one page of opportunity records.
    ///
    /// The shape leaves documented on [`get_opportunity`](Self::get_opportunity) (award fields, attachment counts, `attachments(extraction_status)`) are accepted on the list too.
    pub async fn list_opportunities(&self, opts: ListOpportunitiesOptions) -> Result<Page<Record>> {
        let q = opts.to_query();
        self.get_page("/api/opportunities/", &q).await
    }

    /// Stream every opportunity matching `opts`.
    pub fn iterate_opportunities(&self, opts: ListOpportunitiesOptions) -> 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_opportunities(next).await })
        });
        PageStream::new(self.clone(), fetch)
    }

    /// `GET /api/notices/` — one page of notice records.
    ///
    /// The shape leaves documented on [`get_notice`](Self::get_notice) are accepted on the list too.
    pub async fn list_notices(&self, opts: ListNoticesOptions) -> Result<Page<Record>> {
        let q = opts.to_query();
        self.get_page("/api/notices/", &q).await
    }

    /// Stream every notice matching `opts`.
    pub fn iterate_notices(&self, opts: ListNoticesOptions) -> 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_notices(next).await })
        });
        PageStream::new(self.clone(), fetch)
    }

    /// `GET /api/forecasts/` — one page of forecast records.
    pub async fn list_forecasts(&self, opts: ListForecastsOptions) -> Result<Page<Record>> {
        let q = opts.to_query();
        self.get_page("/api/forecasts/", &q).await
    }

    /// Stream every forecast matching `opts`.
    pub fn iterate_forecasts(&self, opts: ListForecastsOptions) -> 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_forecasts(next).await })
        });
        PageStream::new(self.clone(), fetch)
    }

    /// `GET /api/grants/` — one page of grant records.
    pub async fn list_grants(&self, opts: ListGrantsOptions) -> Result<Page<Record>> {
        let q = opts.to_query();
        self.get_page("/api/grants/", &q).await
    }

    /// Stream every grant matching `opts`.
    pub fn iterate_grants(&self, opts: ListGrantsOptions) -> 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_grants(next).await })
        });
        PageStream::new(self.clone(), fetch)
    }

    /// `GET /api/opportunities/{opportunity_id}/` — a single opportunity.
    ///
    /// None of the fields below is in the SDK's default shape, so name the ones you want.
    ///
    /// **Award fields** (Tango API 5.5.0): `awarded`, `award_date`, `award_amount`, `awardee`, `awardee_uei`, `award_count`, `solicitation_opportunity_id` and the `awards(opportunity_id,notice_id,award_number,award_date,award_amount,awardee,awardee_uei)` expand.
    /// `award_date`, `award_amount`, `awardee` and `awardee_uei` are filled only where SAM.gov posted an award notice, and `award_amount` is the text SAM.gov published, not a number.
    /// When an award is posted as its own opportunity and references its solicitation, the award's `solicitation_opportunity_id` points back to the solicitation, whose `awards(...)` lists up to ten of the most recent linked awards; `award_count` is the full count.
    /// `awarded` is true when the opportunity has an award of its own or has linked awards.
    ///
    /// **Attachment counts** (Tango API 5.9.0): `meta(attachments_count,files_count,links_count)`.
    /// A `file` is a document attached to the notice (only files have extracted text) and a `link` is a URL the notice lists; `meta.attachments_count` still counts every attachment, so files plus links need not equal it.
    /// `files_count` and `links_count` are null until the record has been counted: treat null as unknown, not zero.
    ///
    /// **`attachments(extraction_status)`** (Tango API 5.11.0) reports `pending`, `extracting`, `completed`, `failed` or `unsupported` for each attachment, which says why `extracted_text` is missing. It is available on every plan and returned only when named; `attachments(*)` does not carry it.
    ///
    /// ```text
    /// opportunity_id,title,awarded,award_count,awards(notice_id,award_date,awardee_uei),meta(files_count,links_count),attachments(name,extraction_status)
    /// ```
    pub async fn get_opportunity(
        &self,
        opportunity_id: &str,
        opts: Option<ListOptions>,
    ) -> Result<Record> {
        if opportunity_id.is_empty() {
            return Err(Error::Validation {
                message: "get_opportunity: opportunity_id is required".into(),
                response: None,
            });
        }
        let mut q = Vec::new();
        opts.unwrap_or_default().apply(&mut q);
        let path = format!("/api/opportunities/{}/", urlencoding(opportunity_id));
        self.get_json::<Record>(&path, &q).await
    }

    /// `GET /api/notices/{notice_id}/` — a single notice.
    ///
    /// None of the fields below is in the SDK's default shape, so name the ones you want.
    ///
    /// - **Award fields** (Tango API 5.5.0): `award_date`, `award_amount`, `awardee` and `awardee_uei`, filled only where the notice posted an award.
    /// - **Attachment counts** (Tango API 5.9.0): `file_count` and `link_count` beside `attachment_count`, which still counts every attachment, links included. The new counts are null until the record has been counted: treat null as unknown, not zero.
    /// - **`attachments(extraction_status)`** (Tango API 5.11.0): `pending`, `extracting`, `completed`, `failed` or `unsupported` per attachment, on every plan, returned only when named.
    pub async fn get_notice(&self, notice_id: &str, opts: Option<ListOptions>) -> Result<Record> {
        if notice_id.is_empty() {
            return Err(Error::Validation {
                message: "get_notice: notice_id is required".into(),
                response: None,
            });
        }
        let mut q = Vec::new();
        opts.unwrap_or_default().apply(&mut q);
        let path = format!("/api/notices/{}/", urlencoding(notice_id));
        self.get_json::<Record>(&path, &q).await
    }

    /// `GET /api/forecasts/{id}/` — a single procurement forecast.
    pub async fn get_forecast(&self, id: &str, opts: Option<ListOptions>) -> Result<Record> {
        if id.is_empty() {
            return Err(Error::Validation {
                message: "get_forecast: id is required".into(),
                response: None,
            });
        }
        let mut q = Vec::new();
        opts.unwrap_or_default().apply(&mut q);
        let path = format!("/api/forecasts/{}/", urlencoding(id));
        self.get_json::<Record>(&path, &q).await
    }

    /// `GET /api/grants/{grant_id}/` — a single grant opportunity.
    pub async fn get_grant(&self, grant_id: &str, opts: Option<ListOptions>) -> Result<Record> {
        if grant_id.is_empty() {
            return Err(Error::Validation {
                message: "get_grant: grant_id is required".into(),
                response: None,
            });
        }
        let mut q = Vec::new();
        opts.unwrap_or_default().apply(&mut q);
        let path = format!("/api/grants/{}/", urlencoding(grant_id));
        self.get_json::<Record>(&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 opportunities_emits_all_string_filters() {
        let opts = ListOpportunitiesOptions::builder()
            .active(true)
            .agency("9700")
            .first_notice_date_after("2024-01-01")
            .last_notice_date_before("2024-12-31")
            .naics("541512")
            .notice_type("PRESOL")
            .ordering("-response_deadline")
            .place_of_performance("VA")
            .psc("D302")
            .response_deadline_after("2024-01-15")
            .response_deadline_before("2024-03-31")
            .search("cloud computing")
            .set_aside("8A")
            .solicitation_number("W15P7T24R0001")
            .build();
        let q = opts.to_query();
        assert_eq!(get_q(&q, "active").as_deref(), Some("true"));
        assert_eq!(get_q(&q, "agency").as_deref(), Some("9700"));
        assert_eq!(
            get_q(&q, "first_notice_date_after").as_deref(),
            Some("2024-01-01")
        );
        assert_eq!(
            get_q(&q, "last_notice_date_before").as_deref(),
            Some("2024-12-31")
        );
        assert_eq!(get_q(&q, "naics").as_deref(), Some("541512"));
        assert_eq!(get_q(&q, "notice_type").as_deref(), Some("PRESOL"));
        assert_eq!(get_q(&q, "ordering").as_deref(), Some("-response_deadline"));
        assert_eq!(get_q(&q, "place_of_performance").as_deref(), Some("VA"));
        assert_eq!(get_q(&q, "psc").as_deref(), Some("D302"));
        assert_eq!(get_q(&q, "search").as_deref(), Some("cloud computing"));
        assert_eq!(get_q(&q, "set_aside").as_deref(), Some("8A"));
        assert_eq!(
            get_q(&q, "solicitation_number").as_deref(),
            Some("W15P7T24R0001")
        );
    }

    #[test]
    fn opportunities_active_false_emits_false() {
        let opts = ListOpportunitiesOptions::builder().active(false).build();
        let q = opts.to_query();
        assert_eq!(get_q(&q, "active").as_deref(), Some("false"));
    }

    #[test]
    fn opportunities_award_filters_emit() {
        let q = ListOpportunitiesOptions::builder()
            .awarded(false)
            .awardee_uei("ABCDEF123456|ZYXWVU654321")
            .build()
            .to_query();
        assert_eq!(get_q(&q, "awarded").as_deref(), Some("false"));
        assert_eq!(
            get_q(&q, "awardee_uei").as_deref(),
            Some("ABCDEF123456|ZYXWVU654321")
        );
        let q = ListOpportunitiesOptions::default().to_query();
        assert!(!q.iter().any(|(k, _)| k == "awarded" || k == "awardee_uei"));
    }

    #[test]
    fn opportunities_active_none_omits() {
        let opts = ListOpportunitiesOptions::default();
        let q = opts.to_query();
        assert!(!q.iter().any(|(k, _)| k == "active"));
    }

    #[test]
    fn notices_emits_filters_without_ordering_field() {
        let opts = ListNoticesOptions::builder()
            .active(true)
            .agency("9700")
            .naics("541512")
            .notice_type("AWARD")
            .posted_date_after("2024-01-01")
            .posted_date_before("2024-12-31")
            .search("cybersecurity")
            .build();
        let q = opts.to_query();
        assert_eq!(get_q(&q, "active").as_deref(), Some("true"));
        assert_eq!(get_q(&q, "agency").as_deref(), Some("9700"));
        assert_eq!(get_q(&q, "notice_type").as_deref(), Some("AWARD"));
        assert_eq!(get_q(&q, "search").as_deref(), Some("cybersecurity"));
    }

    #[test]
    fn forecasts_emits_all_filters() {
        let opts = ListForecastsOptions::builder()
            .agency("9700")
            .fiscal_year("2024")
            .fiscal_year_gte("2023")
            .fiscal_year_lte("2025")
            .naics_code("541512")
            .naics_starts_with("5415")
            .ordering("award_date")
            .source_system("SAM")
            .status("active")
            .build();
        let q = opts.to_query();
        assert_eq!(get_q(&q, "agency").as_deref(), Some("9700"));
        assert_eq!(get_q(&q, "fiscal_year").as_deref(), Some("2024"));
        assert_eq!(get_q(&q, "naics_starts_with").as_deref(), Some("5415"));
        assert_eq!(get_q(&q, "source_system").as_deref(), Some("SAM"));
        assert_eq!(get_q(&q, "status").as_deref(), Some("active"));
    }

    #[test]
    fn grants_emits_all_filters() {
        let opts = ListGrantsOptions::builder()
            .agency("9700")
            .applicant_types("11")
            .cfda_number("10.001")
            .grant_id("GRANT-123")
            .funding_categories("AR")
            .funding_instruments("G")
            .opportunity_number("OPP-001")
            .ordering("response_date")
            .posted_date_after("2024-01-01")
            .response_date_before("2024-11-30")
            .search("environment")
            .status("posted")
            .build();
        let q = opts.to_query();
        assert_eq!(get_q(&q, "applicant_types").as_deref(), Some("11"));
        assert_eq!(get_q(&q, "cfda_number").as_deref(), Some("10.001"));
        assert_eq!(get_q(&q, "grant_id").as_deref(), Some("GRANT-123"));
        assert_eq!(get_q(&q, "funding_categories").as_deref(), Some("AR"));
        assert_eq!(get_q(&q, "funding_instruments").as_deref(), Some("G"));
        assert_eq!(get_q(&q, "opportunity_number").as_deref(), Some("OPP-001"));
        assert_eq!(get_q(&q, "status").as_deref(), Some("posted"));
    }

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

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

    #[tokio::test]
    async fn get_forecast_empty_key_returns_validation() {
        let client = Client::builder().api_key("x").build().expect("build");
        let err = client.get_forecast("", 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_notice_empty_key_returns_validation() {
        let client = Client::builder().api_key("x").build().expect("build");
        let err = client.get_notice("", None).await.expect_err("must error");
        match err {
            Error::Validation { message, .. } => assert!(message.contains("notice_id")),
            other => panic!("expected Validation, got {other:?}"),
        }
    }

    #[test]
    fn identifier_and_org_filters_emit() {
        let q = ListNoticesOptions::builder()
            .notice_id("n1")
            .department("DOD")
            .office("W912")
            .build()
            .to_query();
        assert_eq!(get_q(&q, "notice_id").as_deref(), Some("n1"));
        assert_eq!(get_q(&q, "department").as_deref(), Some("DOD"));
        assert_eq!(get_q(&q, "office").as_deref(), Some("W912"));
        let q = ListOpportunitiesOptions::builder()
            .opportunity_id("o1")
            .build()
            .to_query();
        assert_eq!(get_q(&q, "opportunity_id").as_deref(), Some("o1"));
        let q = ListForecastsOptions::builder().id("42").build().to_query();
        assert_eq!(get_q(&q, "id").as_deref(), Some("42"));
    }
}