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
//! Hosted-shop settlement models: monthly statements, the live current-period
//! rollup, per-line detail, fee configuration and backfills.
//!
//! # Two amount families, and they do not mix
//!
//! Statement-level totals are named `*_usd` and are USD minor units — the
//! aggregation normalises every currency into one so a payout is a single
//! figure. Bucket- and line-level amounts are in the **native minor units of
//! that row's `currency`**. Both families are exposed as [`Money`] accessors
//! next to the raw integers, so an amount is never separated from the
//! currency that gives it meaning (see [`crate::money`]).
//!
//! # Redaction is a boundary, not a gap
//!
//! Shop-owner reads come back with the platform fee removed server-side:
//! that figure is DeloPay's cut of the *host's* revenue, and publishing it to
//! a third party hands over the host's margin.
//!
//! The amounts are **zeroed, not omitted** — `platform_fee_amount` and
//! `platform_fee_usd` still arrive, carrying `0`. So a zero is ambiguous by
//! design: a genuinely zero fee and a withheld one look the same, and which
//! it is depends on who asked. `SettlementLine::platform_fee_source` is the
//! one field that is genuinely absent, and it is dropped *together* with the
//! amount it describes — a live source beside a zero would say a fee exists
//! and name what priced it while the zero claims it does not.
//!
//! Either way: never reconstruct a withheld figure from the other amounts.
//!
//! # `platform_fee_incomplete` is not `fx_incomplete`
//!
//! `fx_incomplete` means a line was left **out** of the payout figures
//! because its currency had no reporting rate — the totals are wrong until it
//! is fixed. `platform_fee_incomplete` means the informational platform-fee
//! total is a **lower bound** because some line could not be priced. Only the
//! first one is a reason to distrust what a shop owner gets paid.

use serde::Deserialize;
use serde_json::Value;

use crate::core::money::Money;

/// Payout progress of a settlement statement.
///
/// Modelled as a string rather than an enum: the backend is free to add a
/// state, and a strict enum would turn that into a decode failure across
/// every statement in a list.
pub type SettlementPayoutStatus = String;

/// Who owns the connector a settlement line ran through: `"host"`, `"shop"`,
/// or `"unknown"` for lines frozen before ownership tracking existed.
pub type ConnectorOwnership = String;

/// One per-connector/currency rollup inside a statement or the current-period
/// view. Amounts are native minor units of [`currency`](Self::currency).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SettlementBucket {
    /// Connector the bucket's payments ran through. `None` groups lines with
    /// no recorded connector.
    #[serde(default)]
    pub connector: Option<String>,
    /// Host-owned or shop-brought connector — see [`ConnectorOwnership`].
    pub ownership: ConnectorOwnership,
    /// ISO 4217 currency of every amount in this bucket.
    pub currency: String,
    /// Gross successfully-captured amount.
    pub gross_amount: i64,
    /// DeloPay's platform fee. Informational for the host, and **zeroed**
    /// server-side on shop-owner reads — the key is still sent, carrying `0`.
    ///
    /// A zero here is therefore ambiguous by design: it is either a genuinely
    /// zero fee or a withheld one, and which it is depends on who asked.
    /// Either way it is a permission boundary rather than a gap, so never
    /// re-derive the figure from the other amounts.
    #[serde(default)]
    pub platform_fee_amount: i64,
    /// `true` when at least one line here is still awaiting its platform-fee
    /// figure, making [`platform_fee_amount`](Self::platform_fee_amount) a
    /// lower bound rather than a total.
    #[serde(default)]
    pub platform_fee_incomplete: bool,
    /// The host's hosting fee — what the shop owner is charged.
    pub merchant_fee_amount: i64,
    /// Refunded amount. Hosting fees are **not** returned on refunds.
    pub refund_amount: i64,
    /// `gross − refunds − hosting fees`.
    pub net_to_shop: i64,
    /// Number of settled attempts in the bucket.
    pub line_count: i64,
    /// Number of refunds in the bucket.
    pub refund_count: i64,
    /// Hosting-fee rate applied, e.g. `"2.9"` percent. `None` when the rate
    /// changed mid-period — the bucket quotes no rate rather than
    /// misattributing one.
    #[serde(default)]
    pub fee_percentage: Option<String>,
    /// Flat component of the hosting fee, minor units of
    /// [`currency`](Self::currency).
    #[serde(default)]
    pub fee_flat_amount: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl SettlementBucket {
    /// [`gross_amount`](Self::gross_amount) with its currency attached.
    #[must_use]
    pub fn gross(&self) -> Money {
        Money::new(self.gross_amount, &self.currency)
    }

    /// [`merchant_fee_amount`](Self::merchant_fee_amount) with its currency.
    #[must_use]
    pub fn merchant_fee(&self) -> Money {
        Money::new(self.merchant_fee_amount, &self.currency)
    }

    /// [`refund_amount`](Self::refund_amount) with its currency.
    #[must_use]
    pub fn refund(&self) -> Money {
        Money::new(self.refund_amount, &self.currency)
    }

    /// [`net_to_shop`](Self::net_to_shop) with its currency.
    #[must_use]
    pub fn net(&self) -> Money {
        Money::new(self.net_to_shop, &self.currency)
    }

    /// [`platform_fee_amount`](Self::platform_fee_amount) with its currency.
    ///
    /// A lower bound when
    /// [`platform_fee_incomplete`](Self::platform_fee_incomplete) is set, and
    /// withheld entirely on shop-owner reads.
    #[must_use]
    pub fn platform_fee(&self) -> Money {
        Money::new(self.platform_fee_amount, &self.currency)
    }
}

