delopay 0.20.0

Official Rust SDK for the DeloPay payments 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
//! The `export` resource: emit a list as a file.
//!
//! Every method here mirrors one list endpoint and takes **that list's own
//! filters**, unchanged — there is no second filter vocabulary for exports, so
//! a file cannot disagree with the list that produced it. The shop scope is
//! resolved the same way too: a shop-scoped token exports its own shop, and
//! naming another is refused rather than ignored.
//!
//! Every export is **one read, never a paged walk**, and is bounded at 25 000
//! rows — 500 for a PDF, which is a document rather than a data feed. Over the
//! bound the request is refused with `DE_07 export_row_limit_exceeded` carrying
//! the entity and the limit, never a short file with a `200`.
//!
//! # Format
//!
//! The format is an `Accept` header, not a request field. The API negotiates it
//! that way because an export reuses its list's filter model as literally the
//! same type, and several of those refuse unknown fields — so a `format` key in
//! the body would be a `400` rather than an option.
//!
//! Each entity therefore has two methods: the plain one answers the typed
//! [`ExportEnvelope`], and the `*_file` one asks for
//! [`ExportFormat::Csv`] or [`ExportFormat::Pdf`] and answers the bytes
//! verbatim.

use std::sync::Arc;

use serde::Serialize;
use serde_json::Value;

use crate::core::encoding::to_json_vec;
use crate::core::error::{DelopayError, Result};
use crate::core::models::export::{
    DisputeExportRecord, ExportEnvelope, MerchantAuditLogExportRecord, PayoutExportRecord,
    RefundExportRecord, SubscriptionExportRecord, TransactionExportRecord,
    TransactionLineExportRecord,
};
use crate::http::client::{Inner, KeyPolicy};
use crate::http::transport::HttpMethod;
use crate::resources::audit::MerchantAuditLogListParams;
use crate::resources::disputes::DisputeListParams;
use crate::resources::subscriptions::SubscriptionListParams;

/// Which representation an export is asked for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ExportFormat {
    /// A typed [`ExportEnvelope`]. The default.
    #[default]
    Json,
    /// Comma-separated rows.
    Csv,
    /// A rendered document. Bounded at 500 rows rather than 25 000.
    Pdf,
}

impl ExportFormat {
    /// The media type this format is asked for by name.
    pub fn accept(self) -> &'static str {
        match self {
            Self::Json => "application/json",
            Self::Csv => "text/csv",
            Self::Pdf => "application/pdf",
        }
    }
}

/// The `export` resource, obtained via [`crate::Delopay::export`].
#[derive(Debug, Clone)]
pub struct Export {
    inner: Arc<Inner>,
    /// The encoded PDF presentation, sent only with [`ExportFormat::Pdf`].
    presentation: Option<String>,
}

/// The longest encoded PDF presentation the API reads, in bytes.
pub const MAX_EXPORT_PRESENTATION_BYTES: usize = 6 * 1024;

/// The header a PDF export's words travel in.
const PRESENTATION_HEADER: &str = "x-delopay-export-presentation";

impl Export {
    pub(crate) fn new(inner: Arc<Inner>) -> Self {
        Self {
            inner,
            presentation: None,
        }
    }

    /// This resource with the words a **PDF** export prints in: its title,
    /// filter list, column labels, separators and the report's own words.
    /// A CSV or JSON export is unaffected.
    ///
    /// `presentation` is the presentation object as the API reference
    /// describes it (`title`, `filters_heading`, `filters`, `no_filters`,
    /// `no_rows`, `row_count`, `page`, and the optional `subtitle`,
    /// `columns`, `decimal_separator`, `thousands_separator`, `yes`, `no`,
    /// `words` and value labels). It travels as unpadded base64url JSON in
    /// the `X-Delopay-Export-Presentation` header; one longer than
    /// [`MAX_EXPORT_PRESENTATION_BYTES`] encoded is refused here, before
    /// anything is sent.
    pub fn with_presentation(&self, presentation: &Value) -> Result<Self> {
        let json = to_json_vec(presentation)?;
        let encoded = base64url_unpadded(&json);
        if encoded.len() > MAX_EXPORT_PRESENTATION_BYTES {
            return Err(DelopayError::InvalidRequest(format!(
                "the export presentation is {} bytes encoded; the API reads at most \
                 {MAX_EXPORT_PRESENTATION_BYTES}",
                encoded.len()
            )));
        }
        Ok(Self {
            inner: self.inner.clone(),
            presentation: Some(encoded),
        })
    }

