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
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
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
//! The subscription models: subscriptions, their invoices, purchasable items,
//! and cost estimates.

use std::fmt;

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

use crate::core::models::common::{
    Currency, IntentStatus, InvoiceStatus, PaymentMethodType, SubscriptionPeriodUnit,
    SubscriptionStatus,
};
use crate::core::models::product::ProductPriceTaxBehavior;

/// A subscription, as returned by create / retrieve / update / list.
///
/// The confirm and create-and-confirm flows return
/// [`ConfirmSubscriptionResponse`] instead, which additionally carries the
/// billing-processor subscription ID and the buyer-approval `redirect_url`.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionResponse {
    /// Unique subscription ID.
    pub id: String,
    /// Current lifecycle status.
    pub status: SubscriptionStatus,

    /// Your own reference for this subscription.
    #[serde(default)]
    pub merchant_reference_id: Option<String>,
    /// Plan the subscription is on.
    #[serde(default)]
    pub plan_id: Option<String>,
    /// Price the subscription is billed at.
    #[serde(default)]
    pub item_price_id: Option<String>,
    /// Shop (business profile) ID the subscription belongs to.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Short-lived token used by client SDKs to authenticate confirm calls.
    /// Do not log or share it. Redacted in `Debug`.
    #[serde(default)]
    pub client_secret: Option<String>,
    /// Merchant account ID.
    #[serde(default)]
    pub merchant_id: Option<String>,
    /// Coupon applied at creation, if any.
    #[serde(default)]
    pub coupon_code: Option<String>,
    /// Customer the subscription bills.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// Payment leg for the current billing cycle, once a charge was attempted.
    #[serde(default)]
    pub payment: Option<SubscriptionPaymentData>,
    /// Invoice for the current billing cycle.
    #[serde(default)]
    pub invoice: Option<SubscriptionInvoice>,
    /// The catalog product the subscription bills, when it was created from
    /// one.
    #[serde(default)]
    pub product_id: Option<String>,
    /// The catalog price the subscription bills.
    #[serde(default)]
    pub price_id: Option<String>,
    /// The billing processor that runs the subscription.
    #[serde(default)]
    pub billing_processor: Option<String>,
    /// The billing processor's own subscription ID.
    #[serde(default)]
    pub billing_processor_subscription_id: Option<String>,
    /// ISO 8601 time the status last changed.
    #[serde(default)]
    pub status_changed_at: Option<String>,
    /// The state of the current cycle's renewal retries, after a renewal
    /// charge failed.
    #[serde(default)]
    pub renewal_retry: Option<RenewalRetryState>,
    /// How the buyer pays: `"card"`, `"paypal"` or `"processor_page"`.
    #[serde(default)]
    pub checkout_method: Option<String>,
    /// `true` while the buyer still has to choose how to pay. `false` from
    /// an older API.
    #[serde(default)]
    pub method_choice_pending: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written rather than derived: `client_secret` lets a client SDK confirm
// this subscription, so it is a bearer credential. Whether one was issued
// stays visible (`Some("[redacted]")` vs `None`) because that is usually the
// thing being debugged. Only the modeled field is covered -- `extra` prints
// in full.
impl fmt::Debug for SubscriptionResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SubscriptionResponse")
            .field("id", &self.id)
            .field("status", &self.status)
            .field("merchant_reference_id", &self.merchant_reference_id)
            .field("plan_id", &self.plan_id)
            .field("item_price_id", &self.item_price_id)
            .field("profile_id", &self.profile_id)
            .field(
                "client_secret",
                &self.client_secret.as_ref().map(|_| "[redacted]"),
            )
            .field("merchant_id", &self.merchant_id)
            .field("coupon_code", &self.coupon_code)
            .field("customer_id", &self.customer_id)
            .field("payment", &self.payment)
            .field("invoice", &self.invoice)
            .field("product_id", &self.product_id)
            .field("price_id", &self.price_id)
            .field("billing_processor", &self.billing_processor)
            .field(
                "billing_processor_subscription_id",
                &self.billing_processor_subscription_id,
            )
            .field("status_changed_at", &self.status_changed_at)
            .field("renewal_retry", &self.renewal_retry)
            .field("checkout_method", &self.checkout_method)
            .field("method_choice_pending", &self.method_choice_pending)
            .field("extra", &self.extra)
            .finish()
    }
}