/// One generated monthly settlement statement. Every `*_usd` amount is USD
/// minor units.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct FeeStatementSummary {
    /// Statement ID.
    pub id: String,
    /// The host merchant the statement belongs to.
    pub merchant_id: String,
    /// The shop (business profile) the statement is for.
    pub profile_id: String,
    /// ISO 8601 period start (UTC).
    pub period_start: String,
    /// ISO 8601 period end (UTC).
    pub period_end: String,
    /// Whether these are test-mode figures. Test and live never blend.
    pub test_mode: bool,
    /// Gross captured, USD minor units.
    pub gross_usd: i64,
    /// DeloPay's platform fee, USD minor units. **Zeroed** — not omitted —
    /// on shop-owner reads, so a zero is either a genuinely zero fee or a
    /// withheld one. Never re-derive it from the other amounts.
    #[serde(default)]
    pub platform_fee_usd: i64,
    /// The host's hosting fee, USD minor units.
    pub merchant_fee_usd: i64,
    /// Refunded, USD minor units.
    pub refund_usd: i64,
    /// `gross − refunds − hosting fees`, USD minor units. The computed
    /// sub-total — see
    /// [`net_after_adjustments_usd`](Self::net_after_adjustments_usd) for
    /// what is actually paid.
    pub net_to_shop_usd: i64,
    /// Settled attempts counted.
    pub line_count: i64,
    /// Refunds counted.
    pub refund_count: i64,
    /// `true` when a line was **excluded** for want of an FX rate: the
    /// figures above are missing money, not merely imprecise.
    #[serde(default)]
    pub fx_incomplete: bool,
    /// `true` when [`platform_fee_usd`](Self::platform_fee_usd) is a lower
    /// bound. Does not affect what the shop owner is paid.
    #[serde(default)]
    pub platform_fee_incomplete: bool,
    /// Whether backfilled lines contributed to these figures.
    #[serde(default)]
    pub includes_backfill: bool,
    /// `"unpaid"`, `"partial"` or `"paid"`. While `unpaid`, re-generating
    /// rewrites the figures; afterwards they are frozen.
    pub payout_status: SettlementPayoutStatus,
    /// Handed over so far, USD minor units.
    #[serde(default)]
    pub paid_amount_usd: i64,
    /// ISO 8601 timestamp of the payout, when recorded.
    #[serde(default)]
    pub paid_at: Option<String>,
    /// Free-form note recorded with the payout.
    #[serde(default)]
    pub payout_note: Option<String>,
    /// ISO 8601 timestamp the statement was generated.
    pub generated_at: String,
    /// Signed sum of the host's manual adjustments, USD minor units.
    /// **Positive means the shop owner owes more** and their payout shrinks.
    #[serde(default)]
    pub adjustments_usd: i64,
    /// `net_to_shop_usd − adjustments_usd` — the payable figure.
    #[serde(default)]
    pub net_after_adjustments_usd: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl FeeStatementSummary {
    /// [`net_after_adjustments_usd`](Self::net_after_adjustments_usd) as
    /// USD [`Money`] — the figure to pay out.
    #[must_use]
    pub fn payable(&self) -> Money {
        Money::new(self.net_after_adjustments_usd, "USD")
    }

    /// [`gross_usd`](Self::gross_usd) as USD [`Money`].
    #[must_use]
    pub fn gross(&self) -> Money {
        Money::new(self.gross_usd, "USD")
    }

    /// [`merchant_fee_usd`](Self::merchant_fee_usd) as USD [`Money`].
    #[must_use]
    pub fn merchant_fee(&self) -> Money {
        Money::new(self.merchant_fee_usd, "USD")
    }
}