    /// The headers of a file request: `Accept`, plus the presentation for a
    /// PDF when one is set.
    fn file_headers(&self, format: ExportFormat) -> Vec<(&'static str, &str)> {
        let mut headers = vec![("accept", format.accept())];
        if format == ExportFormat::Pdf
            && let Some(presentation) = &self.presentation
        {
            headers.push((PRESENTATION_HEADER, presentation.as_str()));
        }
        headers
    }

    /// Export transactions, taking the payment list's own filter body (all
    /// fields optional; `limit` and `offset` are ignored, the export is one
    /// bounded read). `None` exports every payment the caller can see.
    ///
    /// The format travels only in `Accept`; the body carries no `format`.
    ///
    /// `POST /export/transactions`
    pub async fn transactions(
        &self,
        filters: Option<&Value>,
    ) -> Result<ExportEnvelope<TransactionExportRecord>> {
        self.post_json("/export/transactions", &filters_or_empty(filters))
            .await
    }

    /// [`transactions`](Self::transactions) as a CSV or PDF file.
    pub async fn transactions_file(
        &self,
        filters: Option<&Value>,
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        self.post_file("/export/transactions", &filters_or_empty(filters), format)
            .await
    }

    /// Export the caller's own shop's transactions, taking the shop payment
    /// list's own filter body.
    ///
    /// Gated on the profile-level payment permission, which a shop-scoped role
    /// can hold where the merchant-level one it replaces cannot.
    ///
    /// `POST /export/profile/transactions`
    pub async fn transactions_for_profile(
        &self,
        filters: Option<&Value>,
    ) -> Result<ExportEnvelope<TransactionExportRecord>> {
        self.post_json("/export/profile/transactions", &filters_or_empty(filters))
            .await
    }

    /// [`transactions_for_profile`](Self::transactions_for_profile) as a file.
    pub async fn transactions_for_profile_file(
        &self,
        filters: Option<&Value>,
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        self.post_file(
            "/export/profile/transactions",
            &filters_or_empty(filters),
            format,
        )
        .await
    }

    /// Export transactions one row per product line, taking the payment
    /// list's own filter body.
    ///
    /// The payments [`transactions`](Self::transactions) would export for the
    /// same filters, one row per product line they recorded, plus one
    /// `row_kind: "no_lines"` row for each payment that recorded none. The
    /// row bound applies to the rows.
    ///
    /// `POST /export/transactions/lines`
    pub async fn transaction_lines(
        &self,
        filters: Option<&Value>,
    ) -> Result<ExportEnvelope<TransactionLineExportRecord>> {
        self.post_json_unkeyed("/export/transactions/lines", &filters_or_empty(filters))
            .await
    }

    /// [`transaction_lines`](Self::transaction_lines) as a CSV file. A line
    /// export has no PDF form: [`ExportFormat::Pdf`] is refused before
    /// anything is sent.
    pub async fn transaction_lines_file(
        &self,
        filters: Option<&Value>,
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        refuse_pdf(format)?;
        self.post_file_unkeyed(
            "/export/transactions/lines",
            &filters_or_empty(filters),
            format,
        )
        .await
    }

    /// Export the caller's own shop's transactions one row per product line,
    /// scoped as [`transactions_for_profile`](Self::transactions_for_profile)
    /// is: to the shop on the token.
    ///
    /// `POST /export/profile/transactions/lines`
    pub async fn transaction_lines_for_profile(
        &self,
        filters: Option<&Value>,
    ) -> Result<ExportEnvelope<TransactionLineExportRecord>> {
        self.post_json_unkeyed(
            "/export/profile/transactions/lines",
            &filters_or_empty(filters),
        )
        .await
    }

    /// [`transaction_lines_for_profile`](Self::transaction_lines_for_profile)
    /// as a CSV file. [`ExportFormat::Pdf`] is refused before anything is
    /// sent.
    pub async fn transaction_lines_for_profile_file(
        &self,
        filters: Option<&Value>,
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        refuse_pdf(format)?;
        self.post_file_unkeyed(
            "/export/profile/transactions/lines",
            &filters_or_empty(filters),
            format,
        )
        .await
    }

