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
//! Prepaid platform-fee billing models: the billing profile, card-setup
//! handshake, top-ups, the balance ledger, blocked attempts, and per-shop
//! allocations.
//!
//! All money fields are integers in minor units, matching the rest of the
//! wire models. Percentages (the volume-tier `rate`) are `f64` because the
//! API sends them as decimals.
use serde::Deserialize;
use serde_json::Value;
use crate::core::models::common::Currency;
/// Billing lifecycle status of a merchant, e.g. `"active"`, `"suspended"`,
/// `"setup_incomplete"`. Open vocabulary — kept as a string so a new backend
/// value cannot break deserialization.
pub type BillingStatus = String;
/// What caused a suspension: `"auto_recharge"` (automatic, lifted by a
/// successful top-up) or `"admin"` (sticky, lifted only by an admin).
pub type SuspensionSource = String;
/// Status of a per-shop balance allocation, e.g. `"active"`, `"suspended"`.
pub type AllocationStatus = String;
/// Why a payment attempt was rejected by the billing gate:
/// `"billing_suspended"`, `"billing_setup_incomplete"`, or
/// `"allocation_suspended"`.
pub type BlockReason = String;
/// Auto-recharge configuration on a [`BillingProfileResponse`].
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct AutoRechargeConfig {
/// Whether auto-recharge is enabled.
pub enabled: bool,
/// Balance (minor units) at or below which a recharge is triggered.
pub threshold_amount: i64,
/// Amount (minor units) charged when a recharge triggers.
pub recharge_amount: i64,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// The merchant's currently-locked platform-fee volume tier.
///
/// Tier 6 ("Custom" / Enterprise) sets [`is_custom`](Self::is_custom) and
/// leaves [`rate`](Self::rate) unset — those merchants are charged at the
/// Tier 5 rate until Delopay writes a negotiated per-merchant fee schedule.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct TierSummary {
/// 1 (Starter) through 6 (Enterprise).
pub level: i64,
/// Human-readable tier name, e.g. `"Growth"`.
pub name: String,
/// True when this is the custom (Tier 6) tier with no published rate.
pub is_custom: bool,
/// Percentage as a decimal — `3.5` means 3.50%. Absent for the custom
/// tier.
#[serde(default)]
pub rate: Option<f64>,
/// ISO date (`YYYY-MM-DD`) the locked tier expires; the next monthly
/// snapshot recomputes it.
#[serde(default)]
pub locked_until: Option<String>,
/// Volume in USD minor units that produced the current tier.
#[serde(default)]
pub volume_usd_minor: Option<i64>,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// A merchant's billing profile: prepaid balance, billing status and
/// auto-recharge configuration.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct BillingProfileResponse {
/// Unique billing profile ID.
pub id: String,
/// Merchant account this profile belongs to.
pub merchant_id: String,
/// Whether a card is on file for auto-recharge and manual top-ups.
pub has_payment_method: bool,
/// Current prepaid balance, in minor units.
pub balance_amount: i64,
/// Currency the balance is denominated in.
pub balance_currency: Currency,
/// Current billing status.
pub billing_status: BillingStatus,
/// Auto-recharge configuration.
pub auto_recharge: AutoRechargeConfig,
/// Balance (minor units) below which payments are refused outright.
pub hard_floor_amount: i64,
/// How many auto-recharge attempts have failed in a row.
pub consecutive_recharge_failures: i64,
/// Whether the merchant is on the trusted list. Trusted merchants are
/// exempt from automatic *and* manual suspension until the flag clears.
pub is_trusted: bool,
/// Stripe customer holding the saved card, when setup is complete.
#[serde(default)]
pub stripe_customer_id: Option<String>,
/// When the merchant was suspended, if it is.
#[serde(default)]
pub suspended_at: Option<String>,
/// What caused the current suspension. Absent when not suspended.
#[serde(default)]
pub suspension_source: Option<SuspensionSource>,
/// Admin-provided reason for a manual suspension. Absent otherwise.
#[serde(default)]
pub suspension_reason: Option<String>,
/// ISO 8601 creation timestamp.
#[serde(default)]
pub created_at: Option<String>,
/// ISO 8601 last-modified timestamp.
#[serde(default)]
pub modified_at: Option<String>,
/// Volume tier the merchant is currently locked to. Omitted on legacy
/// profiles created before tiers existed.
#[serde(default)]
pub current_tier: Option<TierSummary>,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// The card-setup handshake: everything the frontend needs to render a Stripe
/// card element and confirm the SetupIntent.
///
/// [`Debug`] is hand-written and redacts
/// [`setup_intent_client_secret`](Self::setup_intent_client_secret); see the
/// impl.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct BillingSetupResponse {
/// Billing profile the setup belongs to.
pub billing_profile_id: String,
/// Merchant account the setup belongs to.
pub merchant_id: String,
/// Stripe customer the card will be attached to.
pub stripe_customer_id: String,
/// The Stripe SetupIntent to confirm client-side.
pub setup_intent_id: String,
/// **Client secret for the SetupIntent.** Hand it to the frontend over a
/// trusted channel and never log it: it authorizes confirming this
/// SetupIntent.
pub setup_intent_client_secret: String,
/// Billing status after starting setup.
pub billing_status: BillingStatus,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
// Hand-written rather than derived: the client secret authorizes confirming
// the SetupIntent, and a `{:?}` on a setup response is exactly what ends up in
// a log line. `extra` is printed as key names only — a backend that started
// returning another secret under a new name would otherwise leak it through
// the catch-all map.
impl std::fmt::Debug for BillingSetupResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let extra_keys: Vec<&str> = self.extra.keys().map(String::as_str).collect();
f.debug_struct("BillingSetupResponse")
.field("billing_profile_id", &self.billing_profile_id)
.field("merchant_id", &self.merchant_id)
.field("stripe_customer_id", &self.stripe_customer_id)
.field("setup_intent_id", &self.setup_intent_id)
.field("setup_intent_client_secret", &"[redacted]")
.field("billing_status", &self.billing_status)
.field("extra_keys", &extra_keys)
.finish_non_exhaustive()
}
}
/// The result of a manual balance top-up.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct TopupResponse {
/// Stripe PaymentIntent that charged the saved card.
pub payment_intent_id: String,
/// Status of that charge, e.g. `"succeeded"`.
pub status: String,
/// Amount charged, in minor units.
pub amount: i64,
/// Currency of the charge.
pub currency: Currency,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// One credit or debit against the prepaid balance.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct LedgerEntry {
/// Unique ledger row ID.
pub id: String,
/// What kind of movement this is, e.g. `"topup"`, `"fee"`.
pub entry_type: String,
/// Signed amount, in minor units.
pub amount: i64,
/// Currency of [`amount`](Self::amount).
pub currency: Currency,
/// What the entry refers to, e.g. `"payment"`, `"allocation"`.
pub reference_kind: String,
/// ID of the referenced object.
pub reference_id: String,
/// Balance after this entry was applied, in minor units.
pub balance_after: i64,
/// ISO 8601 creation timestamp.
#[serde(default)]
pub created_at: Option<String>,
/// Pre-conversion amount, when the entry was converted.
#[serde(default)]
pub original_amount: Option<i64>,
/// Currency of [`original_amount`](Self::original_amount).
#[serde(default)]
pub original_currency: Option<Currency>,
/// Free-text description.
#[serde(default)]
pub description: Option<String>,
/// Shop (business profile) the entry is attributed to.
#[serde(default)]
pub profile_id: Option<String>,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// A page of the balance ledger.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct LedgerResponse {
/// The ledger entries in this page.
#[serde(default = "Vec::new")]
pub entries: Vec<LedgerEntry>,
/// Total number of matching entries, when the API reports it.
#[serde(default)]
pub total_count: Option<i64>,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// A payment attempt rejected by the billing suspension gate before any
/// payment was created.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct BlockedAttempt {
/// Unique ID of the blocked-attempt record.
pub id: String,
/// Merchant the attempt was made against.
pub merchant_id: String,
/// The payment ID the caller tried to use.
pub payment_id: String,
/// Why the attempt was rejected.
pub block_reason: BlockReason,
/// ISO 8601 creation timestamp.
#[serde(default)]
pub created_at: Option<String>,
/// Shop (business profile) the attempt targeted.
#[serde(default)]
pub profile_id: Option<String>,
/// What caused the suspension, when the merchant was suspended.
#[serde(default)]
pub suspension_source: Option<SuspensionSource>,
/// Attempted amount, in minor units.
#[serde(default)]
pub amount: Option<i64>,
/// Currency of [`amount`](Self::amount).
#[serde(default)]
pub currency: Option<Currency>,
/// Billing status at the time of the attempt.
#[serde(default)]
pub billing_status: Option<BillingStatus>,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// A page of blocked payment attempts.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct BlockedAttemptListResponse {
/// The blocked attempts in this page.
#[serde(default = "Vec::new")]
pub entries: Vec<BlockedAttempt>,
/// Total number of matching attempts, when the API reports it.
#[serde(default)]
pub total_count: Option<i64>,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// A shop's prepaid balance allocation, funded from the host merchant
/// treasury.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct AllocationResponse {
/// Unique allocation ID.
pub id: String,
/// Host merchant that owns the treasury.
pub merchant_id: String,
/// Shop (business profile) the allocation belongs to.
pub profile_id: String,
/// Allocated balance, in minor units.
pub balance_amount: i64,
/// Currency of [`balance_amount`](Self::balance_amount).
pub balance_currency: Currency,
/// Current allocation status.
pub allocation_status: AllocationStatus,
/// ISO 8601 creation timestamp.
#[serde(default)]
pub created_at: Option<String>,
/// ISO 8601 last-modified timestamp.
#[serde(default)]
pub modified_at: Option<String>,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// Every shop allocation for a merchant.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct AllocationListResponse {
/// The allocations.
#[serde(default = "Vec::new")]
pub allocations: Vec<AllocationResponse>,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// The result of moving funds between the host treasury and a shop
/// allocation: both sides' balances after the move, plus the ledger row.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct AllocationTransferResponse {
/// Allocation that was credited or debited.
pub allocation_id: String,
/// Shop (business profile) the allocation belongs to.
pub profile_id: String,
/// Allocation balance after the transfer, in minor units.
pub allocation_balance: i64,
/// Host treasury balance after the transfer, in minor units.
pub host_balance: i64,
/// Ledger row recording the movement.
pub ledger_entry_id: String,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[cfg(test)]
mod tests {
use super::*;
const SETUP_JSON: &str = r#"{
"billing_profile_id": "bp_1",
"merchant_id": "merch_1",
"stripe_customer_id": "cus_1",
"setup_intent_id": "seti_1",
"setup_intent_client_secret": "seti_1_secret_supersecretvalue",
"billing_status": "setup_incomplete"
}"#;
/// The client secret must never reach a `{:?}`; deriving `Debug` on
/// `BillingSetupResponse` makes this fail.
#[test]
fn setup_response_debug_redacts_the_client_secret() {
let setup: BillingSetupResponse = serde_json::from_str(SETUP_JSON).unwrap();
let printed = format!("{setup:?}");
assert!(
!printed.contains("seti_1_secret_supersecretvalue"),
"client secret leaked into Debug output: {printed}"
);
assert!(printed.contains("[redacted]"));
// The non-secret metadata is still useful for debugging.
assert!(printed.contains("bp_1"));
}
/// A backend that returned another secret under an unmodeled name would
/// land in `extra`; only its key names may be printed.
#[test]
fn setup_response_debug_hides_extra_values() {
let mut setup: BillingSetupResponse = serde_json::from_str(SETUP_JSON).unwrap();
setup.extra.insert(
"client_secret".to_string(),
Value::String("another_secret".to_string()),
);
let printed = format!("{setup:?}");
assert!(
!printed.contains("another_secret"),
"an unmodeled secret leaked through `extra`: {printed}"
);
assert!(printed.contains("client_secret"));
}
#[test]
fn billing_profile_decodes_nested_config_and_keeps_unknown_fields() {
let profile: BillingProfileResponse = serde_json::from_str(
r#"{
"id": "bp_1",
"merchant_id": "merch_1",
"has_payment_method": true,
"balance_amount": 12345,
"balance_currency": "USD",
"billing_status": "active",
"auto_recharge": {
"enabled": true,
"threshold_amount": 1000,
"recharge_amount": 20000
},
"hard_floor_amount": -500,
"consecutive_recharge_failures": 0,
"is_trusted": false,
"created_at": "2026-01-01T00:00:00Z",
"modified_at": "2026-01-02T00:00:00Z",
"current_tier": {
"level": 3,
"name": "Growth",
"is_custom": false,
"rate": 3.5,
"volume_usd_minor": 900000
},
"brand_new_field": "keep me"
}"#,
)
.unwrap();
assert_eq!(profile.balance_amount, 12345);
assert_eq!(profile.hard_floor_amount, -500);
assert!(profile.auto_recharge.enabled);
assert_eq!(profile.auto_recharge.threshold_amount, 1000);
let tier = profile.current_tier.expect("current_tier decodes");
assert_eq!(tier.level, 3);
assert_eq!(tier.rate, Some(3.5));
assert_eq!(tier.locked_until, None);
assert_eq!(profile.extra["brand_new_field"], "keep me");
}
#[test]
fn billing_profile_tolerates_a_custom_tier_without_a_rate() {
let profile: BillingProfileResponse = serde_json::from_str(
r#"{
"id": "bp_1",
"merchant_id": "merch_1",
"has_payment_method": false,
"balance_amount": 0,
"balance_currency": "EUR",
"billing_status": "suspended",
"auto_recharge": {"enabled": false, "threshold_amount": 0, "recharge_amount": 0},
"hard_floor_amount": 0,
"consecutive_recharge_failures": 3,
"is_trusted": false,
"suspension_source": "auto_recharge",
"current_tier": {"level": 6, "name": "Custom", "is_custom": true, "rate": null}
}"#,
)
.unwrap();
let tier = profile.current_tier.expect("current_tier decodes");
assert!(tier.is_custom);
assert_eq!(tier.rate, None);
assert_eq!(
profile.suspension_source.as_deref(),
Some("auto_recharge"),
"suspension_source must survive decoding"
);
assert_eq!(profile.created_at, None);
}
#[test]
fn ledger_and_blocked_attempt_pages_decode_their_entries() {
let ledger: LedgerResponse = serde_json::from_str(
r#"{
"entries": [{
"id": "led_1",
"entry_type": "fee",
"amount": -250,
"currency": "USD",
"reference_kind": "payment",
"reference_id": "pay_1",
"balance_after": 9750,
"created_at": "2026-01-01T00:00:00Z",
"profile_id": "pro_1"
}],
"total_count": 1
}"#,
)
.unwrap();
assert_eq!(ledger.total_count, Some(1));
assert_eq!(ledger.entries[0].amount, -250);
assert_eq!(ledger.entries[0].balance_after, 9750);
assert_eq!(ledger.entries[0].profile_id.as_deref(), Some("pro_1"));
let blocked: BlockedAttemptListResponse = serde_json::from_str(
r#"{"entries": [{
"id": "blk_1",
"merchant_id": "merch_1",
"payment_id": "pay_1",
"block_reason": "billing_suspended",
"created_at": "2026-01-01T00:00:00Z",
"amount": 1000
}]}"#,
)
.unwrap();
assert_eq!(blocked.total_count, None);
assert_eq!(blocked.entries[0].block_reason, "billing_suspended");
assert_eq!(blocked.entries[0].amount, Some(1000));
assert_eq!(blocked.entries[0].currency, None);
}
#[test]
fn allocation_shapes_decode() {
let list: AllocationListResponse = serde_json::from_str(
r#"{"allocations": [{
"id": "alc_1",
"merchant_id": "merch_1",
"profile_id": "pro_1",
"balance_amount": 5000,
"balance_currency": "USD",
"allocation_status": "active",
"created_at": "2026-01-01T00:00:00Z",
"modified_at": "2026-01-02T00:00:00Z"
}]}"#,
)
.unwrap();
assert_eq!(list.allocations[0].balance_amount, 5000);
assert_eq!(list.allocations[0].allocation_status, "active");
let transfer: AllocationTransferResponse = serde_json::from_str(
r#"{
"allocation_id": "alc_1",
"profile_id": "pro_1",
"allocation_balance": 5250,
"host_balance": 4750,
"ledger_entry_id": "led_9"
}"#,
)
.unwrap();
assert_eq!(transfer.allocation_balance, 5250);
assert_eq!(transfer.host_balance, 4750);
assert_eq!(transfer.ledger_entry_id, "led_9");
}
#[test]
fn topup_response_decodes_minor_units() {
let topup: TopupResponse = serde_json::from_str(
r#"{"payment_intent_id":"pi_1","status":"succeeded","amount":20000,"currency":"USD"}"#,
)
.unwrap();
assert_eq!(topup.amount, 20000);
assert_eq!(topup.payment_intent_id, "pi_1");
assert_eq!(topup.currency, "USD");
}
}