delopay 0.7.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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
//! The `settlement` resource: hosted-shop settlement — monthly statements,
//! the live current-period rollup, per-line detail, fee configuration,
//! backfills, and the host's manual positions.
//!
//! This is the "who is owed what" layer for a merchant that hosts shops on
//! behalf of third-party owners. It is deliberately independent of the
//! prepaid platform-fee ledger: a settlement figure is what the *host* owes a
//! *shop owner*, not what DeloPay charged the host.
//!
//! # `test_mode` is in every read signature, not a default
//!
//! Test and live figures must never blend, so the environment is an argument
//! the caller has to answer rather than something with a convenient default.
//! `false` is transmitted, not dropped.
//!
//! ```no_run
//! # use delopay::Delopay;
//! # async fn run(client: Delopay) -> delopay::Result<()> {
//! let overview = client.settlement().overview(false).await?;
//! for shop in &overview.shops {
//!     println!("{}: {} unpaid", shop.profile_id, shop.unpaid_net_usd);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # Who can call what
//!
//! Reads need `ProfileSettlementRead`; shop-owner callers are pinned to their
//! own shop server-side, and a host can hide a shop's settlement from its
//! owner entirely. The host actions — [`generate_statement`], [`backfill`],
//! [`update_statement_payout`], [`set_shop_visibility`] and the adjustment
//! calls — need `MerchantSettlementWrite`.
//!
//! [`generate_statement`]: Settlement::generate_statement
//! [`backfill`]: Settlement::backfill
//! [`update_statement_payout`]: Settlement::update_statement_payout
//! [`set_shop_visibility`]: Settlement::set_shop_visibility

use std::sync::Arc;