    /// Export refunds, taking the refund list's own filter body.
    ///
    /// `POST /refunds/list/export`
    pub async fn refunds(
        &self,
        filters: Option<&Value>,
    ) -> Result<ExportEnvelope<RefundExportRecord>> {
        self.post_json("/refunds/list/export", &filters_or_empty(filters))
            .await
    }

    /// [`refunds`](Self::refunds) as a file.
    pub async fn refunds_file(
        &self,
        filters: Option<&Value>,
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        self.post_file("/refunds/list/export", &filters_or_empty(filters), format)
            .await
    }

    /// Export the caller's own shop's refunds.
    ///
    /// `POST /refunds/profile/list/export`
    pub async fn refunds_for_profile(
        &self,
        filters: Option<&Value>,
    ) -> Result<ExportEnvelope<RefundExportRecord>> {
        self.post_json("/refunds/profile/list/export", &filters_or_empty(filters))
            .await
    }

    /// [`refunds_for_profile`](Self::refunds_for_profile) as a file.
    pub async fn refunds_for_profile_file(
        &self,
        filters: Option<&Value>,
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        self.post_file(
            "/refunds/profile/list/export",
            &filters_or_empty(filters),
            format,
        )
        .await
    }

    /// Export payouts, taking the payout list's own filter body.
    ///
    /// `POST /payouts/list/export`
    pub async fn payouts(
        &self,
        filters: Option<&Value>,
    ) -> Result<ExportEnvelope<PayoutExportRecord>> {
        self.post_json("/payouts/list/export", &filters_or_empty(filters))
            .await
    }

    /// [`payouts`](Self::payouts) as a file.
    pub async fn payouts_file(
        &self,
        filters: Option<&Value>,
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        self.post_file("/payouts/list/export", &filters_or_empty(filters), format)
            .await
    }

    /// Export the caller's own shop's payouts.
    ///
    /// `POST /payouts/profile/list/export`
    pub async fn payouts_for_profile(
        &self,
        filters: Option<&Value>,
    ) -> Result<ExportEnvelope<PayoutExportRecord>> {
        self.post_json("/payouts/profile/list/export", &filters_or_empty(filters))
            .await
    }

    /// [`payouts_for_profile`](Self::payouts_for_profile) as a file.
    pub async fn payouts_for_profile_file(
        &self,
        filters: Option<&Value>,
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        self.post_file(
            "/payouts/profile/list/export",
            &filters_or_empty(filters),
            format,
        )
        .await
    }

    /// Export disputes, taking the dispute list's own query filters.
    ///
    /// `GET /disputes/list/export`
    pub async fn disputes(
        &self,
        params: Option<&DisputeListParams>,
    ) -> Result<ExportEnvelope<DisputeExportRecord>> {
        let query = params.map(DisputeListParams::to_query).unwrap_or_default();
        self.get_json("/disputes/list/export", &query).await
    }

    /// [`disputes`](Self::disputes) as a file.
    pub async fn disputes_file(
        &self,
        params: Option<&DisputeListParams>,
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        let query = params.map(DisputeListParams::to_query).unwrap_or_default();
        self.get_file("/disputes/list/export", &query, format).await
    }

    /// Export the caller's own shop's disputes.
    ///
    /// `GET /disputes/profile/list/export`
    pub async fn disputes_for_profile(
        &self,
        params: Option<&DisputeListParams>,
    ) -> Result<ExportEnvelope<DisputeExportRecord>> {
        let query = params.map(DisputeListParams::to_query).unwrap_or_default();
        self.get_json("/disputes/profile/list/export", &query).await
    }

    /// [`disputes_for_profile`](Self::disputes_for_profile) as a file.
    pub async fn disputes_for_profile_file(
        &self,
        params: Option<&DisputeListParams>,
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        let query = params.map(DisputeListParams::to_query).unwrap_or_default();
        self.get_file("/disputes/profile/list/export", &query, format)
            .await
    }