/// The renewal retries of a subscription's current billing cycle.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RenewalRetryState {
    /// Charges of the current cycle that failed, the first renewal charge
    /// included.
    pub failed_attempts: i32,
    /// The first renewal charge plus the retries the recovery policy allows.
    /// `None` without a recovery policy.
    #[serde(default)]
    pub max_attempts: Option<i32>,
    /// ISO 8601 time of the next retry. `None` when no further retry runs.
    #[serde(default)]
    pub next_retry_at: Option<String>,
    /// The payment the buyer can make to recover the cycle.
    #[serde(default)]
    pub recovery_payment: Option<RenewalRecoveryPayment>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The payment a buyer can make to recover a failed renewal.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RenewalRecoveryPayment {
    /// The payment.
    pub payment_id: String,
    /// `"open"`, `"paid"`, `"closed"` or `"needs_reconciliation"`.
    pub status: String,
    /// The cycle's agreed amount, in minor units.
    pub amount: i64,
    /// Currency of `amount`.
    pub currency: Currency,
    /// The hosted page the buyer pays on. `None` until the payment exists.
    #[serde(default)]
    pub payment_link: Option<String>,
    /// ISO 8601 creation time.
    pub created_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The recovery payment announced on a lifecycle webhook.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RecoveryPaymentNotice {
    /// The payment to pay; its amount is the failed cycle's agreed amount.
    pub payment_id: String,
    /// The invoice for the cycle this payment settles.
    pub invoice_id: String,
    /// Amount due, in minor units.
    pub amount: i64,
    /// Currency of `amount`.
    pub currency: Currency,
    /// The hosted page the buyer pays on, when the payment has one.
    #[serde(default)]
    pub payment_link: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Returned by the create-and-confirm and confirm subscription calls.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConfirmSubscriptionResponse {
    /// Unique subscription ID.
    pub id: String,
    /// Current lifecycle status.
    pub status: SubscriptionStatus,

    /// Your own reference for this subscription.
    #[serde(default)]
    pub merchant_reference_id: Option<String>,
    /// Plan the subscription is on.
    #[serde(default)]
    pub plan_id: Option<String>,
    /// Price the subscription is billed at.
    #[serde(default)]
    pub item_price_id: Option<String>,
    /// Coupon applied, if any.
    #[serde(default)]
    pub coupon: Option<String>,
    /// Shop (business profile) ID the subscription belongs to.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Customer the subscription bills.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// Payment leg for the first billing cycle.
    #[serde(default)]
    pub payment: Option<SubscriptionPaymentData>,
    /// Invoice for the first billing cycle.
    #[serde(default)]
    pub invoice: Option<SubscriptionInvoice>,
    /// Subscription ID on the billing processor (Stripe Billing / PayPal).
    #[serde(default)]
    pub billing_processor_subscription_id: Option<String>,
    /// URL the customer must be redirected to in order to approve the
    /// subscription, for billing processors that require buyer approval (e.g.
    /// PayPal). `None` for processors that activate server-side.
    #[serde(default)]
    pub redirect_url: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Returned by `Subscriptions::pause`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PauseSubscriptionResponse {
    /// Unique subscription ID.
    pub id: String,
    /// Status after the pause took effect (or was scheduled).
    pub status: SubscriptionStatus,
    /// Your own reference for this subscription.
    #[serde(default)]
    pub merchant_reference_id: Option<String>,
    /// Shop (business profile) ID.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Merchant account ID.
    #[serde(default)]
    pub merchant_id: Option<String>,
    /// Customer the subscription bills.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// ISO 8601 timestamp the subscription was (or will be) paused at.
    #[serde(default)]
    pub paused_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Returned by `Subscriptions::resume`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ResumeSubscriptionResponse {
    /// Unique subscription ID.
    pub id: String,
    /// Status after resuming.
    pub status: SubscriptionStatus,
    /// Your own reference for this subscription.
    #[serde(default)]
    pub merchant_reference_id: Option<String>,
    /// Shop (business profile) ID.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Merchant account ID.
    #[serde(default)]
    pub merchant_id: Option<String>,
    /// Customer the subscription bills.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// ISO 8601 timestamp of the next billing cycle.
    #[serde(default)]
    pub next_billing_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Returned by `Subscriptions::cancel`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct CancelSubscriptionResponse {
    /// Unique subscription ID.
    pub id: String,
    /// Status after the cancellation took effect (or was scheduled).
    pub status: SubscriptionStatus,
    /// Your own reference for this subscription.
    #[serde(default)]
    pub merchant_reference_id: Option<String>,
    /// Shop (business profile) ID.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Merchant account ID.
    #[serde(default)]
    pub merchant_id: Option<String>,
    /// Customer the subscription billed.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// ISO 8601 timestamp the subscription was (or will be) cancelled at.
    #[serde(default)]
    pub cancelled_at: Option<String>,
    /// Whether the cancellation was performed the way it was asked for — see
    /// [`CancelModeOutcome`].
    ///
    /// Report it: a scheduled cancel a processor executed immediately is still
    /// a cancellation, and the merchant is owed the difference between what
    /// they asked for and what happened. `None` on a router that predates the
    /// field, which is `"unknown"` for display purposes — make no claim.
    #[serde(default)]
    pub cancel_mode_outcome: Option<CancelModeOutcome>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Payment leg attached to a subscription's current billing cycle, present
/// once a charge has been attempted.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionPaymentData {
    /// The payment intent charging this cycle.
    pub payment_id: String,
    /// Status of that payment intent.
    pub status: IntentStatus,
    /// Amount in minor units.
    #[serde(default)]
    pub amount: Option<i64>,
    /// Three-letter ISO 4217 currency code.
    #[serde(default)]
    pub currency: Option<Currency>,
    /// Next action to drive on the client (redirect, render QR, etc.).
    #[serde(default)]
    pub next_action: Option<Value>,
    /// Client secret for client-side confirmation. Do not log or share it:
    /// it authorises completing this charge. Redacted in `Debug`.
    #[serde(default)]
    pub client_secret: Option<String>,
    /// Gateway error code, if the charge failed.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Human-readable error message, if the charge failed.
    #[serde(default)]
    pub error_message: Option<String>,
    /// Payment method sub-type used.
    #[serde(default)]
    pub payment_method_type: Option<PaymentMethodType>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written for the same reason as `SubscriptionResponse`: this
// `client_secret` confirms the cycle's payment.
impl fmt::Debug for SubscriptionPaymentData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SubscriptionPaymentData")
            .field("payment_id", &self.payment_id)
            .field("status", &self.status)
            .field("amount", &self.amount)
            .field("currency", &self.currency)
            .field("next_action", &self.next_action)
            .field(
                "client_secret",
                &self.client_secret.as_ref().map(|_| "[redacted]"),
            )
            .field("error_code", &self.error_code)
            .field("error_message", &self.error_message)
            .field("payment_method_type", &self.payment_method_type)
            .field("extra", &self.extra)
            .finish()
    }
}

/// One resolved payment → subscription link.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionPaymentLink {
    /// The payment that was asked about.
    pub payment_id: String,
    /// The subscription that raised it.
    pub subscription_id: String,
    /// The invoice (billing cycle) the payment settles.
    pub invoice_id: String,
    /// Status of that invoice.
    pub invoice_status: InvoiceStatus,
    /// Whether the invoice's amount is a figure at all — see
    /// [`InvoiceAmountState`]. `None` on a router that predates the field.
    #[serde(default)]
    pub amount_state: Option<InvoiceAmountState>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The resolved subset of a batch of payment ids.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionPaymentLookupResponse {
    /// Only the payments that resolved to a subscription, in no guaranteed
    /// order.
    ///
    /// An id that is **absent** is not an error — it means "not a
    /// subscription payment". A page mixing the two is the normal case, so
    /// match on presence rather than expecting one entry per id.
    #[serde(default)]
    pub links: Vec<SubscriptionPaymentLink>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Whether an invoice's `amount` is a figure at all.
///
/// `"unpriced"` marks a **bootstrap placeholder**: the row exists to link the
/// local payment to the subscription, but nothing has priced it yet, so its
/// `amount` is not money. A hosted-checkout origination has no order until the
/// buyer pays, so the create response reports no invoice figure. Render such a
/// row as awaiting its first charge — never as `0.00`, and never inside a
/// total.
///
/// `"priced"` means there is a real figure: what the processor charged once it
/// has said, and what it quoted before that. It does **not** mean the cycle was
/// collected — `status` answers that, and the two move independently.
///
/// Rows written before the field existed keep an unmarked zero and report
/// `"priced"`. That is deliberate: an unmarked zero cannot be told apart from a
/// genuinely zero-priced invoice, so history was not relabelled.
///
/// Open-ended (`String`) so a state added later reaches the caller as data.
pub type InvoiceAmountState = String;

/// Whether a cancellation was performed the way it was asked for.
///
/// A processor can answer a scheduled cancel by cancelling immediately and name
/// nothing about the mode applied; the subscription really is cancelled, so the
/// merchant is owed a statement that the mode performed was not the mode
/// requested. Four states, because merging any pair misleads: `"unknown"` —
/// render as no claim — is not `"as_requested"`, and a cancellation performed
/// *earlier* than asked (`"executed_immediately"`) is not the same event as one
/// performed *later* (`"executed_later"`).
pub type CancelModeOutcome = String;

/// A single invoice raised for one billing cycle of a subscription.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionInvoice {
    /// Unique invoice ID.
    pub id: String,
    /// The subscription this invoice bills.
    pub subscription_id: String,
    /// Amount in minor units — money only when
    /// [`amount_state`](Self::amount_state) says so.
    pub amount: i64,
    /// Whether [`amount`](Self::amount) is a figure at all. See
    /// [`InvoiceAmountState`]; `None` on a router that predates the field.
    #[serde(default)]
    pub amount_state: Option<InvoiceAmountState>,
    /// Three-letter ISO 4217 currency code.
    pub currency: Currency,
    /// Invoice status. Independent of
    /// [`amount_state`](Self::amount_state): a priced cycle need not be
    /// collected, and an unpriced one is not a failed collection.
    pub status: InvoiceStatus,
    /// Merchant account ID.
    #[serde(default)]
    pub merchant_id: Option<String>,
    /// Shop (business profile) ID.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Customer billed.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// Payment intent charging this invoice, once one exists.
    #[serde(default)]
    pub payment_intent_id: Option<String>,
    /// Payment method charged.
    #[serde(default)]
    pub payment_method_id: Option<String>,
    /// This invoice's ID on the billing processor (Stripe Billing / PayPal).
    #[serde(default)]
    pub billing_processor_invoice_id: Option<String>,
    /// Connector (billing processor) the invoice was raised through.
    #[serde(default)]
    pub provider_name: Option<String>,
    /// The tax the billing processor added to this cycle's charge, in minor
    /// units. Part of `amount`, which stays what the buyer paid. `None` when
    /// the processor reported no tax.
    #[serde(default)]
    pub tax_amount: Option<i64>,
    /// The country `tax_amount` was charged for (ISO 3166-1 alpha-2).
    #[serde(default)]
    pub tax_country: Option<String>,
    /// `amount` without `tax_amount`, in minor units. `None` whenever
    /// `tax_amount` is.
    #[serde(default)]
    pub net_amount: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A purchasable price option for a subscription item (plan or addon).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionItemPrice {
    /// Unique price ID (pass as `item_price_id` when creating a subscription).
    pub price_id: String,
    /// Amount in minor units.
    pub amount: i64,
    /// Three-letter ISO 4217 currency code.
    pub currency: Currency,
    /// Plan or addon ID this price belongs to.
    #[serde(default)]
    pub item_id: Option<String>,
    /// Billing interval unit (`"Day"`, `"Week"`, `"Month"`, `"Year"`).
    #[serde(default)]
    pub interval: Option<SubscriptionPeriodUnit>,
    /// Number of interval units per billing cycle.
    #[serde(default)]
    pub interval_count: Option<i64>,
    /// Trial length, when the price includes one.
    #[serde(default)]
    pub trial_period: Option<i64>,
    /// Unit of `trial_period`.
    #[serde(default)]
    pub trial_period_unit: Option<SubscriptionPeriodUnit>,
    /// Whether the processor adds tax on top of `amount`. `None` when the
    /// processor does not say; the amount then includes it.
    #[serde(default)]
    pub tax_behavior: Option<ProductPriceTaxBehavior>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A subscription item (plan or addon) with its available prices, as returned
/// by `Subscriptions::items`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionItem {
    /// Unique item ID.
    pub item_id: String,
    /// Display name.
    pub name: String,
    /// Description, when set.
    #[serde(default)]
    pub description: Option<String>,
    /// Available prices for this item. Named `price_id` on the wire.
    #[serde(default, rename = "price_id")]
    pub prices: Vec<SubscriptionItemPrice>,
    /// Whether a subscription can be created on this item through this
    /// response: the processor offers it and at least one price could be
    /// stated.
    ///
    /// An unavailable item is still listed so the page stays complete, carries
    /// no prices, and **must not be offered** — a PayPal plan that is not
    /// `ACTIVE` or is priced by volume or tiers, or a Stripe product with no
    /// active recurring price at a single unit amount. `None` on a router that
    /// predates the field.
    #[serde(default)]
    pub available: Option<bool>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A single line of a subscription cost estimate.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionLineItem {
    /// Item this line bills.
    pub item_id: String,
    /// Item type, e.g. `"plan"`, `"addon"`.
    pub item_type: String,
    /// Line description.
    #[serde(default)]
    pub description: Option<String>,
    /// Amount in minor units.
    pub amount: i64,
    /// Three-letter ISO 4217 currency code.
    pub currency: Currency,
    /// Quantity billed.
    #[serde(default)]
    pub quantity: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Cost estimate for a subscription before creating it, as returned by
/// `Subscriptions::estimate`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionEstimateResponse {
    /// Total amount in minor units.
    pub amount: i64,
    /// Three-letter ISO 4217 currency code.
    pub currency: Currency,
    /// Plan estimated.
    #[serde(default)]
    pub plan_id: Option<String>,
    /// Price estimated.
    #[serde(default)]
    pub item_price_id: Option<String>,
    /// Coupon applied to the estimate.
    #[serde(default)]
    pub coupon_code: Option<String>,
    /// Customer the estimate was computed for.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// Line-by-line breakdown.
    #[serde(default)]
    pub line_items: Vec<SubscriptionLineItem>,
    /// Billing interval unit, when the connector exposes it.
    #[serde(default)]
    pub interval: Option<SubscriptionPeriodUnit>,
    /// Number of interval units per cycle, when known.
    #[serde(default)]
    pub interval_count: Option<i64>,
    /// Where the amount comes from: `"processor_estimate"` or
    /// `"plan_list_price"`. `None` from an older API.
    #[serde(default)]
    pub amount_source: Option<String>,
    /// `Exclusive` when the billing processor adds tax on top of `amount`
    /// (only a Creem list price can): show it as "plus tax", never as what the
    /// buyer pays. `None` from an older API.
    #[serde(default)]
    pub tax_behavior: Option<ProductPriceTaxBehavior>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

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

    #[test]
    fn subscription_response_decodes_catalog_billing_and_retry_fields() {
        let sub: SubscriptionResponse = serde_json::from_str(
            r#"{"id":"sub_1","status":"active","product_id":"prod_1","price_id":"prc_1",
                "billing_processor":"stripe","billing_processor_subscription_id":"sub_ext",
                "status_changed_at":"2026-09-01T00:00:00Z","checkout_method":"paypal",
                "method_choice_pending":true,
                "renewal_retry":{"failed_attempts":2,"max_attempts":4,"next_retry_at":null,
                    "recovery_payment":{"payment_id":"pay_9","status":"open","amount":999,
                        "currency":"EUR","created_at":"2026-09-02T00:00:00Z"}}}"#,
        )
        .unwrap();
        assert_eq!(sub.product_id.as_deref(), Some("prod_1"));
        assert_eq!(sub.checkout_method.as_deref(), Some("paypal"));
        assert!(sub.method_choice_pending);
        let retry = sub.renewal_retry.as_ref().unwrap();
        assert_eq!(retry.failed_attempts, 2);
        assert_eq!(retry.recovery_payment.as_ref().unwrap().status, "open");

        let price: SubscriptionItemPrice = serde_json::from_str(
            r#"{"price_id":"prod_1","amount":1000,"currency":"EUR","tax_behavior":"exclusive"}"#,
        )
        .unwrap();
        assert_eq!(price.tax_behavior, Some(ProductPriceTaxBehavior::Exclusive));

        let estimate: SubscriptionEstimateResponse = serde_json::from_str(
            r#"{"amount":999,"currency":"EUR","amount_source":"plan_list_price"}"#,
        )
        .unwrap();
        assert_eq!(estimate.amount_source.as_deref(), Some("plan_list_price"));

        let webhook: LifecycleWebhook = serde_json::from_str(
            r#"{"id":"sub_1","subscription_id":"sub_1","customer_id":"cus_1","profile_id":"pro_1",
                "status":"past_due","transition_id":"tr_1",
                "recovery_payment":{"payment_id":"pay_9","invoice_id":"inv_9","amount":999,
                    "currency":"EUR","payment_link":"https://checkout.test/pay/pl_9"}}"#,
        )
        .unwrap();
        let notice = webhook.recovery_payment.as_ref().unwrap();
        assert_eq!(notice.invoice_id, "inv_9");
        assert_eq!(notice.amount, 999);
    }

    /// Kills a `Debug` that prints `&self.client_secret` on the subscription.
    #[test]
    fn subscription_response_debug_redacts_the_client_secret() {
        let res: SubscriptionResponse = serde_json::from_str(
            r#"{"id":"sub_1","status":"active","client_secret":"sub_1_secret_xyz"}"#,
        )
        .unwrap();
        let printed = format!("{res:?}");

        assert!(!printed.contains("sub_1_secret_xyz"));
        assert!(printed.contains("client_secret: Some(\"[redacted]\")"));
        assert!(printed.contains("sub_1"));
    }

    /// Kills a `Debug` that hard-codes the redaction marker.
    #[test]
    fn subscription_response_debug_shows_none_when_no_client_secret() {
        let res: SubscriptionResponse =
            serde_json::from_str(r#"{"id":"sub_1","status":"active"}"#).unwrap();
        assert!(format!("{res:?}").contains("client_secret: None"));
    }

    /// The nested payment leg carries its own secret; a redaction on the outer
    /// struct alone would still leak it, since `payment` is printed whole.
    #[test]
    fn subscription_payment_data_debug_redacts_the_client_secret() {
        let res: SubscriptionResponse = serde_json::from_str(
            r#"{"id":"sub_1","status":"active","payment":{"payment_id":"pay_1",
                "status":"requires_confirmation","client_secret":"pay_1_secret_nested"}}"#,
        )
        .unwrap();
        let printed = format!("{res:?}");

        assert!(!printed.contains("pay_1_secret_nested"));
        assert!(printed.contains("pay_1"));
    }

    #[test]
    fn subscription_payment_data_debug_shows_none_when_no_client_secret() {
        let data: SubscriptionPaymentData =
            serde_json::from_str(r#"{"payment_id":"pay_1","status":"succeeded"}"#).unwrap();
        assert!(format!("{data:?}").contains("client_secret: None"));
    }
}

/// The subscription snapshot carried by a lifecycle webhook.
///
/// Delivered under `content.type: "subscription_details"` for the lifecycle
/// event types — `subscription_created`, `subscription_active`,
/// `subscription_past_due`, `subscription_paused`, `subscription_resumed`,
/// `subscription_cancelled`, `subscription_expired` and
/// `invoice_payment_failed`. `invoice_paid` keeps its
/// [`ConfirmSubscriptionResponse`] payload byte for byte, so the presence of
/// [`transition_id`](Self::transition_id) is what tells the two apart.
///
/// A **scheduled** cancellation fires `subscription_cancelled` while the status
/// is still `"active"`, with
/// [`cancel_at_period_end`](Self::cancel_at_period_end) `true`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct LifecycleWebhook {
    /// The subscription's own id, as `id`.
    pub id: String,
    /// The subscription's id again, under the name the rest of the API uses.
    pub subscription_id: String,
    /// The merchant's own reference for the subscription, when it set one.
    #[serde(default)]
    pub merchant_reference_id: Option<String>,
    /// The customer the subscription belongs to.
    pub customer_id: String,
    /// The shop (business profile) the subscription belongs to.
    pub profile_id: String,
    /// The subscription's status at this transition.
    pub status: SubscriptionStatus,
    /// The provider's own subscription identifier.
    #[serde(default)]
    pub billing_processor_subscription_id: Option<String>,
    /// The plan the subscription runs on, when the provider names one.
    #[serde(default)]
    pub plan_id: Option<String>,
    /// The price the subscription runs on, when the provider names one.
    #[serde(default)]
    pub item_price_id: Option<String>,
    /// Identifies this transition, and is **stable across delivery retries**:
    /// deduplicate on it rather than on the event id.
    pub transition_id: String,
    /// Which environment the subscription runs in.
    #[serde(default)]
    pub test_mode: Option<bool>,
    /// End of the current billing period (UTC). Provider-reported: `None` means
    /// unknown, not "no period".
    #[serde(default)]
    pub current_period_end: Option<String>,
    /// When the provider recorded the cancellation.
    #[serde(default)]
    pub cancelled_at: Option<String>,
    /// Why it was cancelled, when the provider supplies a reason.
    #[serde(default)]
    pub cancellation_reason: Option<String>,
    /// Whether the cancellation takes effect at the end of the paid period
    /// rather than immediately.
    #[serde(default)]
    pub cancel_at_period_end: Option<bool>,
    /// On `subscription_recovery_payment_created`: the payment the buyer can
    /// make to recover a failed renewal.
    #[serde(default)]
    pub recovery_payment: Option<RecoveryPaymentNotice>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// --- Native enrollment and renewal recovery settings --------------------

/// How a failed renewal is recovered once its off-session charges have
/// failed: `"off"`, or `"buyer_link"` (a payment the buyer pays on the hosted
/// page).
///
/// A string rather than an enum, so a mode added later still decodes.
pub type NativeRecoveryMode = String;

/// A shop's native enrollment settings, returned by
/// [`Subscriptions::native_config`](crate::resources::subscriptions::Subscriptions::native_config)
/// and
/// [`Subscriptions::update_native_config`](crate::resources::subscriptions::Subscriptions::update_native_config).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NativeShopConfigResponse {
    /// Whether new card subscriptions can be enrolled natively on this shop.
    pub enabled: bool,
    /// The payment account new enrollments charge through, when one is
    /// selected.
    #[serde(default)]
    pub payment_connector_id: Option<String>,
    /// Whether enrollments run in the test environment.
    pub test_mode: bool,
    /// The connectors whose accounts the shop may choose for new card
    /// subscriptions, e.g. `"stripe"`.
    #[serde(default)]
    pub eligible_connectors: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The merchant-wide renewal recovery settings.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NativeDunningConfigResponse {
    /// Whether failed renewals are retried.
    pub enabled: bool,
    /// Retry days, as offsets from the first failed charge.
    #[serde(default)]
    pub retry_days: Vec<i32>,
    /// Charges per cycle, the opening attempt included.
    pub max_attempts: i32,
    /// Whether the subscription is cancelled once every attempt has failed.
    pub cancel_after_exhaustion: bool,
    /// What follows the failed off-session charges.
    pub recovery_mode: NativeRecoveryMode,
    /// Off-session charges of a cycle before the buyer recovery link, the
    /// first renewal charge included.
    pub recovery_after_attempt: i32,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Which lifecycle actions an existing subscription supports.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionCapabilities {
    /// The subscription can be paused with immediate effect.
    pub pause_immediately: bool,
    /// The subscription can be resumed with immediate effect.
    pub resume_immediately: bool,
    /// The subscription can be cancelled with immediate effect.
    pub cancel_immediately: bool,
    /// The subscription can be cancelled at the end of the paid period.
    pub cancel_at_period_end: bool,
    /// The subscription's plan can be changed.
    pub change_plan: bool,
    /// Pausing voids the invoices raised while it is paused.
    pub pause_voids_invoices: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// --- Adoption and import -------------------------------------------------

/// The result of taking a subscription already running at its billing
/// processor into DeloPay.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct AdoptSubscriptionResponse {
    /// The DeloPay subscription that now holds it.
    pub subscription_id: String,
    /// `false` when DeloPay already held the subscription: repeating an
    /// adoption returns the existing ID.
    pub adopted: bool,
    /// The billing processor, e.g. `"creem"`.
    pub billing_processor: String,
    /// The billing account it runs on.
    #[serde(default)]
    pub merchant_connector_id: Option<String>,
    /// The processor's own subscription ID.
    #[serde(default)]
    pub external_subscription_id: Option<String>,
    /// Current lifecycle status.
    pub status: SubscriptionStatus,
    /// The DeloPay customer it belongs to.
    pub customer_id: String,
    /// The shop (business profile) it belongs to.
    pub profile_id: String,
    /// Your own reference for the subscription.
    #[serde(default)]
    pub merchant_reference_id: Option<String>,
    /// The plan it runs on.
    #[serde(default)]
    pub plan_id: Option<String>,
    /// The price it runs on.
    #[serde(default)]
    pub item_price_id: Option<String>,
    /// Which environment it runs in.
    #[serde(default)]
    pub test_mode: Option<bool>,
    /// When it was adopted (ISO 8601).
    #[serde(default)]
    pub adopted_at: Option<String>,
    /// Whether the adoption was confirmed as stored. Retry the adoption when
    /// `false`. It does not say that your own integration stopped handling
    /// the processor's events.
    pub handoff_confirmed: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Why the import cannot list, offer or take over a subscription, as a code
/// to word: e.g. `"listing_unsupported"`, `"adoption_disabled"`.
///
/// A string rather than an enum, so a reason added later still decodes.
pub type SubscriptionImportReason = String;

/// How a processor subscription relates to DeloPay: `"new"`,
/// `"needs_customer"`, `"held"`, `"ended"` or `"not_adoptable"`.
pub type SubscriptionImportClassification = String;

/// What taking one subscription over did: `"adopted"`, `"already_held"` or
/// `"failed"`.
pub type SubscriptionImportOutcome = String;

/// What the import can do on one billing processor.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionImportCapabilities {
    /// The connector behind the billing account.
    pub connector: String,
    /// Whether the processor lets its subscriptions be listed at all.
    pub listing: bool,
    /// Whether a listed subscription can be taken over here.
    pub adoption: bool,
    /// Why `listing` or `adoption` is `false`, in English.
    #[serde(default)]
    pub reason: Option<String>,
    /// The same, as a code.
    #[serde(default)]
    pub reason_code: Option<SubscriptionImportReason>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// How many listed subscriptions fell into each classification.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionImportCounts {
    /// Not held by DeloPay, and the buyer is a DeloPay customer.
    #[serde(default)]
    pub new: i32,
    /// Not held by DeloPay, and the buyer is not yet a DeloPay customer.
    #[serde(default)]
    pub needs_customer: i32,
    /// Already held by DeloPay.
    #[serde(default)]
    pub held: i32,
    /// Ended at the processor.
    #[serde(default)]
    pub ended: i32,
    /// Cannot be taken over here.
    #[serde(default)]
    pub not_adoptable: i32,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One subscription the processor holds, as the import classifies it.
///
/// `Debug` shows whether a buyer email was reported, never the address.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionImportItem {
    /// The processor's ID for the subscription.
    pub external_subscription_id: String,
    /// The processor's status, as it reports it.
    pub provider_status: String,
    /// That status in DeloPay's terms, when it maps to one.
    #[serde(default)]
    pub status: Option<SubscriptionStatus>,
    /// The processor's product or price it bills on.
    #[serde(default)]
    pub item_price_id: Option<String>,
    /// The processor's ID for the buyer.
    #[serde(default)]
    pub connector_customer_id: Option<String>,
    /// The buyer's email at the processor, when it reports one.
    #[serde(default)]
    pub customer_email: Option<String>,
    /// The DeloPay customer recorded as that buyer at this account.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// How it relates to DeloPay.
    pub classification: SubscriptionImportClassification,
    /// The DeloPay subscription that holds it, when one does.
    #[serde(default)]
    pub subscription_id: Option<String>,
    /// Why it is `not_adoptable`, in English.
    #[serde(default)]
    pub note: Option<String>,
    /// The same, as a code.
    #[serde(default)]
    pub note_code: Option<SubscriptionImportReason>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written rather than derived: `customer_email` is the buyer's personal
// data and must not reach logs. Whether one was reported stays visible.
impl fmt::Debug for SubscriptionImportItem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SubscriptionImportItem")
            .field("external_subscription_id", &self.external_subscription_id)
            .field("provider_status", &self.provider_status)
            .field("status", &self.status)
            .field("item_price_id", &self.item_price_id)
            .field("connector_customer_id", &self.connector_customer_id)
            .field(
                "customer_email",
                &self.customer_email.as_ref().map(|_| "[redacted]"),
            )
            .field("customer_id", &self.customer_id)
            .field("classification", &self.classification)
            .field("subscription_id", &self.subscription_id)
            .field("note", &self.note)
            .field("note_code", &self.note_code)
            .field("extra", &self.extra)
            .finish()
    }
}

/// What a billing account holds at its processor, classified against
/// DeloPay's subscriptions.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionImportPreviewResponse {
    /// What the import can do on this processor.
    pub capabilities: SubscriptionImportCapabilities,
    /// How many items fell into each classification.
    pub counts: SubscriptionImportCounts,
    /// `true` when the processor may hold more subscriptions than were read:
    /// only those in [`items`](Self::items) were classified.
    #[serde(default)]
    pub truncated: bool,
    /// The subscriptions read.
    #[serde(default)]
    pub items: Vec<SubscriptionImportItem>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One selection's import result.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionImportResult {
    /// The processor's ID for the subscription.
    pub external_subscription_id: String,
    /// What taking it over did.
    pub outcome: SubscriptionImportOutcome,
    /// The DeloPay subscription that holds it now, unless it failed.
    #[serde(default)]
    pub subscription_id: Option<String>,
    /// Why it failed, in English.
    #[serde(default)]
    pub reason: Option<String>,
    /// The same, as a code.
    #[serde(default)]
    pub reason_code: Option<SubscriptionImportReason>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The results of an import, one per selection in request order.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionImportApplyResponse {
    /// One result per selection, in request order.
    #[serde(default)]
    pub results: Vec<SubscriptionImportResult>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// --- Sync with the billing processor ------------------------------------

/// What reading one subscription back from its processor did: `"updated"`,
/// `"unchanged"`, `"undated"`, `"not_at_processor"`, `"not_found"` or
/// `"failed"`.
pub type SubscriptionSyncOutcome = String;

/// One read of a subscription at its billing processor.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionProviderRead {
    /// The processor's own ID for the subscription.
    pub billing_processor_subscription_id: String,
    /// The status the processor reports, when it maps to one.
    #[serde(default)]
    pub status: Option<SubscriptionStatus>,
    /// When the processor says that status last changed (ISO 8601).
    #[serde(default)]
    pub status_changed_at: Option<String>,
    /// The plan the processor bills on now, as an `item_price_id`.
    #[serde(default)]
    pub item_price_id: Option<String>,
    /// The processor's own ID for the buyer.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// When it was read (ISO 8601).
    pub read_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One subscription's sync result.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionSyncResult {
    /// The subscription that was read.
    pub subscription_id: String,
    /// What the read did.
    pub outcome: SubscriptionSyncOutcome,
    /// The status the subscription holds after the sync.
    #[serde(default)]
    pub status: Option<SubscriptionStatus>,
    /// What the processor reported, when it was read. A status here that
    /// differs from [`status`](Self::status) is one that could not be taken:
    /// undated, or older than an event already recorded.
    #[serde(default)]
    pub provider: Option<SubscriptionProviderRead>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The results of a batch sync, one per requested ID in request order.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionSyncResponse {
    /// One result per requested ID, in request order.
    #[serde(default)]
    pub results: Vec<SubscriptionSyncResult>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// --- Billing history and processor identity -----------------------------

/// One subscription's billing history, newest cycle first.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionInvoiceListResponse {
    /// Recorded billing cycles, newest first.
    #[serde(default)]
    pub invoices: Vec<SubscriptionInvoice>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The billing processor a shop's subscriptions run on.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionBillingProcessorResponse {
    /// The billing account named as the shop's billing processor.
    pub merchant_connector_id: String,
    /// The connector behind it, e.g. `"creem"`, `"paypal"` or
    /// `"stripebilling"`.
    pub connector_name: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}