use serde::Serialize;

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::core::models::settlement::{
    FeeStatementDetail, SettlementBackfillResponse, SettlementCurrentResponse,
    SettlementLineListResponse, SettlementOverviewResponse, SettlementStatementListResponse,
    ShopFeeConfigResponse, ShopVisibilityResponse, StatementAdjustment,
    StatementAdjustmentListResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

/// The `settlement` resource, obtained via [`crate::Delopay::settlement`].
///
/// See the [module docs](self) for the `test_mode` rule and the permission
/// split between reads and host actions.
#[derive(Debug, Clone)]
pub struct Settlement {
    inner: Arc<Inner>,
}

impl Settlement {
    pub(crate) fn new(inner: Arc<Inner>) -> Self {
        Self { inner }
    }

    /// Per-shop settlement rollup for the host merchant: unpaid totals and
    /// the running current period, one row per shop.
    ///
    /// `GET /settlement/overview`
    pub async fn overview(&self, test_mode: bool) -> Result<SettlementOverviewResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                "/settlement/overview",
                None,
                &[("test_mode", test_mode.to_string())],
                None,
            )
            .await
    }

    /// Live rollup of the current (not yet statemented) period.
    ///
    /// `profile_id` narrows to one shop; shop-owner callers are pinned to
    /// their own regardless.
    ///
    /// `GET /settlement/current`
    pub async fn current(
        &self,
        test_mode: bool,
        profile_id: Option<&str>,
    ) -> Result<SettlementCurrentResponse> {
        let mut query = vec![("test_mode", test_mode.to_string())];
        if let Some(profile_id) = profile_id {
            query.push(("profile_id", profile_id.to_string()));
        }
        self.inner
            .request(HttpMethod::Get, "/settlement/current", None, &query, None)
            .await
    }

    /// List generated settlement statements, newest first.
    ///
    /// `GET /settlement/statements`
    pub async fn list_statements(
        &self,
        params: &StatementListParams,
    ) -> Result<SettlementStatementListResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                "/settlement/statements",
                None,
                &params.to_query(),
                None,
            )
            .await
    }

    /// One statement with its per-connector/currency breakdown.
    ///
    /// `GET /settlement/statements/{statement_id}`
    pub async fn retrieve_statement(&self, statement_id: &str) -> Result<FeeStatementDetail> {
        let path = statement_path(statement_id);
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Generate — or regenerate — the statement for one shop and calendar
    /// month.
    ///
    /// Regeneration only rewrites the figures while the statement is
    /// `unpaid`; once it is `partial` or `paid` the money has moved and the
    /// numbers are frozen.
    ///
    /// `POST /settlement/statements/generate`
    pub async fn generate_statement(
        &self,
        params: &StatementGenerateRequest,
    ) -> Result<FeeStatementDetail> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/settlement/statements/generate",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Record payout progress on a statement.
    ///
    /// `POST /settlement/statements/{statement_id}/payout`
    pub async fn update_statement_payout(
        &self,
        statement_id: &str,
        params: &StatementPayoutUpdateRequest,
    ) -> Result<FeeStatementDetail> {
        let path = format!("{}/payout", statement_path(statement_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Export a statement as a PDF, returned as raw bytes.
    ///
    /// Same auth, retries and error handling as every JSON call — write the
    /// bytes to a file or hand them to whatever serves them.
    ///
    /// The document deliberately carries **no platform fee for any viewer**:
    /// a host forwards this to a shop owner as their invoice, and a figure
    /// that is only safe for one of them cannot live on a page that gets
    /// forwarded.
    ///
    /// `GET /settlement/statements/{statement_id}/pdf`
    ///
    /// ```no_run
    /// # use delopay::{Delopay, StatementPdfParams};
    /// # async fn run(client: Delopay) -> delopay::Result<()> {
    /// let pdf = client
    ///     .settlement()
    ///     .download_statement_pdf("stmt_1", &StatementPdfParams::new().currency("EUR"))
    ///     .await?;
    /// std::fs::write("statement.pdf", pdf).unwrap();
    /// # Ok(())
    /// # }
    /// ```
    pub async fn download_statement_pdf(
        &self,
        statement_id: &str,
        params: &StatementPdfParams,
    ) -> Result<Vec<u8>> {
        let path = format!("{}/pdf", statement_path(statement_id));
        self.inner
            .request_bytes(
                HttpMethod::Get,
                &path,
                &params.to_query(),
                "application/pdf",
            )
            .await
    }

    /// The individual settled attempts of one shop's calendar month.
    ///
    /// `GET /settlement/lines`
    pub async fn list_lines(
        &self,
        params: &SettlementLineListParams,
    ) -> Result<SettlementLineListResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                "/settlement/lines",
                None,
                &params.to_query(),
                None,
            )
            .await
    }

    /// The fee schedules that currently apply to a shop.
    ///
    /// These are today's schedules, not the ones a past statement was priced
    /// with — statements keep their own pricing.
    ///
    /// `GET /settlement/fee-config`
    pub async fn fee_config(&self, profile_id: &str) -> Result<ShopFeeConfigResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                "/settlement/fee-config",
                None,
                &[("profile_id", profile_id.to_string())],
                None,
            )
            .await
    }

    /// Enqueue a settlement-line backfill over historical attempts.
    ///
    /// Attempts already covered by a line are skipped, so this is safe to run
    /// again. Historical attempts are priced with the **currently
    /// configured** schedules — the one place settlement prices the past with
    /// today's rates — and attempts with no applicable schedule are skipped
    /// rather than written at zero, so they stay re-priceable.
    ///
    /// `POST /settlement/backfill`
    pub async fn backfill(
        &self,
        params: &SettlementBackfillRequest,
    ) -> Result<SettlementBackfillResponse> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/settlement/backfill",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Toggle whether a shop's owner can open their own settlement figures.
    ///
    /// Read-side only: lines and statements keep accruing while a shop is
    /// hidden, so re-enabling reveals the full history rather than a gap.
    ///
    /// `POST /settlement/shops/visibility`
    pub async fn set_shop_visibility(
        &self,
        profile_id: &str,
        visible_to_shop: bool,
    ) -> Result<ShopVisibilityResponse> {
        let body = to_json_vec(&ShopVisibilityUpdateRequest {
            profile_id: profile_id.to_string(),
            visible_to_shop,
        })?;
        self.inner
            .request(
                HttpMethod::Post,
                "/settlement/shops/visibility",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// The manual positions the host recorded on a statement.
    ///
    /// `GET /settlement/statements/{statement_id}/adjustments`
    pub async fn list_statement_adjustments(
        &self,
        statement_id: &str,
    ) -> Result<StatementAdjustmentListResponse> {
        let path = format!("{}/adjustments", statement_path(statement_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Add a manual position to a statement.
    ///
    /// **Positive `amount_usd` charges the shop owner** (their payout
    /// shrinks); negative credits them. Only editable while the statement is
    /// `unpaid`.
    ///
    /// `POST /settlement/statements/{statement_id}/adjustments`
    pub async fn create_statement_adjustment(
        &self,
        statement_id: &str,
        params: &StatementAdjustmentCreateRequest,
    ) -> Result<StatementAdjustment> {
        let path = format!("{}/adjustments", statement_path(statement_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Remove a manual position from a statement.
    ///
    /// `DELETE /settlement/statements/{statement_id}/adjustments/{adjustment_id}`
    pub async fn delete_statement_adjustment(
        &self,
        statement_id: &str,
        adjustment_id: &str,
    ) -> Result<()> {
        let path = format!(
            "{}/adjustments/{}",
            statement_path(statement_id),
            encode_segment(adjustment_id)
        );
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }
}

/// `/settlement/statements/{statement_id}`, percent-encoded.
fn statement_path(statement_id: &str) -> String {
    format!("/settlement/statements/{}", encode_segment(statement_id))
}

/// Parameters for [`Settlement::list_statements`].
#[derive(Debug, Clone)]
pub struct StatementListParams {
    /// Statement environment. Required, and transmitted even when `false`.
    pub test_mode: bool,
    /// Restrict to one shop. Enforced from the token for shop-owner callers.
    pub profile_id: Option<String>,
    /// Maximum statements to return.
    pub limit: Option<i64>,
    /// Statements to skip.
    pub offset: Option<i64>,
}

impl StatementListParams {
    /// List statements for one environment.
    #[must_use]
    pub fn new(test_mode: bool) -> Self {
        Self {
            test_mode,
            profile_id: None,
            limit: None,
            offset: None,
        }
    }

    /// Restrict to one shop.
    #[must_use]
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// Page size.
    #[must_use]
    pub fn limit(mut self, limit: i64) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Page offset.
    #[must_use]
    pub fn offset(mut self, offset: i64) -> Self {
        self.offset = Some(offset);
        self
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = vec![("test_mode", self.test_mode.to_string())];
        if let Some(v) = &self.profile_id {
            q.push(("profile_id", v.clone()));
        }
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = self.offset {
            q.push(("offset", v.to_string()));
        }
        q
    }
}

/// Parameters for [`Settlement::list_lines`].
#[derive(Debug, Clone)]
pub struct SettlementLineListParams {
    /// The shop whose lines to list.
    pub profile_id: String,
    /// Calendar year (UTC).
    pub year: i32,
    /// Calendar month, 1–12 (UTC).
    pub month: u32,
    /// Line environment. Required, and transmitted even when `false`.
    pub test_mode: bool,
    /// Maximum lines to return.
    pub limit: Option<i64>,
    /// Lines to skip.
    pub offset: Option<i64>,
}

impl SettlementLineListParams {
    /// List one shop's lines for one calendar month and environment.
    #[must_use]
    pub fn new(profile_id: impl Into<String>, year: i32, month: u32, test_mode: bool) -> Self {
        Self {
            profile_id: profile_id.into(),
            year,
            month,
            test_mode,
            limit: None,
            offset: None,
        }
    }

    /// Page size.
    #[must_use]
    pub fn limit(mut self, limit: i64) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Page offset.
    #[must_use]
    pub fn offset(mut self, offset: i64) -> Self {
        self.offset = Some(offset);
        self
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = vec![
            ("profile_id", self.profile_id.clone()),
            ("year", self.year.to_string()),
            ("month", self.month.to_string()),
            ("test_mode", self.test_mode.to_string()),
        ];
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = self.offset {
            q.push(("offset", v.to_string()));
        }
        q
    }
}

/// Query parameters for [`Settlement::download_statement_pdf`].
#[derive(Debug, Clone, Default)]
pub struct StatementPdfParams {
    /// ISO currency the PDF totals are converted to. Defaults to USD.
    pub currency: Option<String>,
    /// Append a per-transaction table. Off by default.
    pub include_transactions: Option<bool>,
}

impl StatementPdfParams {
    /// The default PDF: USD totals, no transaction appendix.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Convert the totals to this currency.
    #[must_use]
    pub fn currency(mut self, currency: impl Into<String>) -> Self {
        self.currency = Some(currency.into());
        self
    }

    /// Append the per-transaction table.
    #[must_use]
    pub fn include_transactions(mut self, include_transactions: bool) -> Self {
        self.include_transactions = Some(include_transactions);
        self
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = &self.currency {
            q.push(("currency", v.clone()));
        }
        if let Some(v) = self.include_transactions {
            q.push(("include_transactions", v.to_string()));
        }
        q
    }
}

/// Body for [`Settlement::generate_statement`].
#[derive(Debug, Clone, Serialize)]
pub struct StatementGenerateRequest {
    /// The shop to generate for.
    pub profile_id: String,
    /// Calendar year (UTC).
    pub year: i32,
    /// Calendar month, 1–12 (UTC).
    pub month: u32,
    /// Statement environment. Always sent.
    pub test_mode: bool,
}

impl StatementGenerateRequest {
    /// Generate one shop's statement for one calendar month and environment.
    #[must_use]
    pub fn new(profile_id: impl Into<String>, year: i32, month: u32, test_mode: bool) -> Self {
        Self {
            profile_id: profile_id.into(),
            year,
            month,
            test_mode,
        }
    }
}

/// Body for [`Settlement::update_statement_payout`].
#[derive(Debug, Clone, Serialize)]
pub struct StatementPayoutUpdateRequest {
    /// `"unpaid"`, `"partial"` or `"paid"`.
    pub payout_status: String,
    /// Handed over so far, USD minor units — what makes `partial` a real
    /// figure. Omitted, it defaults to the full net for `paid` and zero for
    /// `unpaid`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub paid_amount_usd: Option<i64>,
    /// ISO 8601 payout timestamp. Defaults to now (UTC) when marking `paid`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub paid_at: Option<String>,
    /// Free-form note recorded with the payout.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

impl StatementPayoutUpdateRequest {
    /// Set the payout status, leaving the amount to the server default.
    #[must_use]
    pub fn new(payout_status: impl Into<String>) -> Self {
        Self {
            payout_status: payout_status.into(),
            paid_amount_usd: None,
            paid_at: None,
            note: None,
        }
    }

    /// Record how much has actually been handed over, USD minor units.
    #[must_use]
    pub fn paid_amount_usd(mut self, paid_amount_usd: i64) -> Self {
        self.paid_amount_usd = Some(paid_amount_usd);
        self
    }

    /// Record when the payout happened (ISO 8601).
    #[must_use]
    pub fn paid_at(mut self, paid_at: impl Into<String>) -> Self {
        self.paid_at = Some(paid_at.into());
        self
    }

    /// Attach a note.
    #[must_use]
    pub fn note(mut self, note: impl Into<String>) -> Self {
        self.note = Some(note.into());
        self
    }
}

/// Body for [`Settlement::backfill`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct SettlementBackfillRequest {
    /// Restrict to one shop. Omitted, every shop of the merchant is covered.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// ISO 8601 inclusive start (UTC). Omitted, from the beginning.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,
    /// ISO 8601 exclusive end (UTC). Omitted, up to now.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to: Option<String>,
}

impl SettlementBackfillRequest {
    /// Backfill every shop, over all time.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Restrict to one shop.
    #[must_use]
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// Inclusive start of the range (ISO 8601, UTC).
    #[must_use]
    pub fn from(mut self, from: impl Into<String>) -> Self {
        self.from = Some(from.into());
        self
    }

    /// Exclusive end of the range (ISO 8601, UTC).
    #[must_use]
    pub fn to(mut self, to: impl Into<String>) -> Self {
        self.to = Some(to.into());
        self
    }
}

/// Body of [`Settlement::set_shop_visibility`].
#[derive(Debug, Clone, Serialize)]
struct ShopVisibilityUpdateRequest {
    profile_id: String,
    visible_to_shop: bool,
}

/// Body for [`Settlement::create_statement_adjustment`].
#[derive(Debug, Clone, Serialize)]
pub struct StatementAdjustmentCreateRequest {
    /// Host-authored label, e.g. `"Setup fee"`.
    pub label: String,
    /// Signed USD minor units. **Positive charges the shop owner**; negative
    /// credits them.
    pub amount_usd: i64,
}

impl StatementAdjustmentCreateRequest {
    /// A position that **charges** the shop owner `amount_usd` USD minor
    /// units, reducing their payout.
    ///
    /// The magnitude is taken, so the sign of the argument cannot flip the
    /// direction of the money. `saturating_abs` rather than `abs` because
    /// `i64::MIN.abs()` overflows — the same reason [`crate::Money`] reaches
    /// for `unsigned_abs`.
    #[must_use]
    pub fn charge(label: impl Into<String>, amount_usd: i64) -> Self {
        Self {
            label: label.into(),
            amount_usd: amount_usd.saturating_abs(),
        }
    }

    /// A position that **credits** the shop owner `amount_usd` USD minor
    /// units, increasing their payout.
    ///
    /// Takes the magnitude and negates it, so a caller cannot accidentally
    /// bill someone by passing a positive number to the credit constructor.
    #[must_use]
    pub fn credit(label: impl Into<String>, amount_usd: i64) -> Self {
        Self {
            label: label.into(),
            amount_usd: -amount_usd.saturating_abs(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http::mock::{Step, client_with};

    const STATEMENT_JSON: &str = r#"{
        "id": "stmt_1",
        "merchant_id": "mer_1",
        "profile_id": "pro_1",
        "period_start": "2026-07-01T00:00:00Z",
        "period_end": "2026-08-01T00:00:00Z",
        "test_mode": false,
        "gross_usd": 100000,
        "platform_fee_usd": 1000,
        "merchant_fee_usd": 15000,
        "refund_usd": 0,
        "net_to_shop_usd": 85000,
        "line_count": 12,
        "refund_count": 0,
        "payout_status": "unpaid",
        "paid_amount_usd": 0,
        "generated_at": "2026-08-01T00:20:00Z",
        "adjustments_usd": 0,
        "net_after_adjustments_usd": 85000,
        "breakdown": []
    }"#;

    #[tokio::test]
    async fn overview_transmits_a_false_test_mode() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"shops":[]}"#)]);
        client.settlement().overview(false).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        // Dropping `test_mode=false` as "falsy" would silently return the
        // wrong environment's money. Pin the literal.
        assert_eq!(
            seen[0].url,
            "https://api.test/settlement/overview?test_mode=false"
        );
    }

    #[tokio::test]
    async fn current_omits_an_absent_profile_but_keeps_test_mode() {
        let (client, mock) = client_with(vec![
            Step::ok(
                r#"{"period_start":"2026-08-01T00:00:00Z","period_end":"2026-09-01T00:00:00Z",
                    "test_mode":true,"breakdown":[]}"#,
            ),
            Step::ok(
                r#"{"period_start":"2026-08-01T00:00:00Z","period_end":"2026-09-01T00:00:00Z",
                    "test_mode":true,"breakdown":[]}"#,
            ),
        ]);
        client.settlement().current(true, None).await.unwrap();
        client
            .settlement()
            .current(true, Some("pro/1"))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/settlement/current?test_mode=true"
        );
        assert_eq!(
            seen[1].url,
            "https://api.test/settlement/current?test_mode=true&profile_id=pro/1"
        );
    }

    #[tokio::test]
    async fn list_statements_sends_every_set_filter() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"statements":[],"total_count":0}"#)]);
        let params = StatementListParams::new(false)
            .profile_id("pro_1")
            .limit(20)
            .offset(40);
        client.settlement().list_statements(&params).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/settlement/statements?test_mode=false&profile_id=pro_1&limit=20&offset=40"
        );
    }

    #[tokio::test]
    async fn retrieve_statement_encodes_the_id_and_decodes_the_breakdown() {
        let (client, mock) = client_with(vec![Step::ok(STATEMENT_JSON)]);
        let detail = client
            .settlement()
            .retrieve_statement("stmt/1")
            .await
            .unwrap();
        assert_eq!(detail.summary.id, "stmt_1");
        assert_eq!(detail.summary.net_after_adjustments_usd, 85000);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/settlement/statements/stmt%2F1"
        );
    }

    #[tokio::test]
    async fn generate_statement_posts_the_period() {
        let (client, mock) = client_with(vec![Step::ok(STATEMENT_JSON)]);
        let params = StatementGenerateRequest::new("pro_1", 2026, 7, false);
        client
            .settlement()
            .generate_statement(&params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/settlement/statements/generate"
        );
        let body = seen[0].body_json();
        assert_eq!(body["profile_id"], "pro_1");
        assert_eq!(body["year"], 2026);
        assert_eq!(body["month"], 7);
        // `test_mode` is not optional in the body either.
        assert_eq!(body["test_mode"], false);
    }

    #[tokio::test]
    async fn update_statement_payout_posts_only_the_set_fields() {
        let (client, mock) = client_with(vec![Step::ok(STATEMENT_JSON)]);
        let params = StatementPayoutUpdateRequest::new("partial").paid_amount_usd(40000);
        client
            .settlement()
            .update_statement_payout("stmt_1", &params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/settlement/statements/stmt_1/payout"
        );
        let body = seen[0].body_json();
        assert_eq!(body["payout_status"], "partial");
        assert_eq!(body["paid_amount_usd"], 40000);
        // An unset note must not be sent as `null` — the server reads that as
        // "clear the note".
        assert!(body.get("note").is_none());
        assert!(body.get("paid_at").is_none());
    }

    #[tokio::test]
    async fn download_statement_pdf_returns_bytes_and_asks_for_pdf() {
        let (client, mock) = client_with(vec![Step::ok("%PDF-1.4\nnot json at all")]);
        let params = StatementPdfParams::new()
            .currency("EUR")
            .include_transactions(true);
        let bytes = client
            .settlement()
            .download_statement_pdf("stmt_1", &params)
            .await
            .unwrap();
        // The body is returned verbatim: a JSON decode step would fail here.
        assert!(bytes.starts_with(b"%PDF-1.4"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/settlement/statements/stmt_1/pdf?currency=EUR&include_transactions=true"
        );
        assert_eq!(seen[0].header("accept"), Some("application/pdf"));
        // Exactly one `accept`: the JSON default must have been replaced, not
        // joined.
        assert_eq!(
            seen[0]
                .headers
                .iter()
                .filter(|(name, _)| name.eq_ignore_ascii_case("accept"))
                .count(),
            1
        );
    }

    #[tokio::test]
    async fn list_lines_sends_the_full_period_key() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"lines":[],"total_count":0}"#)]);
        let params = SettlementLineListParams::new("pro_1", 2026, 7, true).limit(50);
        client.settlement().list_lines(&params).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/settlement/lines?profile_id=pro_1&year=2026&month=7&test_mode=true&limit=50"
        );
    }

    #[tokio::test]
    async fn fee_config_scopes_by_profile() {
        let (client, mock) =
            client_with(vec![Step::ok(r#"{"profile_id":"pro_1","schedules":[]}"#)]);
        let out = client.settlement().fee_config("pro_1").await.unwrap();
        assert_eq!(out.profile_id, "pro_1");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/settlement/fee-config?profile_id=pro_1"
        );
    }

    #[tokio::test]
    async fn backfill_posts_an_empty_body_when_unrestricted() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"enqueued":true,"job_id":"job_1"}"#)]);
        let out = client
            .settlement()
            .backfill(&SettlementBackfillRequest::new())
            .await
            .unwrap();
        assert!(out.enqueued);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/settlement/backfill");
        // An unrestricted backfill sends `{}`, not `{"profile_id":null}` —
        // a null there is a different request.
        assert_eq!(seen[0].body_json(), serde_json::json!({}));
    }

    #[tokio::test]
    async fn set_shop_visibility_posts_both_fields() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"profile_id":"pro_1","visible_to_shop":false}"#,
        )]);
        let out = client
            .settlement()
            .set_shop_visibility("pro_1", false)
            .await
            .unwrap();
        assert!(!out.visible_to_shop);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].url, "https://api.test/settlement/shops/visibility");
        let body = seen[0].body_json();
        assert_eq!(body["profile_id"], "pro_1");
        assert_eq!(body["visible_to_shop"], false);
    }

    #[tokio::test]
    async fn adjustments_round_trip_on_the_statement_sub_path() {
        let (client, mock) = client_with(vec![
            Step::ok(r#"{"adjustments":[]}"#),
            Step::ok(
                r#"{"id":"adj_1","label":"Setup fee","amount_usd":5000,
                    "created_at":"2026-08-02T00:00:00Z"}"#,
            ),
            Step::ok(""),
        ]);
        let settlement = client.settlement();
        settlement
            .list_statement_adjustments("stmt_1")
            .await
            .unwrap();
        settlement
            .create_statement_adjustment(
                "stmt_1",
                &StatementAdjustmentCreateRequest::charge("Setup fee", 5000),
            )
            .await
            .unwrap();
        settlement
            .delete_statement_adjustment("stmt_1", "adj/1")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/settlement/statements/stmt_1/adjustments"
        );
        assert_eq!(seen[1].method, "POST");
        assert_eq!(seen[2].method, "DELETE");
        assert_eq!(
            seen[2].url,
            "https://api.test/settlement/statements/stmt_1/adjustments/adj%2F1"
        );
    }

    #[test]
    fn credit_is_negative_and_charge_is_positive_whatever_the_caller_passes() {
        // The sign is the whole meaning of the field: a credit constructed
        // with a positive magnitude must still bill nobody.
        assert_eq!(
            StatementAdjustmentCreateRequest::credit("Goodwill", 2500).amount_usd,
            -2500
        );
        assert_eq!(
            StatementAdjustmentCreateRequest::credit("Goodwill", -2500).amount_usd,
            -2500
        );
        assert_eq!(
            StatementAdjustmentCreateRequest::charge("Setup", 2500).amount_usd,
            2500
        );
        assert_eq!(
            StatementAdjustmentCreateRequest::charge("Setup", -2500).amount_usd,
            2500
        );
    }

    #[test]
    fn the_adjustment_constructors_survive_i64_min() {
        // `abs()` overflows here; `saturating_abs()` does not. Pathological
        // input, but a panic in a money constructor is not a failure mode
        // worth having.
        assert_eq!(
            StatementAdjustmentCreateRequest::charge("Setup", i64::MIN).amount_usd,
            i64::MAX
        );
        assert_eq!(
            StatementAdjustmentCreateRequest::credit("Goodwill", i64::MIN).amount_usd,
            -i64::MAX
        );
    }
}