    /// Export one shop's subscriptions, taking the subscription list's own
    /// filters.
    ///
    /// Subscription routes are profile-scoped: `profile_id` travels as the
    /// `x-profile-id` header the route requires, and the rest of the filter —
    /// `limit`, `offset`, `test_mode` — travels on the query exactly as the
    /// list takes it.
    ///
    /// `GET /subscriptions/list/export`
    pub async fn subscriptions(
        &self,
        profile_id: &str,
        params: Option<&SubscriptionListParams>,
    ) -> Result<ExportEnvelope<SubscriptionExportRecord>> {
        let query = params
            .map(SubscriptionListParams::to_query)
            .unwrap_or_default();
        self.inner
            .request_with_headers(
                HttpMethod::Get,
                "/subscriptions/list/export",
                None,
                &query,
                None,
                &[
                    ("x-profile-id", profile_id),
                    ("accept", ExportFormat::Json.accept()),
                ],
            )
            .await
    }

    /// [`subscriptions`](Self::subscriptions) as a file.
    pub async fn subscriptions_file(
        &self,
        profile_id: &str,
        params: Option<&SubscriptionListParams>,
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        let query = params
            .map(SubscriptionListParams::to_query)
            .unwrap_or_default();
        let mut headers = self.file_headers(format);
        headers.push(("x-profile-id", profile_id));
        self.inner
            .send_raw(
                HttpMethod::Get,
                "/subscriptions/list/export",
                None,
                &query,
                None,
                &headers,
                None,
            )
            .await
    }

    /// Export the merchant's own audit log, taking the audit list's own query
    /// filters.
    ///
    /// `GET /audit/export`
    pub async fn audit_log(
        &self,
        params: Option<&MerchantAuditLogListParams>,
    ) -> Result<ExportEnvelope<MerchantAuditLogExportRecord>> {
        let query = params
            .map(MerchantAuditLogListParams::to_query)
            .unwrap_or_default();
        self.get_json("/audit/export", &query).await
    }

    /// [`audit_log`](Self::audit_log) as a file.
    pub async fn audit_log_file(
        &self,
        params: Option<&MerchantAuditLogListParams>,
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        let query = params
            .map(MerchantAuditLogListParams::to_query)
            .unwrap_or_default();
        self.get_file("/audit/export", &query, format).await
    }

    async fn post_json<B: Serialize, T: serde::de::DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        let bytes = to_json_vec(body)?;
        self.inner
            .request_with_headers(
                HttpMethod::Post,
                path,
                Some(&bytes),
                &[],
                None,
                &[("accept", ExportFormat::Json.accept())],
            )
            .await
    }

    async fn post_file<B: Serialize>(
        &self,
        path: &str,
        body: &B,
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        let bytes = to_json_vec(body)?;
        self.inner
            .send_raw(
                HttpMethod::Post,
                path,
                Some(&bytes),
                &[],
                None,
                &self.file_headers(format),
                None,
            )
            .await
    }

    /// [`post_json`](Self::post_json) for an export this crate added after
    /// the client-wide idempotency key existed: it never carries that key, so
    /// it is not replayed on a network error or a 5xx.
    async fn post_json_unkeyed<B: Serialize, T: serde::de::DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        let bytes = to_json_vec(body)?;
        self.inner
            .request_body_keyed_with_query_and_headers(
                HttpMethod::Post,
                path,
                Some(&bytes),
                &[],
                &[("accept", ExportFormat::Json.accept())],
                None,
            )
            .await
    }

    /// [`post_file`](Self::post_file) without the client-wide idempotency
    /// key, as [`post_json_unkeyed`](Self::post_json_unkeyed).
    async fn post_file_unkeyed<B: Serialize>(
        &self,
        path: &str,
        body: &B,
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        let bytes = to_json_vec(body)?;
        self.inner
            .send_raw_keyed(
                HttpMethod::Post,
                path,
                Some(&bytes),
                &[],
                None,
                KeyPolicy::BodyKeyOnly,
                &self.file_headers(format),
                None,
            )
            .await
    }

    async fn get_json<T: serde::de::DeserializeOwned>(
        &self,
        path: &str,
        query: &[(&str, String)],
    ) -> Result<T> {
        self.inner
            .request_with_headers(
                HttpMethod::Get,
                path,
                None,
                query,
                None,
                &[("accept", ExportFormat::Json.accept())],
            )
            .await
    }

    async fn get_file(
        &self,
        path: &str,
        query: &[(&str, String)],
        format: ExportFormat,
    ) -> Result<Vec<u8>> {
        self.inner
            .send_raw(
                HttpMethod::Get,
                path,
                None,
                query,
                None,
                &self.file_headers(format),
                None,
            )
            .await
    }
}