/// A statement with its per-connector/currency breakdown.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct FeeStatementDetail {
    /// The statement's own figures.
    #[serde(flatten)]
    pub summary: FeeStatementSummary,
    /// Per-connector/currency rollups behind the totals.
    #[serde(default)]
    pub breakdown: Vec<SettlementBucket>,
}

/// A page of generated statements, newest first.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SettlementStatementListResponse {
    /// The statements on this page.
    #[serde(default)]
    pub statements: Vec<FeeStatementSummary>,
    /// Total matching statements, ignoring paging.
    #[serde(default)]
    pub total_count: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One shop's row in the host merchant's settlement overview.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ShopSettlementOverview {
    /// The shop (business profile).
    pub profile_id: String,
    /// Display name of the shop, when it has one.
    #[serde(default)]
    pub profile_name: Option<String>,
    /// Outstanding across all unpaid statements, USD minor units.
    #[serde(default)]
    pub unpaid_net_usd: i64,
    /// How many statements are still unpaid.
    #[serde(default)]
    pub unpaid_statement_count: i64,
    /// Running net for the current, not-yet-statemented period.
    #[serde(default)]
    pub current_period_net_usd: i64,
    /// Running hosting fee for the current period.
    #[serde(default)]
    pub current_period_merchant_fee_usd: i64,
    /// Running gross for the current period.
    #[serde(default)]
    pub current_period_gross_usd: i64,
    /// `true` when a line was excluded for want of an FX rate.
    #[serde(default)]
    pub fx_incomplete: bool,
    /// Whether a hosting-fee schedule is configured for this shop. Without
    /// one, no settlement lines are written at all.
    #[serde(default)]
    pub has_fee_config: bool,
    /// Whether the shop's own owner may open these figures.
    #[serde(default)]
    pub visible_to_shop: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Per-shop settlement rollup for the host merchant.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SettlementOverviewResponse {
    /// One row per shop.
    #[serde(default)]
    pub shops: Vec<ShopSettlementOverview>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Live rollup of the current (not yet statemented) period.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SettlementCurrentResponse {
    /// ISO 8601 period start (UTC).
    pub period_start: String,
    /// ISO 8601 period end (UTC).
    pub period_end: String,
    /// Whether these are test-mode figures.
    pub test_mode: bool,
    /// Gross captured so far, USD minor units.
    #[serde(default)]
    pub gross_usd: i64,
    /// Platform fee so far, USD minor units. Withheld from shop owners.
    #[serde(default)]
    pub platform_fee_usd: i64,
    /// Hosting fee so far, USD minor units.
    #[serde(default)]
    pub merchant_fee_usd: i64,
    /// Refunded so far, USD minor units.
    #[serde(default)]
    pub refund_usd: i64,
    /// Net to the shop so far, USD minor units.
    #[serde(default)]
    pub net_to_shop_usd: i64,
    /// Settled attempts counted so far.
    #[serde(default)]
    pub line_count: i64,
    /// Refunds counted so far.
    #[serde(default)]
    pub refund_count: i64,
    /// `true` when a line was excluded for want of an FX rate.
    #[serde(default)]
    pub fx_incomplete: bool,
    /// `true` when the platform-fee total is a lower bound.
    #[serde(default)]
    pub platform_fee_incomplete: bool,
    /// Per-connector/currency rollups behind the totals.
    #[serde(default)]
    pub breakdown: Vec<SettlementBucket>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One manual position the host added to a statement.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct StatementAdjustment {
    /// Adjustment ID.
    pub id: String,
    /// Host-authored label, e.g. `"Setup fee"`.
    pub label: String,
    /// Signed USD minor units. **Positive charges the shop owner** (reducing
    /// their payout); negative credits them.
    pub amount_usd: i64,
    /// ISO 8601 creation timestamp.
    pub created_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl StatementAdjustment {
    /// [`amount_usd`](Self::amount_usd) as USD [`Money`], sign preserved.
    #[must_use]
    pub fn amount(&self) -> Money {
        Money::new(self.amount_usd, "USD")
    }
}

/// The manual adjustments recorded on a statement.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct StatementAdjustmentListResponse {
    /// The adjustments, in creation order.
    #[serde(default)]
    pub adjustments: Vec<StatementAdjustment>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One settled payment attempt. Amounts are native minor units of
/// [`currency`](Self::currency).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SettlementLine {
    /// The payment the attempt belongs to.
    pub payment_id: String,
    /// The attempt. Only unique within a merchant.
    pub attempt_id: String,
    /// Connector the attempt ran through.
    #[serde(default)]
    pub connector: Option<String>,
    /// Host-owned or shop-brought connector.
    pub connector_ownership: ConnectorOwnership,
    /// Payment method, as stamped at record time.
    #[serde(default)]
    pub payment_method: Option<String>,
    /// Payment method type, as stamped at record time.
    #[serde(default)]
    pub payment_method_type: Option<String>,
    /// ISO 4217 currency of every amount on this line.
    pub currency: String,
    /// Gross captured.
    pub gross_amount: i64,
    /// DeloPay's platform fee. **Zeroed** on shop-owner reads, together with
    /// [`platform_fee_source`](Self::platform_fee_source) being dropped.
    #[serde(default)]
    pub platform_fee_amount: i64,
    /// The host's hosting fee.
    pub merchant_fee_amount: i64,
    /// `gross − hosting fee`.
    pub net_to_shop: i64,
    /// How the hosting fee was priced.
    pub merchant_fee_source: String,
    /// How the platform fee was priced — `"unpriceable"` marks a line whose
    /// platform fee could not be computed. Absent on shop-owner reads, which
    /// is redaction rather than a gap.
    #[serde(default)]
    pub platform_fee_source: Option<String>,
    /// What the (untouched) prepaid ledger deduct did for this attempt.
    pub merchant_ledger_outcome: String,
    /// Whether the attempt was in test mode.
    pub test_mode: bool,
    /// Whether the line was written by a backfill rather than at payment time.
    #[serde(default)]
    pub backfilled: bool,
    /// ISO 8601 timestamp of the transaction.
    pub transaction_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl SettlementLine {
    /// [`gross_amount`](Self::gross_amount) with its currency attached.
    #[must_use]
    pub fn gross(&self) -> Money {
        Money::new(self.gross_amount, &self.currency)
    }

    /// [`merchant_fee_amount`](Self::merchant_fee_amount) with its currency.
    #[must_use]
    pub fn merchant_fee(&self) -> Money {
        Money::new(self.merchant_fee_amount, &self.currency)
    }

    /// [`net_to_shop`](Self::net_to_shop) with its currency.
    #[must_use]
    pub fn net(&self) -> Money {
        Money::new(self.net_to_shop, &self.currency)
    }
}

/// A page of settlement lines.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SettlementLineListResponse {
    /// The lines on this page.
    #[serde(default)]
    pub lines: Vec<SettlementLine>,
    /// Total matching lines, ignoring paging.
    #[serde(default)]
    pub total_count: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One fee schedule that currently applies to a shop.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ShopFeeConfigEntry {
    /// The fee schedule's ID.
    pub schedule_id: String,
    /// Connector the schedule is restricted to, if any.
    #[serde(default)]
    pub connector: Option<String>,
    /// Whether the schedule is scoped to this shop rather than the merchant.
    #[serde(default)]
    pub profile_specific: bool,
    /// Which fee this schedule prices (the hosting fee or the platform fee).
    pub fee_type: String,
    /// Percentage component, e.g. `2.9`.
    #[serde(default)]
    pub percentage_fee: Option<f64>,
    /// Flat component, minor units of
    /// [`flat_fee_currency`](Self::flat_fee_currency).
    #[serde(default)]
    pub flat_fee_amount: Option<i64>,
    /// Currency of the flat and min/max components.
    #[serde(default)]
    pub flat_fee_currency: Option<String>,
    /// Floor, minor units. Lifts a *priced* fee up; never creates one.
    #[serde(default)]
    pub min_fee_amount: Option<i64>,
    /// Ceiling, minor units.
    #[serde(default)]
    pub max_fee_amount: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl ShopFeeConfigEntry {
    /// [`flat_fee_amount`](Self::flat_fee_amount) with its currency attached.
    ///
    /// `None` when either half is missing — a flat fee with no currency is
    /// not an amount, and this deliberately refuses to invent one.
    #[must_use]
    pub fn flat_fee(&self) -> Option<Money> {
        match (self.flat_fee_amount, self.flat_fee_currency.as_deref()) {
            (Some(amount), Some(currency)) => Some(Money::new(amount, currency)),
            _ => None,
        }
    }
}

/// The fee schedules that currently apply to a shop.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ShopFeeConfigResponse {
    /// The shop the schedules apply to.
    pub profile_id: String,
    /// The applicable schedules.
    #[serde(default)]
    pub schedules: Vec<ShopFeeConfigEntry>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Outcome of enqueuing a settlement-line backfill.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SettlementBackfillResponse {
    /// Whether the job was accepted.
    pub enqueued: bool,
    /// The enqueued job's ID.
    pub job_id: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Whether a shop's owner may open their own settlement figures.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ShopVisibilityResponse {
    /// The shop the setting is for.
    pub profile_id: String,
    /// `true` when the shop's owner can see their settlement.
    pub visible_to_shop: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

#[cfg(test)]
mod tests {
    use super::*;

    const BUCKET_JSON: &str = r#"{
        "connector": "stripe",
        "ownership": "host",
        "currency": "JPY",
        "gross_amount": 1999,
        "platform_fee_amount": 20,
        "platform_fee_incomplete": true,
        "merchant_fee_amount": 200,
        "refund_amount": 0,
        "net_to_shop": 1799,
        "line_count": 3,
        "refund_count": 0,
        "fee_percentage": "10",
        "fee_flat_amount": 0,
        "surprise_field": 1
    }"#;

    #[test]
    fn bucket_amounts_carry_their_own_currency() {
        let bucket: SettlementBucket = serde_json::from_str(BUCKET_JSON).unwrap();
        // JPY has no minor unit, so 1999 is ¥1999 — not ¥19.99. A `Money`
        // hard-coded to two digits fails right here.
        assert_eq!(bucket.gross().to_major_string().as_deref(), Some("1999"));
        assert_eq!(bucket.net().to_major_string().as_deref(), Some("1799"));
        assert_eq!(bucket.merchant_fee().amount, 200);
        assert!(bucket.platform_fee_incomplete);
        assert_eq!(bucket.extra["surprise_field"], 1);
    }

    #[test]
    fn statement_detail_flattens_the_summary_beside_the_breakdown() {
        let json = format!(
            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",
                "generated_at": "2026-08-01T00:20:00Z",
                "adjustments_usd": 5000,
                "net_after_adjustments_usd": 80000,
                "breakdown": [{BUCKET_JSON}]
            }}"#
        );
        let detail: FeeStatementDetail = serde_json::from_str(&json).unwrap();
        assert_eq!(detail.summary.id, "stmt_1");
        assert_eq!(detail.breakdown.len(), 1);
        // The payable figure is net *after* the host's positions, not the
        // computed sub-total — swapping the two is the bug this pins.
        assert_eq!(
            detail.summary.payable().to_major_string().as_deref(),
            Some("800.00")
        );
        assert_eq!(detail.summary.net_to_shop_usd, 85000);
        // `breakdown` must not be swallowed into the flattened summary's
        // `extra` — a mutation reordering the two would show up here.
        assert!(!detail.summary.extra.contains_key("breakdown"));
    }

    #[test]
    fn statement_defaults_absent_flags_to_false() {
        let json = 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": true,
            "gross_usd": 0,
            "platform_fee_usd": 0,
            "merchant_fee_usd": 0,
            "refund_usd": 0,
            "net_to_shop_usd": 0,
            "line_count": 0,
            "refund_count": 0,
            "payout_status": "unpaid",
            "generated_at": "2026-08-01T00:20:00Z"
        }"#;
        // Pre-#772 snapshots carry no `platform_fee_incomplete`; they must
        // parse and read `false` rather than failing the whole list.
        let summary: FeeStatementSummary = serde_json::from_str(json).unwrap();
        assert!(!summary.platform_fee_incomplete);
        assert!(!summary.fx_incomplete);
        assert_eq!(summary.adjustments_usd, 0);
    }

    #[test]
    fn a_redacted_bucket_and_summary_still_decode() {
        // The backend zeroes the platform fee rather than omitting the key,
        // so this is what a shop owner actually receives. `#[serde(default)]`
        // is belt-and-braces: a payload that *did* omit it must not take the
        // whole breakdown — or a whole statement list — down with it.
        let bucket: SettlementBucket = serde_json::from_str(
            r#"{"ownership":"shop","currency":"EUR","gross_amount":1999,
                "merchant_fee_amount":200,"refund_amount":0,"net_to_shop":1799,
                "line_count":1,"refund_count":0}"#,
        )
        .unwrap();
        assert_eq!(bucket.platform_fee_amount, 0);

        let summary: FeeStatementSummary = serde_json::from_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,"merchant_fee_usd":15000,
                "refund_usd":0,"net_to_shop_usd":85000,"line_count":12,"refund_count":0,
                "payout_status":"unpaid","generated_at":"2026-08-01T00:20:00Z"}"#,
        )
        .unwrap();
        assert_eq!(summary.platform_fee_usd, 0);
        // The figures the shop owner is actually paid survive intact.
        assert_eq!(summary.net_to_shop_usd, 85000);
        assert_eq!(summary.merchant_fee_usd, 15000);
    }

    #[test]
    fn adjustment_amount_keeps_its_sign() {
        let json = r#"{
            "id": "adj_1",
            "label": "Goodwill credit",
            "amount_usd": -2500,
            "created_at": "2026-08-02T10:00:00Z"
        }"#;
        let adjustment: StatementAdjustment = serde_json::from_str(json).unwrap();
        // Negative = a credit in the shop owner's favour. Dropping the sign
        // would turn a credit into a charge.
        assert_eq!(
            adjustment.amount().to_major_string().as_deref(),
            Some("-25.00")
        );
    }

    #[test]
    fn line_redaction_is_visible_as_an_absent_source() {
        let json = r#"{
            "payment_id": "pay_1",
            "attempt_id": "pay_1_1",
            "connector_ownership": "shop",
            "currency": "EUR",
            "gross_amount": 1999,
            "merchant_fee_amount": 200,
            "net_to_shop": 1799,
            "merchant_fee_source": "schedule",
            "merchant_ledger_outcome": "deducted",
            "test_mode": false,
            "transaction_at": "2026-07-15T12:00:00Z"
        }"#;
        let line: SettlementLine = serde_json::from_str(json).unwrap();
        assert_eq!(line.platform_fee_source, None);
        assert_eq!(line.platform_fee_amount, 0);
        assert_eq!(line.gross().to_major_string().as_deref(), Some("19.99"));
    }

    #[test]
    fn flat_fee_needs_both_halves() {
        let with_currency: ShopFeeConfigEntry = serde_json::from_str(
            r#"{"schedule_id":"fee_1","fee_type":"merchant","flat_fee_amount":30,
                "flat_fee_currency":"USD"}"#,
        )
        .unwrap();
        assert_eq!(
            with_currency
                .flat_fee()
                .unwrap()
                .to_major_string()
                .as_deref(),
            Some("0.30")
        );

        // An amount with no currency is not an amount. Defaulting it to USD
        // is exactly the class of guess this SDK refuses to make.
        let without_currency: ShopFeeConfigEntry = serde_json::from_str(
            r#"{"schedule_id":"fee_1","fee_type":"merchant","flat_fee_amount":30}"#,
        )
        .unwrap();
        assert_eq!(without_currency.flat_fee(), None);
    }
}