/// Unpadded base64url (RFC 4648 §5) of `bytes`.
fn base64url_unpadded(bytes: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let b = [
            chunk[0],
            chunk.get(1).copied().unwrap_or(0),
            chunk.get(2).copied().unwrap_or(0),
        ];
        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
        let chars = chunk.len() + 1;
        for i in 0..chars {
            let index = (n >> (18 - 6 * i)) & 0x3f;
            out.push(char::from(ALPHABET[index as usize]));
        }
    }
    out
}

/// A line export has no PDF form; the API would answer 422.
fn refuse_pdf(format: ExportFormat) -> Result<()> {
    if format == ExportFormat::Pdf {
        return Err(DelopayError::InvalidRequest(
            "a transaction line export is CSV or JSON only; it has no PDF form".to_owned(),
        ));
    }
    Ok(())
}

fn filters_or_empty(filters: Option<&Value>) -> Value {
    filters
        .cloned()
        .unwrap_or_else(|| Value::Object(Default::default()))
}

#[cfg(test)]
mod tests {
    use super::{
        DelopayError, ExportFormat, MAX_EXPORT_PRESENTATION_BYTES, SubscriptionListParams,
        base64url_unpadded,
    };
    use crate::http::mock::{Step, client_with, client_with_retries};
    use serde_json::json;

    /// RFC 4648 test vectors, in the URL-safe alphabet without padding.
    /// Mutation: emit `+`/`/` or pad with `=` — an assertion fails.
    #[test]
    fn base64url_unpadded_matches_the_rfc_vectors() {
        assert_eq!(base64url_unpadded(b""), "");
        assert_eq!(base64url_unpadded(b"f"), "Zg");
        assert_eq!(base64url_unpadded(b"fo"), "Zm8");
        assert_eq!(base64url_unpadded(b"foo"), "Zm9v");
        assert_eq!(base64url_unpadded(b"foobar"), "Zm9vYmFy");
        assert_eq!(base64url_unpadded(&[0xfb, 0xff]), "-_8");
    }

    /// The presentation rides only on a PDF. Mutation: drop the format check
    /// in `file_headers` — the CSV request carries the header and fails.
    #[tokio::test]
    async fn the_presentation_header_is_sent_with_pdf_files_only() {
        let (client, mock) =
            client_with(vec![Step::ok("%PDF"), Step::ok("a,b\n"), Step::ok("%PDF")]);
        let presentation = json!({"title": "Ä", "filters_heading": "Filter", "filters": [],
            "no_filters": "-", "no_rows": "-", "row_count": "{count}", "page": "{page}"});
        let export = client.export().with_presentation(&presentation).unwrap();
        export
            .transactions_file(None, ExportFormat::Pdf)
            .await
            .unwrap();
        export
            .transactions_file(None, ExportFormat::Csv)
            .await
            .unwrap();
        export.disputes_file(None, ExportFormat::Pdf).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        let expected = base64url_unpadded(&serde_json::to_vec(&presentation).unwrap());
        assert_eq!(
            seen[0].header("x-delopay-export-presentation"),
            Some(expected.as_str())
        );
        assert_eq!(seen[0].header("accept"), Some("application/pdf"));
        assert_eq!(seen[1].header("x-delopay-export-presentation"), None);
        assert_eq!(seen[2].method, "GET");
        assert_eq!(
            seen[2].header("x-delopay-export-presentation"),
            Some(expected.as_str())
        );
        assert_eq!(seen[2].header("accept"), Some("application/pdf"));
    }

    #[tokio::test]
    async fn an_oversized_presentation_is_refused_before_sending() {
        let (client, _mock) = client_with(vec![]);
        let huge = json!({"title": "x".repeat(MAX_EXPORT_PRESENTATION_BYTES)});
        assert!(matches!(
            client.export().with_presentation(&huge),
            Err(DelopayError::InvalidRequest(_))
        ));
    }

    const LINE_ROWS_JSON: &str = r#"{
        "records": [
            {
                "payment_id": "pay_1", "merchant_id": "mer_1", "shop_id": "pro_1",
                "created_at": "2026-09-01T00:00:00Z", "status": "succeeded", "test_mode": false,
                "payment_amount": 1500, "payment_currency": "EUR", "row_kind": "line",
                "line_id": "pli_1", "position": 0, "parent_line_id": null, "line_role": "product",
                "product_id": "prod_1", "product_name": "Hat", "product_alias": null,
                "attributed": true, "quantity": 2, "unit_amount": 750, "line_total": 1500,
                "currency": "EUR", "tax_rate": 19.0, "tax_amount": null, "surprise_field": 1
            },
            {
                "payment_id": "pay_2", "merchant_id": "mer_1", "shop_id": "pro_1",
                "created_at": null, "status": "failed", "test_mode": null,
                "payment_amount": 900, "payment_currency": "EUR", "row_kind": "no_lines",
                "line_id": null, "position": null, "parent_line_id": null, "line_role": null,
                "product_id": null, "product_name": null, "product_alias": null,
                "attributed": false, "quantity": null, "unit_amount": null, "line_total": null,
                "currency": null, "tax_rate": null, "tax_amount": null
            }
        ],
        "record_count": 2,
        "filters": {}
    }"#;

    #[tokio::test]
    async fn transaction_lines_posts_the_list_filters_and_asks_for_json() {
        let (client, mock) = client_with(vec![Step::ok(LINE_ROWS_JSON)]);
        let filters = json!({"currency": ["EUR"], "limit": 100});
        let out = client
            .export()
            .transaction_lines(Some(&filters))
            .await
            .unwrap();
        assert_eq!(out.record_count, Some(2));
        let line = &out.records[0];
        assert_eq!(line.row_kind, "line");
        assert_eq!(line.quantity, Some(2));
        assert_eq!(line.tax_rate, Some(19.0));
        assert!(line.tax_amount.is_none());
        assert_eq!(line.extra["surprise_field"], 1);
        let no_lines = &out.records[1];
        assert_eq!(no_lines.row_kind, "no_lines");
        assert!(!no_lines.attributed);
        assert!(no_lines.test_mode.is_none());

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/export/transactions/lines");
        assert_eq!(seen[0].body_json(), filters);
        assert_eq!(seen[0].header("accept"), Some("application/json"));
    }

    #[tokio::test]
    async fn transaction_lines_for_profile_file_asks_for_csv_on_the_profile_path() {
        let (client, mock) = client_with(vec![Step::ok(
            "payment_id,row_kind
pay_1,line
",
        )]);
        let out = client
            .export()
            .transaction_lines_for_profile_file(None, ExportFormat::Csv)
            .await
            .unwrap();
        assert_eq!(
            out,
            b"payment_id,row_kind
pay_1,line
"
        );

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/export/profile/transactions/lines"
        );
        // No filters is an empty object, not a missing body.
        assert_eq!(seen[0].body_json(), json!({}));
        assert_eq!(seen[0].header("accept"), Some("text/csv"));
    }

    #[tokio::test]
    async fn transaction_lines_for_profile_posts_to_the_profile_path() {
        let (client, mock) = client_with(vec![Step::ok(LINE_ROWS_JSON)]);
        client
            .export()
            .transaction_lines_for_profile(None)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/export/profile/transactions/lines"
        );
        assert_eq!(seen[0].header("accept"), Some("application/json"));
    }

    #[tokio::test]
    async fn transaction_lines_file_posts_csv_and_refuses_pdf_before_sending() {
        let (client, mock) = client_with(vec![Step::ok(
            "payment_id
pay_1
",
        )]);
        let export = client.export();
        let csv = export
            .transaction_lines_file(None, ExportFormat::Csv)
            .await
            .unwrap();
        assert_eq!(
            csv,
            b"payment_id
pay_1
"
        );
        assert!(matches!(
            export.transaction_lines_file(None, ExportFormat::Pdf).await,
            Err(DelopayError::InvalidRequest(_))
        ));
        assert!(matches!(
            export
                .transaction_lines_for_profile_file(None, ExportFormat::Pdf)
                .await,
            Err(DelopayError::InvalidRequest(_))
        ));

        let seen = mock.seen.lock().unwrap();
        // Only the CSV request reached the wire.
        assert_eq!(seen.len(), 1);
        assert_eq!(seen[0].url, "https://api.test/export/transactions/lines");
        assert_eq!(seen[0].header("accept"), Some("text/csv"));
    }

    /// The format is negotiated with `Accept` and the body is the list
    /// filter verbatim, with no `format` key. Mutation: drop the `accept`
    /// header from `post_json`, or add `format` to the body — an assertion
    /// fails.
    #[tokio::test]
    async fn transactions_posts_the_list_filter_and_asks_for_json() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"records":[{"payment_id":"pay_1","amount":500,"test_mode":false,"connector_settlement_status":"paid_out"}],"record_count":1,"filters":{}}"#,
        )]);
        let filters = json!({"profile_id": ["pro_1"], "start_time": "2026-09-01T00:00:00Z"});
        let out = client.export().transactions(Some(&filters)).await.unwrap();

        assert_eq!(out.record_count, Some(1));
        assert_eq!(out.records[0].payment_id, "pay_1");
        assert_eq!(out.records[0].test_mode, Some(false));
        assert_eq!(
            out.records[0].connector_settlement_status.as_deref(),
            Some("paid_out")
        );

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/export/transactions");
        assert_eq!(seen[0].body_json(), filters);
        assert_eq!(seen[0].header("accept"), Some("application/json"));
    }

    /// A CSV export must ask for `text/csv` and hand back the bytes unparsed.
    /// Mutation: make `post_file` decode as JSON, or send
    /// `ExportFormat::Json.accept()` — the body assertion, then the header
    /// assertion, go red.
    #[tokio::test]
    async fn transactions_file_asks_for_csv_and_returns_bytes() {
        let (client, mock) = client_with(vec![
            Step::ok("payment_id,amount\npay_1,500\n"),
            Step::ok("payment_id\n"),
        ]);
        let export = client.export();
        let out = export
            .transactions_file(None, ExportFormat::Csv)
            .await
            .unwrap();
        assert_eq!(out, b"payment_id,amount\npay_1,500\n");
        export
            .transactions_for_profile_file(None, ExportFormat::Pdf)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].header("accept"), Some("text/csv"));
        // No filter is an empty object, and the format is never on the body.
        assert_eq!(seen[0].body_json(), json!({}));
        assert_eq!(seen[1].url, "https://api.test/export/profile/transactions");
        assert_eq!(seen[1].header("accept"), Some("application/pdf"));
        assert_eq!(seen[1].body_json(), json!({}));
    }

    /// The subscription export is profile-scoped by header. Mutation: drop the
    /// `x-profile-id` header — the header assertion fails.
    #[tokio::test]
    async fn subscriptions_export_scopes_by_profile_header() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"records":[],"record_count":0}"#)]);
        client
            .export()
            .subscriptions(
                "pro_1",
                Some(&SubscriptionListParams {
                    limit: Some(50),
                    offset: Some(100),
                    test_mode: Some(true),
                }),
            )
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        // The export reuses the list's filter vocabulary, paging included — a
        // file that could not be paged would disagree with the list it came
        // from.
        assert_eq!(
            seen[0].url,
            "https://api.test/subscriptions/list/export?limit=50&offset=100&test_mode=true"
        );
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
    }

    /// A transaction line export never carries an idempotency key, not even the
    /// client-wide one, so a 5xx is not replayed. Mutation: switch a call
    /// site back to `request(.., None)` — the header appears and the call
    /// count grows.
    #[tokio::test]
    async fn line_exports_ignore_the_client_wide_idempotency_key() {
        let (client, mock) = client_with_retries(
            vec![
                Step::status(503, "{}"),
                Step::status(503, "{}"),
                Step::ok("{}"),
            ],
            2,
        );
        let export = client.with_idempotency_key("client-key").export();
        assert!(export.transaction_lines(None).await.is_err());
        assert!(
            export
                .transaction_lines_for_profile_file(None, ExportFormat::Csv)
                .await
                .is_err()
        );
        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen.len(), 2);
        assert!(seen.iter().all(|step| !step.had_idempotency_key()));
        assert_eq!(seen[1].header("accept"), Some("text/csv"));
    }
}