Skip to main content

longbridge/asset/
types.rs

1use num_enum::{FromPrimitive, IntoPrimitive};
2use rust_decimal::Decimal;
3use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
4use time::OffsetDateTime;
5
6use crate::serde_utils;
7
8/// Response for get statement data list request
9#[derive(Debug, Clone, Default, Serialize, Deserialize)]
10pub struct GetStatementListResponse {
11    /// Available statement entries
12    pub list: Vec<StatementItem>,
13}
14
15/// Statement data info
16#[derive(Debug, Clone, Default, Serialize, Deserialize)]
17pub struct StatementItem {
18    /// Statement date as `YYYYMM` (e.g. `202401`)
19    pub dt: i32,
20    /// Opaque key identifying the statement file (pass to the download
21    /// endpoint)
22    pub file_key: String,
23}
24
25/// Response for get statement data download url request
26#[derive(Debug, Clone, Default, Serialize, Deserialize)]
27pub struct GetStatementResponse {
28    /// Temporary download URL for the statement file
29    pub url: String,
30}
31
32/// Implements `Serialize` (as the integer code) and a lenient `Deserialize`
33/// (a JSON integer or an integer string; anything else, including an
34/// undocumented code, becomes `Unknown`) for an integer-coded account enum.
35macro_rules! impl_account_code_enum {
36    ($($ty:ty),* $(,)?) => {
37        $(
38            impl Serialize for $ty {
39                fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
40                    let value: i32 = (*self).into();
41                    value.serialize(serializer)
42                }
43            }
44
45            impl<'de> Deserialize<'de> for $ty {
46                fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
47                    let value = serde_json::Value::deserialize(deserializer)?;
48                    Ok(serde_utils::account_int_opt(&value)
49                        .and_then(|v| i32::try_from(v).ok())
50                        .map(<$ty>::from)
51                        .unwrap_or_default())
52                }
53            }
54        )*
55    };
56}
57
58/// Verification status of a bank card
59#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
60#[repr(i32)]
61pub enum BankCardStatus {
62    /// Unknown (an undocumented code)
63    #[default]
64    Unknown = -1,
65    /// Not verified
66    Unverified = 0,
67    /// Under review
68    UnderReview = 1,
69    /// Verified
70    Verified = 2,
71}
72
73/// Witness (in-person / video verification) state of a bank card
74#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
75#[repr(i32)]
76pub enum BankCardWitnessState {
77    /// Unknown (an undocumented code)
78    #[default]
79    Unknown = -1,
80    /// Witnessing not required
81    NotRequired = 1,
82    /// Witnessing pending
83    Pending = 2,
84    /// Witnessed
85    Witnessed = 3,
86}
87
88/// Binding state of a bank card
89#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
90#[repr(i32)]
91pub enum BankCardBindState {
92    /// Unknown (an undocumented code)
93    #[default]
94    Unknown = -1,
95    /// Binding in progress
96    Binding = 0,
97    /// Bound
98    Bound = 1,
99    /// Binding failed
100    Failed = 2,
101}
102
103/// Status of a bank-card authorization (eDDA, bank securities account, FPS)
104/// or of an eDDA application
105#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
106#[repr(i32)]
107pub enum AuthorizationStatus {
108    /// Unknown (an undocumented code)
109    #[default]
110    Unknown = -1,
111    /// Not authorized
112    Unauthorized = 0,
113    /// Authorized
114    Authorized = 1,
115    /// Authorization in progress
116    Authorizing = 2,
117    /// Authorization failed (see the `message` field for the reason)
118    Failed = 3,
119}
120
121/// State of a stock transfer-in application (another broker → this account)
122#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
123#[repr(i32)]
124pub enum StockTransferInState {
125    /// Unknown (an undocumented code)
126    #[default]
127    Unknown = -1,
128    /// Submitted
129    Submitted = 0,
130    /// Cancelled
131    Cancelled = 1,
132    /// Completed
133    Completed = 3,
134    /// Processing
135    Processing = 5,
136    /// Partially completed
137    PartiallyCompleted = 7,
138    /// Failed
139    Failed = 8,
140}
141
142/// State of a stock transfer-out application (this account → another
143/// broker)
144#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
145#[repr(i32)]
146pub enum StockTransferOutState {
147    /// Unknown (an undocumented code)
148    #[default]
149    Unknown = -1,
150    /// Submitted (the only state in which the application can still be
151    /// cancelled)
152    Submitted = 0,
153    /// Processing
154    Processing = 1,
155    /// Executing
156    Executing = 2,
157    /// Completed
158    Completed = 3,
159    /// Cancelled
160    Cancelled = 4,
161    /// Partially completed
162    PartiallyCompleted = 5,
163    /// Failed
164    Failed = 6,
165    /// Rejected
166    Rejected = 7,
167}
168
169/// State of one stock inside a stock transfer application
170#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
171#[repr(i32)]
172pub enum TransferStockState {
173    /// Unknown (an undocumented code)
174    #[default]
175    Unknown = -1,
176    /// Processing
177    Processing = 0,
178    /// Succeeded
179    Succeeded = 1,
180    /// Failed
181    Failed = 2,
182}
183
184/// Type of a reward record
185#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
186#[repr(i32)]
187pub enum RewardType {
188    /// Unknown (an undocumented code)
189    #[default]
190    Unknown = -1,
191    /// Cash reward
192    Cash = 0,
193    /// Gift (prize)
194    Gift = 1,
195    /// Coupon
196    Coupon = 2,
197    /// Task reward
198    Task = 3,
199}
200
201/// Which upstream detail object a reward record came from
202#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, Serialize, Deserialize)]
203#[serde(rename_all = "snake_case")]
204pub enum RewardDetailKind {
205    /// No known detail object (e.g. a task reward); only the reward type is
206    /// set
207    #[default]
208    None,
209    /// The `cash` object
210    Cash,
211    /// The `card` (coupon) object
212    Card,
213    /// The `prize` (gift) object
214    Prize,
215}
216
217/// Status of a reward record
218#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
219#[repr(i32)]
220pub enum RewardStatus {
221    /// Unknown (an undocumented code)
222    #[default]
223    Unknown = -1,
224    /// Upcoming
225    Upcoming = 0,
226    /// Cancelled
227    Cancelled = 1,
228    /// The user exited the activity
229    ExitedActivity = 2,
230    /// Not claimed yet
231    Unclaimed = 8,
232    /// Being issued
233    Issuing = 10,
234    /// Issued
235    Issued = 12,
236    /// Issuing failed
237    Failed = 13,
238    /// Exchanged
239    Exchanged = 16,
240    /// Expired
241    Expired = 17,
242    /// Refunded
243    Refunded = 18,
244}
245
246/// Delivery status of an issued prize (only meaningful when the reward
247/// status is [`RewardStatus::Issued`] and the reward is a gift)
248#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
249#[repr(i32)]
250pub enum RewardDeliverStatus {
251    /// Unknown (an undocumented code, or no delivery status)
252    #[default]
253    Unknown = -1,
254    /// Not activated
255    NotActivated = 0,
256    /// Activated, or shipping
257    ActivatedOrShipping = 1,
258    /// Consumed
259    Consumed = 2,
260    /// E-voucher activating
261    EVoucherActivating = 5,
262    /// E-voucher expired before activation
263    EVoucherExpired = 6,
264    /// E-voucher invalid
265    EVoucherInvalid = 7,
266    /// Shipping address missing
267    AddressMissing = 8,
268    /// Shipping address filled (the server uses both 9 and 11)
269    #[num_enum(alternatives = [11])]
270    AddressFilled = 9,
271    /// Shipping
272    Shipping = 10,
273}
274
275/// Status of a coupon
276#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
277#[repr(i32)]
278pub enum CouponStatus {
279    /// Unknown (an undocumented code)
280    #[default]
281    Unknown = -1,
282    /// Unused
283    Unused = 0,
284    /// Used
285    Used = 1,
286    /// Expired
287    Expired = 2,
288    /// Being redeemed
289    Redeeming = 3,
290    /// In use
291    InUse = 4,
292    /// Processing
293    Processing = 5,
294}
295
296/// State of a deposit record
297#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
298#[repr(i32)]
299pub enum DepositState {
300    /// Unknown (an undocumented code)
301    #[default]
302    Unknown = -1,
303    /// Processing
304    Processing = 0,
305    /// Credited to the account
306    Credited = 1,
307    /// Failed
308    Failed = 2,
309    /// Cancelled
310    Cancelled = 3,
311    /// Invalidated
312    Invalidated = 4,
313    /// Rejected
314    Rejected = 5,
315}
316
317/// State of a withdrawal record
318#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
319#[repr(i32)]
320pub enum WithdrawalState {
321    /// Unknown (an undocumented code)
322    #[default]
323    Unknown = -1,
324    /// Submitted
325    Submitted = 0,
326    /// Processing
327    Processing = 1,
328    /// Rejected
329    Rejected = 2,
330    /// Cancelled
331    Cancelled = 3,
332    /// Remitted
333    Remitted = 4,
334    /// Failed
335    Failed = 5,
336    /// Refunded
337    Refunded = 6,
338    /// Approved, awaiting payout
339    ApprovedAwaitingPayout = 7,
340    /// Large-amount review
341    LargeAmountReview = 8,
342    /// Change pending approval
343    ChangePendingApproval = 9,
344    /// Deletion pending approval
345    DeletionPendingApproval = 10,
346    /// Deleted
347    Deleted = 11,
348    /// Rejection pending approval
349    RejectionPendingApproval = 12,
350    /// Awaiting confirmation
351    AwaitingConfirmation = 15,
352}
353
354impl_account_code_enum!(
355    BankCardStatus,
356    BankCardWitnessState,
357    BankCardBindState,
358    AuthorizationStatus,
359    StockTransferInState,
360    StockTransferOutState,
361    TransferStockState,
362    RewardType,
363    RewardStatus,
364    RewardDeliverStatus,
365    CouponStatus,
366    DepositState,
367    WithdrawalState,
368);
369
370/// An authorization attached to a bank card (eDDA, bank securities account,
371/// FPS, …)
372#[derive(Debug, Clone, Default, Serialize, Deserialize)]
373#[serde(default, remote = "Self")]
374pub struct BankCardAuthorization {
375    /// Authorization flow: `hk_edda` / `hk_sdda` (eDDA), `hk_bank_sec`,
376    /// `hk_fps`, …
377    #[serde(deserialize_with = "serde_utils::string_lenient")]
378    pub flow_id: String,
379    /// Display name of the authorization
380    #[serde(deserialize_with = "serde_utils::string_lenient")]
381    pub name: String,
382    /// Authorized currency
383    #[serde(deserialize_with = "serde_utils::string_lenient")]
384    pub currency: String,
385    /// Authorization status
386    pub status: AuthorizationStatus,
387    /// The server's numeric code of `status`, also when it is a code this SDK
388    /// does not know (`status` is then `Unknown`); `None` when the value is
389    /// missing or is not a code
390    pub status_raw: Option<i32>,
391    /// Failure reason (empty unless the authorization failed)
392    #[serde(deserialize_with = "serde_utils::string_lenient")]
393    pub message: String,
394    /// Whether this authorization is supported for the card
395    #[serde(deserialize_with = "serde_utils::bool_lenient")]
396    pub is_support: bool,
397    /// Maximum amount per debit (`None` when not set)
398    #[serde(with = "serde_utils::decimal_opt_lenient_0_is_none")]
399    pub max_amount: Option<Decimal>,
400    /// Whether the per-debit amount is unlimited
401    #[serde(deserialize_with = "serde_utils::bool_lenient")]
402    pub max_amount_unlimited: bool,
403    /// Maximum number of debits per day (`None` when not set)
404    #[serde(with = "serde_utils::int64_opt_lenient_0_is_none")]
405    pub daily_max_count: Option<i64>,
406    /// Whether the daily debit count is unlimited
407    #[serde(deserialize_with = "serde_utils::bool_lenient")]
408    pub daily_max_count_unlimited: bool,
409    /// Expiry date of the authorization (`None` when not set, and for a
410    /// long-term authorization: the server's 9999-12-31 "never expires"
411    /// sentinel, like any date in or after 2100, is `None`; check
412    /// [`Self::long_term_valid`])
413    #[serde(with = "serde_utils::account_time_opt")]
414    pub expiry_date: Option<OffsetDateTime>,
415    /// Whether the authorization never expires
416    #[serde(deserialize_with = "serde_utils::bool_lenient")]
417    pub long_term_valid: bool,
418    /// Whether submitted documents are under review
419    #[serde(deserialize_with = "serde_utils::bool_lenient")]
420    pub doc_reviewing: bool,
421    /// Whether the "no prior deposit" check is under review
422    #[serde(deserialize_with = "serde_utils::bool_lenient")]
423    pub no_prior_deposit_reviewing: bool,
424}
425
426/// A linked bank card
427///
428/// The server also returns the card holder's name and postal address and the
429/// storage keys of uploaded ID documents; those are intentionally not
430/// modelled.
431#[derive(Debug, Clone, Default, Serialize, Deserialize)]
432#[serde(default, remote = "Self")]
433pub struct BankCard {
434    /// Bank card ID (pass to [`crate::AssetContext::edda_applications`])
435    #[serde(deserialize_with = "serde_utils::string_lenient")]
436    pub id: String,
437    /// Bank ID
438    #[serde(deserialize_with = "serde_utils::string_lenient")]
439    pub bank_id: String,
440    /// Bank name
441    #[serde(deserialize_with = "serde_utils::string_lenient")]
442    pub bank: String,
443    /// Bank name in English
444    #[serde(deserialize_with = "serde_utils::string_lenient")]
445    pub bank_en: String,
446    /// Bank code
447    #[serde(deserialize_with = "serde_utils::string_lenient")]
448    pub bank_code: String,
449    /// Bank account number, as returned by the server (not masked)
450    #[serde(deserialize_with = "serde_utils::string_lenient")]
451    pub account: String,
452    /// Account type
453    #[serde(deserialize_with = "serde_utils::string_lenient")]
454    pub account_type: String,
455    /// Country or region of the bank (e.g. `Hong Kong`; not a currency)
456    #[serde(deserialize_with = "serde_utils::string_lenient")]
457    pub country: String,
458    /// Country or region as displayed in the app, as returned by the server
459    #[serde(deserialize_with = "serde_utils::string_lenient")]
460    pub country_display: String,
461    /// Region code
462    #[serde(deserialize_with = "serde_utils::string_lenient")]
463    pub region: String,
464    /// Region name
465    #[serde(deserialize_with = "serde_utils::string_lenient")]
466    pub region_name: String,
467    /// SWIFT code
468    #[serde(deserialize_with = "serde_utils::string_lenient")]
469    pub swift_code: String,
470    /// Remark
471    #[serde(deserialize_with = "serde_utils::string_lenient")]
472    pub remark: String,
473    /// Verification status
474    pub status: BankCardStatus,
475    /// The server's numeric code of `status`, also when it is a code this SDK
476    /// does not know (`status` is then `Unknown`); `None` when the value is
477    /// missing or is not a code
478    pub status_raw: Option<i32>,
479    /// Witness state
480    pub witness_state: BankCardWitnessState,
481    /// The server's numeric code of `witness_state`, also when it is a code
482    /// this SDK does not know (`witness_state` is then `Unknown`); `None` when
483    /// the value is missing or is not a code
484    pub witness_state_raw: Option<i32>,
485    /// Whether the card supports witnessing
486    #[serde(deserialize_with = "serde_utils::bool_lenient")]
487    pub support_witness: bool,
488    /// Binding state
489    pub bind_state: BankCardBindState,
490    /// The server's numeric code of `bind_state`, also when it is a code this
491    /// SDK does not know (`bind_state` is then `Unknown`); `None` when the
492    /// value is missing or is not a code
493    pub bind_state_raw: Option<i32>,
494    /// Binding hint text
495    #[serde(deserialize_with = "serde_utils::string_lenient")]
496    pub bind_tip: String,
497    /// Withdrawal fee text, as returned by the server
498    #[serde(deserialize_with = "serde_utils::string_lenient")]
499    pub withdraw_fee: String,
500    /// Time the card was added
501    #[serde(with = "serde_utils::account_time_opt")]
502    pub created_at: Option<OffsetDateTime>,
503    /// Authorizations attached to the card
504    #[serde(deserialize_with = "serde_utils::null_as_default")]
505    pub auth_list: Vec<BankCardAuthorization>,
506}
507
508#[derive(Debug, Default, Deserialize)]
509pub(crate) struct BankCardsResponse {
510    #[serde(default, deserialize_with = "serde_utils::null_as_default")]
511    pub(crate) list: Vec<BankCard>,
512}
513
514/// An eDDA authorization application of a bank card
515#[derive(Debug, Clone, Default, Serialize, Deserialize)]
516#[serde(default, remote = "Self")]
517pub struct EddaApplication {
518    /// Application ID
519    #[serde(deserialize_with = "serde_utils::string_lenient")]
520    pub id: String,
521    /// Authorization flow: `hk_edda` (authorized at the bank) or `hk_sdda`
522    /// (authorized in the app)
523    #[serde(deserialize_with = "serde_utils::string_lenient")]
524    pub flow_id: String,
525    /// Display name of the authorization
526    #[serde(deserialize_with = "serde_utils::string_lenient")]
527    pub name: String,
528    /// Authorized currency
529    #[serde(deserialize_with = "serde_utils::string_lenient")]
530    pub currency: String,
531    /// Application status
532    pub status: AuthorizationStatus,
533    /// The server's numeric code of `status`, also when it is a code this SDK
534    /// does not know (`status` is then `Unknown`); `None` when the value is
535    /// missing or is not a code
536    pub status_raw: Option<i32>,
537    /// Failure reason (empty unless the application failed)
538    #[serde(deserialize_with = "serde_utils::string_lenient")]
539    pub message: String,
540    /// Time the application was filed (`None` when not set)
541    #[serde(with = "serde_utils::account_time_opt")]
542    pub created_at: Option<OffsetDateTime>,
543    /// Time the application was last updated (`None` when not set)
544    #[serde(with = "serde_utils::account_time_opt")]
545    pub updated_at: Option<OffsetDateTime>,
546}
547
548/// The eDDA status reply: `{list: [...]}`, or a single `{id, status,
549/// message}` object from older server builds.
550#[derive(Debug, Default)]
551pub(crate) struct EddaApplicationsResponse(pub(crate) Vec<EddaApplication>);
552
553impl<'de> Deserialize<'de> for EddaApplicationsResponse {
554    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
555        let value = serde_json::Value::deserialize(deserializer)?;
556        let items = match value {
557            serde_json::Value::Object(mut obj) => match obj.remove("list") {
558                Some(serde_json::Value::Array(list)) => list,
559                Some(_) => Vec::new(),
560                None if obj.contains_key("status") => vec![serde_json::Value::Object(obj)],
561                None => Vec::new(),
562            },
563            _ => Vec::new(),
564        };
565        items
566            .into_iter()
567            .map(serde_json::from_value)
568            .collect::<Result<Vec<_>, _>>()
569            .map(Self)
570            .map_err(D::Error::custom)
571    }
572}
573
574/// One stock in a stock transfer application
575///
576/// Storage keys of uploaded proof documents are intentionally not modelled.
577#[derive(Debug, Clone, Default, Serialize, Deserialize)]
578#[serde(default, remote = "Self")]
579pub struct TransferStock {
580    /// Stock code
581    #[serde(deserialize_with = "serde_utils::string_lenient")]
582    pub code: String,
583    /// Stock name
584    #[serde(deserialize_with = "serde_utils::string_lenient")]
585    pub name: String,
586    /// Stock name in English
587    #[serde(deserialize_with = "serde_utils::string_lenient")]
588    pub name_en: String,
589    /// Market
590    #[serde(deserialize_with = "serde_utils::string_lenient")]
591    pub market: String,
592    /// Counter ID
593    #[serde(deserialize_with = "serde_utils::string_lenient")]
594    pub counter_id: String,
595    /// Quantity
596    #[serde(with = "serde_utils::decimal_opt_lenient")]
597    pub amount: Option<Decimal>,
598    /// Currency
599    #[serde(deserialize_with = "serde_utils::string_lenient")]
600    pub currency: String,
601    /// Cost price
602    #[serde(with = "serde_utils::decimal_opt_lenient")]
603    pub cost: Option<Decimal>,
604    /// State code of this stock in the transfer (the server's `state`)
605    #[serde(rename(deserialize = "state"), alias = "state_code")]
606    pub state_code: TransferStockState,
607    /// The server's numeric code of `state_code`, also when it is a code this
608    /// SDK does not know (`state_code` is then `Unknown`); `None` when the
609    /// value is missing or is not a code
610    pub state_code_raw: Option<i32>,
611    /// Quantity held in street name, as returned by the server
612    #[serde(with = "serde_utils::decimal_opt_lenient")]
613    pub street_amount: Option<Decimal>,
614    /// Quantity held by a nominee, as returned by the server
615    #[serde(with = "serde_utils::decimal_opt_lenient")]
616    pub nominee_amount: Option<Decimal>,
617    /// Quantity held in the holder's own name, as returned by the server
618    #[serde(with = "serde_utils::decimal_opt_lenient")]
619    pub own_amount: Option<Decimal>,
620    /// Number of share certificates, as returned by the server
621    #[serde(deserialize_with = "serde_utils::account_int64")]
622    pub certificate_count: i64,
623    /// Position side
624    #[serde(deserialize_with = "serde_utils::string_lenient")]
625    pub position_side: String,
626}
627
628/// The `app_state` of a stock transfer application when the user tapped "I
629/// have notified the broker" in the app (the user's own confirmation, not a
630/// Longbridge action)
631pub const APP_STATE_NOTICED: &str = "noticed";
632
633/// A stock transfer-in application (another broker → this account)
634///
635/// The account holder's name and contact details at the other broker and the
636/// storage keys of uploaded proof documents are intentionally not modelled.
637#[derive(Debug, Clone, Default, Serialize, Deserialize)]
638#[serde(default, remote = "Self")]
639pub struct StockTransferIn {
640    /// Record ID
641    #[serde(deserialize_with = "serde_utils::string_lenient")]
642    pub id: String,
643    /// Order ID
644    #[serde(deserialize_with = "serde_utils::string_lenient")]
645    pub order_id: String,
646    /// Market
647    #[serde(deserialize_with = "serde_utils::string_lenient")]
648    pub market: String,
649    /// Name of the other broker
650    #[serde(deserialize_with = "serde_utils::string_lenient")]
651    pub broker: String,
652    /// ID of the other broker
653    #[serde(deserialize_with = "serde_utils::string_lenient")]
654    pub broker_id: String,
655    /// English name of the other broker
656    #[serde(deserialize_with = "serde_utils::string_lenient")]
657    pub broker_en: String,
658    /// Broker code of the other broker
659    #[serde(rename = "code", deserialize_with = "serde_utils::string_lenient")]
660    pub broker_code: String,
661    /// Account number at the other broker, as returned by the server (not
662    /// masked)
663    #[serde(deserialize_with = "serde_utils::string_lenient")]
664    pub account: String,
665    /// State text, as returned by the server
666    #[serde(deserialize_with = "serde_utils::string_lenient")]
667    pub state: String,
668    /// State code
669    pub state_code: StockTransferInState,
670    /// The server's numeric code of `state_code`, also when it is a code this
671    /// SDK does not know (`state_code` is then `Unknown`); `None` when the
672    /// value is missing or is not a code
673    pub state_code_raw: Option<i32>,
674    /// App-side state: [`APP_STATE_NOTICED`] (`noticed`) means the user
675    /// tapped "I have notified the broker" in the app (the user's own
676    /// confirmation, not a Longbridge action); `default` otherwise. See
677    /// [`Self::user_notified_broker`].
678    #[serde(deserialize_with = "serde_utils::string_lenient")]
679    pub app_state: String,
680    /// Whether the application can still be cancelled or changed
681    #[serde(deserialize_with = "serde_utils::bool_lenient")]
682    pub can_modify: bool,
683    /// Created time
684    #[serde(with = "serde_utils::account_time_opt")]
685    pub created_at: Option<OffsetDateTime>,
686    /// Updated time
687    #[serde(with = "serde_utils::account_time_opt")]
688    pub updated_at: Option<OffsetDateTime>,
689    /// Processing start time (`None` when not set)
690    #[serde(with = "serde_utils::account_time_opt")]
691    pub process_at: Option<OffsetDateTime>,
692    /// Execution time (`None` when not executed)
693    #[serde(with = "serde_utils::account_time_opt")]
694    pub exec_at: Option<OffsetDateTime>,
695    /// Remark
696    #[serde(deserialize_with = "serde_utils::string_lenient")]
697    pub remark: String,
698    /// Reason (e.g. for a failure)
699    #[serde(deserialize_with = "serde_utils::string_lenient")]
700    pub reason: String,
701    /// Stocks in the application
702    #[serde(deserialize_with = "serde_utils::null_as_default")]
703    pub stocks: Vec<TransferStock>,
704}
705
706/// Response for the stock transfer-in list
707#[derive(Debug, Clone, Default, Serialize, Deserialize)]
708#[serde(default)]
709pub struct StockTransferInResponse {
710    /// Records
711    #[serde(deserialize_with = "serde_utils::null_as_default")]
712    pub records: Vec<StockTransferIn>,
713    /// Total number of records
714    #[serde(deserialize_with = "serde_utils::account_int64")]
715    pub total: i64,
716}
717
718/// A stock transfer-out application (this account → another broker)
719///
720/// The account holder's name and contact details at the other broker and the
721/// storage keys of uploaded proof documents are intentionally not modelled.
722#[derive(Debug, Clone, Default, Serialize, Deserialize)]
723#[serde(default, remote = "Self")]
724pub struct StockTransferOut {
725    /// Record ID
726    #[serde(deserialize_with = "serde_utils::string_lenient")]
727    pub id: String,
728    /// Order ID
729    #[serde(deserialize_with = "serde_utils::string_lenient")]
730    pub order_id: String,
731    /// Market
732    #[serde(deserialize_with = "serde_utils::string_lenient")]
733    pub market: String,
734    /// Name of the other broker
735    #[serde(deserialize_with = "serde_utils::string_lenient")]
736    pub broker: String,
737    /// ID of the other broker
738    #[serde(deserialize_with = "serde_utils::string_lenient")]
739    pub broker_id: String,
740    /// English name of the other broker (the server's `name_en`)
741    #[serde(rename = "name_en", deserialize_with = "serde_utils::string_lenient")]
742    pub broker_en: String,
743    /// Broker code of the other broker
744    #[serde(rename = "code", deserialize_with = "serde_utils::string_lenient")]
745    pub broker_code: String,
746    /// Account number at the other broker, as returned by the server (not
747    /// masked)
748    #[serde(deserialize_with = "serde_utils::string_lenient")]
749    pub account: String,
750    /// State text, as returned by the server
751    #[serde(deserialize_with = "serde_utils::string_lenient")]
752    pub state: String,
753    /// State code. Only [`StockTransferOutState::Submitted`] applications can
754    /// be cancelled (the server's `can_modify` is not reliable here, so it is
755    /// not modelled).
756    pub state_code: StockTransferOutState,
757    /// The server's numeric code of `state_code`, also when it is a code this
758    /// SDK does not know (`state_code` is then `Unknown`); `None` when the
759    /// value is missing or is not a code
760    pub state_code_raw: Option<i32>,
761    /// App-side state: [`APP_STATE_NOTICED`] (`noticed`) means the user
762    /// tapped "I have notified the broker" in the app (the user's own
763    /// confirmation, not a Longbridge action); `default` otherwise. See
764    /// [`Self::user_notified_broker`].
765    #[serde(deserialize_with = "serde_utils::string_lenient")]
766    pub app_state: String,
767    /// Created time
768    #[serde(with = "serde_utils::account_time_opt")]
769    pub created_at: Option<OffsetDateTime>,
770    /// Updated time
771    #[serde(with = "serde_utils::account_time_opt")]
772    pub updated_at: Option<OffsetDateTime>,
773    /// Processing start time (`None` when not set)
774    #[serde(with = "serde_utils::account_time_opt")]
775    pub process_at: Option<OffsetDateTime>,
776    /// Execution time (`None` when not executed)
777    #[serde(with = "serde_utils::account_time_opt")]
778    pub exec_at: Option<OffsetDateTime>,
779    /// Time the other broker agreed (`None` when not set)
780    #[serde(with = "serde_utils::account_time_opt")]
781    pub agree_at: Option<OffsetDateTime>,
782    /// Time the application was refused (`None` when not set)
783    #[serde(with = "serde_utils::account_time_opt")]
784    pub refuse_at: Option<OffsetDateTime>,
785    /// Time the application was cancelled (`None` when not set)
786    #[serde(with = "serde_utils::account_time_opt")]
787    pub cancel_at: Option<OffsetDateTime>,
788    /// Remark
789    #[serde(deserialize_with = "serde_utils::string_lenient")]
790    pub remark: String,
791    /// Reason (e.g. for a rejection)
792    #[serde(deserialize_with = "serde_utils::string_lenient")]
793    pub reason: String,
794    /// Stocks in the application
795    #[serde(deserialize_with = "serde_utils::null_as_default")]
796    pub stocks: Vec<TransferStock>,
797}
798
799impl StockTransferIn {
800    /// Whether the user confirmed in the app that the other broker was
801    /// notified (`app_state` is [`APP_STATE_NOTICED`])
802    #[inline]
803    pub fn user_notified_broker(&self) -> bool {
804        self.app_state == APP_STATE_NOTICED
805    }
806}
807
808impl StockTransferOut {
809    /// Whether the user confirmed in the app that the other broker was
810    /// notified (`app_state` is [`APP_STATE_NOTICED`])
811    #[inline]
812    pub fn user_notified_broker(&self) -> bool {
813        self.app_state == APP_STATE_NOTICED
814    }
815
816    /// Whether the application can still be cancelled (only
817    /// [`StockTransferOutState::Submitted`] applications can)
818    #[inline]
819    pub fn cancellable(&self) -> bool {
820        self.state_code == StockTransferOutState::Submitted
821    }
822}
823
824#[derive(Debug, Default, Deserialize)]
825pub(crate) struct StockTransferOutResponse {
826    #[serde(default, deserialize_with = "serde_utils::null_as_default")]
827    pub(crate) records: Vec<StockTransferOut>,
828}
829
830/// A reward record from the reward center
831///
832/// The server nests the details in one of `cash` / `card` / `prize`; this
833/// type flattens them. Prize redemption secrets (`coupon_secret`), cash card
834/// codes (`cash_card_code`) and shipping contact details of prizes are
835/// intentionally not modelled.
836#[derive(Debug, Clone, Default, Serialize, Deserialize)]
837#[serde(from = "RawRewardRecord")]
838pub struct RewardRecord {
839    /// Reward type: named after the detail object the server sent (`cash`,
840    /// `card` or `prize`, checked in that order), or the server's
841    /// `reward_type` code when it sent no detail object
842    pub reward_type: RewardType,
843    /// The server's numeric code of `reward_type`, also when it is a code this
844    /// SDK does not know (`reward_type` is then `Unknown`); `None` when the
845    /// value is missing or is not a code
846    pub reward_type_raw: Option<i32>,
847    /// The detail object the fields below came from
848    pub detail_kind: RewardDetailKind,
849    /// Record ID
850    pub record_id: String,
851    /// Title of the activity that granted the reward
852    pub activity_title: String,
853    /// Reward title
854    pub title: String,
855    /// Reward description
856    pub description: String,
857    /// Coupon type (coupon rewards), e.g. `commission`
858    pub card_type: String,
859    /// Coupon status (coupon rewards; [`CouponStatus::Unknown`] otherwise)
860    pub card_status: CouponStatus,
861    /// The server's numeric code of `card_status`, also when it is a code this
862    /// SDK does not know (`card_status` is then `Unknown`); `None` when the
863    /// value is missing or is not a code
864    pub card_status_raw: Option<i32>,
865    /// Prize type code (gift rewards; `0` = physical goods), `None` when not
866    /// set
867    pub prize_type: Option<i32>,
868    /// Amount
869    pub amount: Option<Decimal>,
870    /// Currency
871    pub currency: String,
872    /// Reward status
873    pub status: RewardStatus,
874    /// The server's numeric code of `status`, also when it is a code this SDK
875    /// does not know (`status` is then `Unknown`); `None` when the value is
876    /// missing or is not a code
877    pub status_raw: Option<i32>,
878    /// Delivery status (issued gift rewards only). The server uses both 9
879    /// and 11 for [`RewardDeliverStatus::AddressFilled`];
880    /// [`Self::deliver_status_raw`] tells them apart.
881    pub deliver_status: RewardDeliverStatus,
882    /// The server's numeric code of `deliver_status` (e.g. 11, which
883    /// `deliver_status` reads as `AddressFilled`, like 9), also when it is a
884    /// code this SDK does not know (`deliver_status` is then `Unknown`); `None`
885    /// when the value is missing or is not a code
886    pub deliver_status_raw: Option<i32>,
887    /// Exit status code, as returned by the server
888    pub exit_status: i32,
889    /// Time the reward was sent
890    #[serde(with = "serde_utils::account_time_opt")]
891    pub send_time: Option<OffsetDateTime>,
892    /// Start time
893    #[serde(with = "serde_utils::account_time_opt")]
894    pub start_time: Option<OffsetDateTime>,
895    /// End time
896    #[serde(with = "serde_utils::account_time_opt")]
897    pub end_time: Option<OffsetDateTime>,
898    /// Effective time
899    #[serde(with = "serde_utils::account_time_opt")]
900    pub effective_time: Option<OffsetDateTime>,
901    /// Deadline to claim the reward
902    #[serde(with = "serde_utils::account_time_opt")]
903    pub receive_deadline: Option<OffsetDateTime>,
904}
905
906#[derive(Debug, Default, Deserialize)]
907#[serde(default)]
908struct RawRewardDetail {
909    #[serde(deserialize_with = "serde_utils::string_lenient")]
910    record_id: String,
911    #[serde(deserialize_with = "serde_utils::string_lenient")]
912    activity_title: String,
913    #[serde(deserialize_with = "serde_utils::string_lenient")]
914    title: String,
915    #[serde(deserialize_with = "serde_utils::string_lenient")]
916    description: String,
917    #[serde(deserialize_with = "serde_utils::string_lenient")]
918    card_type: String,
919    card_status: serde_json::Value,
920    prize_type: serde_json::Value,
921    #[serde(with = "serde_utils::decimal_opt_lenient")]
922    amount: Option<Decimal>,
923    #[serde(deserialize_with = "serde_utils::string_lenient")]
924    currency: String,
925    status: serde_json::Value,
926    deliver_status: serde_json::Value,
927    #[serde(deserialize_with = "serde_utils::account_int32")]
928    exit_status: i32,
929    #[serde(with = "serde_utils::account_time_opt")]
930    send_time: Option<OffsetDateTime>,
931    #[serde(with = "serde_utils::account_time_opt")]
932    start_time: Option<OffsetDateTime>,
933    #[serde(with = "serde_utils::account_time_opt")]
934    end_time: Option<OffsetDateTime>,
935    #[serde(with = "serde_utils::account_time_opt")]
936    effective_time: Option<OffsetDateTime>,
937    #[serde(with = "serde_utils::account_time_opt")]
938    receive_deadline: Option<OffsetDateTime>,
939}
940
941#[derive(Debug, Default, Deserialize)]
942#[serde(default)]
943struct RawRewardRecord {
944    reward_type: serde_json::Value,
945    #[serde(deserialize_with = "object_opt")]
946    cash: Option<RawRewardDetail>,
947    #[serde(deserialize_with = "object_opt")]
948    card: Option<RawRewardDetail>,
949    #[serde(deserialize_with = "object_opt")]
950    prize: Option<RawRewardDetail>,
951}
952
953/// A typed code and the server's numeric code, decoded from a wire value.
954fn typed_and_raw<T>(wire: &serde_json::Value) -> (T, Option<i32>)
955where
956    T: serde::de::DeserializeOwned + Into<i32> + Copy + Default + PartialEq,
957{
958    let typed: T = serde_json::from_value(wire.clone()).unwrap_or_default();
959    let present = !wire.is_null();
960    (
961        typed,
962        present.then(|| raw_code(typed, Some(wire))).flatten(),
963    )
964}
965
966impl From<RawRewardRecord> for RewardRecord {
967    fn from(raw: RawRewardRecord) -> Self {
968        let (code, reward_type_raw) = typed_and_raw::<RewardType>(&raw.reward_type);
969        // Like the app, read the first detail object present and name the
970        // type after it; without one, fall back to the server's code.
971        let (reward_type, detail_kind, detail) = match (raw.cash, raw.card, raw.prize) {
972            (Some(d), _, _) => (RewardType::Cash, RewardDetailKind::Cash, d),
973            (None, Some(d), _) => (RewardType::Coupon, RewardDetailKind::Card, d),
974            (None, None, Some(d)) => (RewardType::Gift, RewardDetailKind::Prize, d),
975            (None, None, None) => (code, RewardDetailKind::None, RawRewardDetail::default()),
976        };
977        let prize_type =
978            serde_utils::account_int_opt(&detail.prize_type).and_then(|v| i32::try_from(v).ok());
979        let (card_status, card_status_raw) = typed_and_raw(&detail.card_status);
980        let (status, status_raw) = typed_and_raw(&detail.status);
981        let (deliver_status, deliver_status_raw) = typed_and_raw(&detail.deliver_status);
982        Self {
983            reward_type,
984            reward_type_raw,
985            detail_kind,
986            record_id: detail.record_id,
987            activity_title: detail.activity_title,
988            title: detail.title,
989            description: detail.description,
990            card_type: detail.card_type,
991            card_status,
992            card_status_raw,
993            prize_type,
994            amount: detail.amount,
995            currency: detail.currency,
996            status,
997            status_raw,
998            deliver_status,
999            deliver_status_raw,
1000            exit_status: detail.exit_status,
1001            send_time: detail.send_time,
1002            start_time: detail.start_time,
1003            end_time: detail.end_time,
1004            effective_time: detail.effective_time,
1005            receive_deadline: detail.receive_deadline,
1006        }
1007    }
1008}
1009
1010/// Response for the reward record list
1011#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1012#[serde(default)]
1013pub struct RewardRecordsResponse {
1014    /// Reward records
1015    #[serde(deserialize_with = "serde_utils::null_as_default")]
1016    pub list: Vec<RewardRecord>,
1017    /// Total number of records
1018    #[serde(deserialize_with = "serde_utils::account_int64")]
1019    pub total: i64,
1020}
1021
1022/// Implements `Serialize` (as the integer code) and a lenient `Deserialize`
1023/// for a proto enum that the server sends either as its name or as its number
1024/// (a JSON integer or an integer string). Anything else, including an
1025/// undocumented name or code, becomes `Unknown`.
1026macro_rules! impl_named_code_enum {
1027    ($($ty:ty { $($name:literal => $variant:ident),* $(,)? })*) => {
1028        $(
1029            impl Serialize for $ty {
1030                fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1031                    let value: i32 = (*self).into();
1032                    value.serialize(serializer)
1033                }
1034            }
1035
1036            impl<'de> Deserialize<'de> for $ty {
1037                fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1038                    let value = serde_json::Value::deserialize(deserializer)?;
1039                    if let serde_json::Value::String(name) = &value {
1040                        match name.trim() {
1041                            $($name => return Ok(<$ty>::$variant),)*
1042                            _ => {}
1043                        }
1044                    }
1045                    Ok(serde_utils::account_int_opt(&value)
1046                        .and_then(|v| i32::try_from(v).ok())
1047                        .map(<$ty>::from)
1048                        .unwrap_or_default())
1049                }
1050            }
1051        )*
1052    };
1053}
1054
1055/// Instrument type a coupon applies to (the server's `bz_types` /
1056/// `underlying_type`)
1057#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
1058#[repr(i32)]
1059pub enum CouponTargetType {
1060    /// Unknown (an undocumented code)
1061    #[default]
1062    Unknown = -1,
1063    /// Stocks (`StockTrade`)
1064    Stock = 0,
1065    /// US stock options (`UsStockOptions`)
1066    UsOption = 1,
1067    /// HK warrants (`HkStockWarrant`)
1068    HkWarrant = 2,
1069    /// ETF
1070    Etf = 3,
1071    /// LOF
1072    Lof = 4,
1073}
1074
1075/// IPO subscription type an IPO commission coupon applies to
1076#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
1077#[repr(i32)]
1078pub enum IpoCouponTargetType {
1079    /// Unknown (unset, or an undocumented code)
1080    #[default]
1081    Unknown = -1,
1082    /// Financing (margin) IPO subscription (`FinancingIPO`)
1083    Financing = 1,
1084    /// Cash IPO subscription (`CashIPO`)
1085    Cash = 2,
1086}
1087
1088/// Kind of commission coupon (the server's `unlimited` code)
1089///
1090/// The meanings are the ones the Longbridge app gives the codes; the proto
1091/// names, which read differently, are given in brackets.
1092#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
1093#[repr(i32)]
1094pub enum CommissionUnlimitedType {
1095    /// Unknown (an undocumented code)
1096    #[default]
1097    Unknown = -1,
1098    /// Time-limited free commission (`Proportionate`, code 0)
1099    Proportionate = 0,
1100    /// Commission rebate (`Full`, code 1)
1101    Full = 1,
1102    /// Commission deduction (`Lifetime`, code 2)
1103    Lifetime = 2,
1104    /// Per-use card with a fixed amount per use: `amount / usage_count`
1105    /// (`ByAmountPer`, code 6)
1106    ByAmountPer = 6,
1107    /// Per-use discount card, capped at `amount_limit` per use (`ByRatePer`,
1108    /// code 7)
1109    ByRatePer = 7,
1110}
1111
1112/// Investor type a quote coupon applies to
1113#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
1114#[repr(i32)]
1115pub enum QuoteInvestorType {
1116    /// Unknown (an undocumented code)
1117    #[default]
1118    Unknown = -1,
1119    /// Any investor (`INVESTOR_TYPE_ANY`)
1120    Any = 0,
1121    /// Non-professional investors (`INVESTOR_TYPE_NON_PROFESSIONAL`)
1122    NonProfessional = 1,
1123    /// Professional investors (`INVESTOR_TYPE_PROFESSIONAL`)
1124    Professional = 2,
1125}
1126
1127impl_named_code_enum!(
1128    CouponTargetType {
1129        "StockTrade" => Stock,
1130        "UsStockOptions" => UsOption,
1131        "HkStockWarrant" => HkWarrant,
1132        "ETF" => Etf,
1133        "LOF" => Lof,
1134    }
1135    IpoCouponTargetType {
1136        "FinancingIPO" => Financing,
1137        "CashIPO" => Cash,
1138    }
1139    CommissionUnlimitedType {
1140        "Proportionate" => Proportionate,
1141        "Full" => Full,
1142        "Lifetime" => Lifetime,
1143        "ByAmountPer" => ByAmountPer,
1144        "ByRatePer" => ByRatePer,
1145    }
1146    QuoteInvestorType {
1147        "INVESTOR_TYPE_ANY" => Any,
1148        "INVESTOR_TYPE_NON_PROFESSIONAL" => NonProfessional,
1149        "INVESTOR_TYPE_PROFESSIONAL" => Professional,
1150    }
1151);
1152
1153/// Decodes one element of a list of enum codes: a number (or numeric
1154/// string) gives its value (`Unknown` for an undocumented code) and its raw
1155/// code; a known name gives its value and code; anything else (null, an
1156/// unknown name, an object) is `None` and is skipped by both [`enum_vec`]
1157/// and [`raw_codes`], so the two lists stay the same length and order.
1158fn enum_element<T>(item: &serde_json::Value) -> Option<(T, i32)>
1159where
1160    T: serde::de::DeserializeOwned + Into<i32> + Copy + Default + PartialEq,
1161{
1162    let typed: T = serde_json::from_value(item.clone()).unwrap_or_default();
1163    match serde_utils::account_int_opt(item).and_then(|v| i32::try_from(v).ok()) {
1164        Some(code) => Some((typed, code)),
1165        None => (typed != T::default()).then(|| (typed, typed.into())),
1166    }
1167}
1168
1169/// Decodes a list of enum values (each a name or a code), skipping elements
1170/// that are neither (see [`enum_element`]); anything other than a JSON array
1171/// becomes empty.
1172fn enum_vec<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
1173where
1174    D: Deserializer<'de>,
1175    T: serde::de::DeserializeOwned + Into<i32> + Copy + Default + PartialEq,
1176{
1177    Ok(match serde_json::Value::deserialize(deserializer)? {
1178        serde_json::Value::Array(items) => items
1179            .iter()
1180            .filter_map(enum_element::<T>)
1181            .map(|(typed, _)| typed)
1182            .collect(),
1183        _ => Vec::new(),
1184    })
1185}
1186
1187/// Decodes an optional nested object: `null` or anything other than a JSON
1188/// object (the server sends `null` for the detail objects of other coupon
1189/// types) becomes `None`.
1190fn object_opt<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
1191where
1192    D: Deserializer<'de>,
1193    T: serde::de::DeserializeOwned,
1194{
1195    match serde_json::Value::deserialize(deserializer)? {
1196        value @ serde_json::Value::Object(_) => serde_json::from_value(value)
1197            .map(Some)
1198            .map_err(D::Error::custom),
1199        _ => Ok(None),
1200    }
1201}
1202
1203/// Decodes a list of nested objects: anything other than a JSON array becomes
1204/// empty, and elements that are not JSON objects are skipped.
1205fn object_vec<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
1206where
1207    D: Deserializer<'de>,
1208    T: serde::de::DeserializeOwned,
1209{
1210    match serde_json::Value::deserialize(deserializer)? {
1211        serde_json::Value::Array(items) => items
1212            .into_iter()
1213            .filter(serde_json::Value::is_object)
1214            .map(serde_json::from_value)
1215            .collect::<Result<Vec<_>, _>>()
1216            .map_err(D::Error::custom),
1217        _ => Ok(Vec::new()),
1218    }
1219}
1220
1221/// Decodes a nested object, or its default when the value is `null` or not a
1222/// JSON object.
1223fn object_or_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
1224where
1225    D: Deserializer<'de>,
1226    T: serde::de::DeserializeOwned + Default,
1227{
1228    Ok(object_opt(deserializer)?.unwrap_or_default())
1229}
1230
1231/// Decodes a list of 64-bit integers leniently (numbers or integer strings);
1232/// anything other than a JSON array becomes empty.
1233fn int64_vec<'de, D>(deserializer: D) -> Result<Vec<i64>, D::Error>
1234where
1235    D: Deserializer<'de>,
1236{
1237    Ok(match serde_json::Value::deserialize(deserializer)? {
1238        serde_json::Value::Array(items) => items
1239            .iter()
1240            .map(|v| serde_utils::account_int_opt(v).unwrap_or_default())
1241            .collect(),
1242        _ => Vec::new(),
1243    })
1244}
1245
1246/// Commission terms of a commission coupon (`commission`)
1247#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1248#[serde(default, remote = "Self")]
1249pub struct CouponCommission {
1250    /// Markets the coupon applies to
1251    #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1252    pub markets: Vec<String>,
1253    /// Rebate rate, as returned by the server
1254    #[serde(deserialize_with = "serde_utils::string_lenient")]
1255    pub rebate_rate: String,
1256    /// Instrument types the coupon applies to
1257    #[serde(deserialize_with = "enum_vec")]
1258    pub bz_types: Vec<CouponTargetType>,
1259    /// The server's numeric codes of `bz_types`, including codes this SDK
1260    /// does not know (`Unknown` in `bz_types`); always the same length and
1261    /// order as `bz_types` (elements that are neither a code nor a known name
1262    /// are left out of both)
1263    pub bz_types_raw: Vec<i32>,
1264    /// Remaining commission balance
1265    #[serde(with = "serde_utils::decimal_opt_lenient")]
1266    pub commission_balance: Option<Decimal>,
1267    /// Commission duration in seconds (the app reads 200 years or more as
1268    /// lifetime free commission)
1269    #[serde(deserialize_with = "serde_utils::account_int64")]
1270    pub commission_duration: i64,
1271    /// Kind of commission coupon (the server's `unlimited` code)
1272    pub unlimited: CommissionUnlimitedType,
1273    /// The server's numeric code of `unlimited`, also when it is a code this
1274    /// SDK does not know (`unlimited` is then `Unknown`); `None` when the value
1275    /// is missing or is not a code
1276    pub unlimited_raw: Option<i32>,
1277    /// Commission expiry time (`None` when not set)
1278    #[serde(with = "serde_utils::account_time_opt")]
1279    pub commission_expired_time: Option<OffsetDateTime>,
1280    /// Number of times used
1281    #[serde(deserialize_with = "serde_utils::account_int64")]
1282    pub usage_count: i64,
1283    /// Number of uses left
1284    #[serde(deserialize_with = "serde_utils::account_int64")]
1285    pub lave_usage_count: i64,
1286    /// Settlement model, as returned by the server
1287    #[serde(deserialize_with = "serde_utils::string_lenient")]
1288    pub settlement_model: String,
1289    /// Amount cap per use of a per-use discount card
1290    /// ([`CommissionUnlimitedType::ByRatePer`]), as returned by the server
1291    #[serde(deserialize_with = "serde_utils::account_int64")]
1292    pub amount_limit: i64,
1293    /// Whether the coupon can be combined with other coupons
1294    #[serde(deserialize_with = "serde_utils::bool_lenient")]
1295    pub superposition: bool,
1296}
1297
1298/// Terms of an AI benefit coupon (`ai_benefit`)
1299#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1300#[serde(default)]
1301pub struct CouponAiBenefit {
1302    /// Length of the benefit in days
1303    #[serde(deserialize_with = "serde_utils::account_int32")]
1304    pub benefit_days: i32,
1305    /// Start of the benefit (`None` when not set)
1306    #[serde(with = "serde_utils::account_time_opt")]
1307    pub benefit_start: Option<OffsetDateTime>,
1308    /// End of the benefit (`None` when not set)
1309    #[serde(with = "serde_utils::account_time_opt")]
1310    pub benefit_end: Option<OffsetDateTime>,
1311    /// Benefit tag, as returned by the server
1312    #[serde(deserialize_with = "serde_utils::string_lenient")]
1313    pub benefit_tag: String,
1314}
1315
1316/// Terms of a cash coupon (`cash`)
1317#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1318#[serde(default)]
1319pub struct CouponCash {
1320    /// Receive duration, as returned by the server (its unit and meaning are
1321    /// not confirmed)
1322    #[serde(deserialize_with = "serde_utils::account_int64")]
1323    pub receive_duration: i64,
1324}
1325
1326/// A store of a coffee coupon
1327#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1328#[serde(default)]
1329pub struct CouponCoffeeStore {
1330    /// Store ID
1331    #[serde(deserialize_with = "serde_utils::account_int64")]
1332    pub store_id: i64,
1333    /// Store name
1334    #[serde(deserialize_with = "serde_utils::string_lenient")]
1335    pub store_name: String,
1336}
1337
1338/// Terms of a coffee coupon (`coffee_coupon`)
1339#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1340#[serde(default)]
1341pub struct CouponCoffee {
1342    /// Coupon channel, as returned by the server
1343    #[serde(deserialize_with = "serde_utils::string_lenient")]
1344    pub coupon_channel: String,
1345    /// Coupon ID, as returned by the server
1346    #[serde(deserialize_with = "serde_utils::string_lenient")]
1347    pub coupon_id: String,
1348    /// Voucher template code, e.g. `coffee-50` (not a personal redemption
1349    /// code)
1350    #[serde(deserialize_with = "serde_utils::string_lenient")]
1351    pub coupon_no: String,
1352    /// Whether the coupon can be used at every store
1353    #[serde(deserialize_with = "serde_utils::bool_lenient")]
1354    pub is_available_all_store: bool,
1355    /// Period type (e.g. `day`), as returned by the server
1356    #[serde(deserialize_with = "serde_utils::string_lenient")]
1357    pub period_type: String,
1358    /// ID of the store the coupon was settled at (`0` when not settled)
1359    #[serde(deserialize_with = "serde_utils::account_int64")]
1360    pub settled_store_id: i64,
1361    /// IDs of the stores the coupon can be used at
1362    #[serde(deserialize_with = "int64_vec")]
1363    pub store_id_list: Vec<i64>,
1364    /// Stores the coupon can be used at
1365    #[serde(deserialize_with = "object_vec")]
1366    pub store_list: Vec<CouponCoffeeStore>,
1367    /// Threshold, as returned by the server
1368    #[serde(deserialize_with = "serde_utils::account_int64")]
1369    pub threshold: i64,
1370    /// Use limit (`total` or `period`), as returned by the server
1371    #[serde(deserialize_with = "serde_utils::string_lenient")]
1372    pub use_limit: String,
1373}
1374
1375/// A counter (security) of a crypto coupon
1376#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1377#[serde(default)]
1378pub struct CouponCryptoCounter {
1379    /// Counter ID
1380    #[serde(deserialize_with = "serde_utils::string_lenient")]
1381    pub counter_id: String,
1382}
1383
1384/// Fallback of a crypto coupon
1385#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1386#[serde(default)]
1387pub struct CouponCryptoFallback {
1388    /// Whether the fallback is enabled
1389    #[serde(deserialize_with = "serde_utils::bool_lenient")]
1390    pub enabled: bool,
1391    /// Counter ID
1392    #[serde(deserialize_with = "serde_utils::string_lenient")]
1393    pub counter_id: String,
1394}
1395
1396/// Terms of a crypto coupon (`crypto`)
1397#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1398#[serde(default)]
1399pub struct CouponCrypto {
1400    /// Fallback
1401    #[serde(deserialize_with = "object_or_default")]
1402    pub fallback: CouponCryptoFallback,
1403    /// Optional counters
1404    #[serde(deserialize_with = "object_vec")]
1405    pub optional_counters: Vec<CouponCryptoCounter>,
1406}
1407
1408/// Terms of a finance interest coupon (`finance_interest`)
1409///
1410/// The meaning of these fields is not confirmed; they are returned as the
1411/// server sends them.
1412#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1413#[serde(default)]
1414pub struct CouponFinanceInterest {
1415    /// Discount mode, as returned by the server
1416    #[serde(deserialize_with = "serde_utils::account_int32")]
1417    pub discount_mode: i32,
1418    /// Discount rate
1419    #[serde(with = "serde_utils::decimal_opt_lenient")]
1420    pub discount_rate: Option<Decimal>,
1421    /// Whether the coupon can be combined with other coupons
1422    #[serde(deserialize_with = "serde_utils::bool_lenient")]
1423    pub superposition: bool,
1424}
1425
1426/// Terms of a fund deduction coupon (`fund_deduct`)
1427#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1428#[serde(default)]
1429pub struct CouponFundDeduct {
1430    /// Maximum risk level, as returned by the server
1431    #[serde(deserialize_with = "serde_utils::account_int32")]
1432    pub max_risk_level: i32,
1433    /// Minimum order amount, as returned by the server
1434    #[serde(deserialize_with = "serde_utils::string_lenient")]
1435    pub min_order_amount: String,
1436    /// Order types, as returned by the server
1437    #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1438    pub order_types: Vec<String>,
1439    /// Underlying type, as returned by the server
1440    #[serde(deserialize_with = "serde_utils::string_lenient")]
1441    pub underlying_type: String,
1442    /// Underlying values, as returned by the server
1443    #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1444    pub underlying_values: Vec<String>,
1445    /// Underlying names, as returned by the server
1446    #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1447    pub underlying_names: Vec<String>,
1448}
1449
1450/// Terms of a quote (market data) or fundamental-data coupon (`quote` /
1451/// `fundamental`)
1452#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1453#[serde(default, remote = "Self")]
1454pub struct CouponQuote {
1455    /// Current end time (`None` when not set)
1456    #[serde(with = "serde_utils::account_time_opt")]
1457    pub current_end_time: Option<OffsetDateTime>,
1458    /// Whether the coupon is inapplicable, as returned by the server
1459    #[serde(deserialize_with = "serde_utils::bool_lenient")]
1460    pub inapplicable: bool,
1461    /// Investor type the coupon applies to
1462    pub investor_type: QuoteInvestorType,
1463    /// The server's numeric code of `investor_type`, also when it is a code
1464    /// this SDK does not know (`investor_type` is then `Unknown`); `None` when
1465    /// the value is missing or is not a code
1466    pub investor_type_raw: Option<i32>,
1467    /// Whether the coupon is activated manually
1468    #[serde(deserialize_with = "serde_utils::bool_lenient")]
1469    pub manual_activate: bool,
1470    /// Markets
1471    #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1472    pub markets: Vec<String>,
1473    /// Investor type of the member, as returned by the server
1474    #[serde(deserialize_with = "serde_utils::account_int32")]
1475    pub member_investor_type: i32,
1476    /// Paired SPU number, as returned by the server
1477    #[serde(deserialize_with = "serde_utils::string_lenient")]
1478    pub pair_spu_no: String,
1479    /// Quote duration in seconds (the app reads 200 years or more as
1480    /// lifetime)
1481    #[serde(deserialize_with = "serde_utils::account_int64")]
1482    pub quote_duration: i64,
1483    /// Quote market
1484    #[serde(deserialize_with = "serde_utils::string_lenient")]
1485    pub quote_market: String,
1486    /// Quote tags
1487    #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1488    pub quote_tags: Vec<String>,
1489    /// Whether the coupon can be combined with other coupons
1490    #[serde(deserialize_with = "serde_utils::bool_lenient")]
1491    pub superposition: bool,
1492}
1493
1494/// Terms of an IPO coupon (`ipo`)
1495#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1496#[serde(default)]
1497pub struct CouponIpo {
1498    /// Subscription ID
1499    #[serde(deserialize_with = "serde_utils::string_lenient")]
1500    pub subscription_id: String,
1501}
1502
1503/// Terms of an IPO commission coupon (`ipo_commission`)
1504#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1505#[serde(default, remote = "Self")]
1506pub struct CouponIpoCommission {
1507    /// IPO subscription types the coupon applies to
1508    #[serde(deserialize_with = "enum_vec")]
1509    pub bz_types: Vec<IpoCouponTargetType>,
1510    /// The server's numeric codes of `bz_types`, including codes this SDK
1511    /// does not know (`Unknown` in `bz_types`); always the same length and
1512    /// order as `bz_types` (elements that are neither a code nor a known name
1513    /// are left out of both)
1514    pub bz_types_raw: Vec<i32>,
1515    /// Counter ID
1516    #[serde(deserialize_with = "serde_utils::string_lenient")]
1517    pub counter_id: String,
1518    /// Counter name
1519    #[serde(deserialize_with = "serde_utils::string_lenient")]
1520    pub counter_name: String,
1521    /// Financing limit, as returned by the server
1522    #[serde(deserialize_with = "serde_utils::string_lenient")]
1523    pub financing_limit: String,
1524}
1525
1526/// Terms of an IPO interest coupon (`ipo_interest`)
1527#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1528#[serde(default)]
1529pub struct CouponIpoInterest {
1530    /// Annual interest discount rate, as returned by the server (the app
1531    /// computes the daily discount as rate × financed amount / 365)
1532    #[serde(deserialize_with = "serde_utils::string_lenient")]
1533    pub discount_rate: String,
1534}
1535
1536/// Terms of a platform fee deduction coupon (`platform_fee_deduct`)
1537#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1538#[serde(default, remote = "Self")]
1539pub struct CouponPlatformFeeDeduct {
1540    /// Instrument types the coupon applies to
1541    #[serde(deserialize_with = "enum_vec")]
1542    pub bz_types: Vec<CouponTargetType>,
1543    /// The server's numeric codes of `bz_types`, including codes this SDK
1544    /// does not know (`Unknown` in `bz_types`); always the same length and
1545    /// order as `bz_types` (elements that are neither a code nor a known name
1546    /// are left out of both)
1547    pub bz_types_raw: Vec<i32>,
1548    /// Counter ID
1549    #[serde(deserialize_with = "serde_utils::string_lenient")]
1550    pub counter_id: String,
1551    /// Counter name
1552    #[serde(deserialize_with = "serde_utils::string_lenient")]
1553    pub counter_name: String,
1554    /// Markets the coupon applies to
1555    #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1556    pub markets: Vec<String>,
1557    /// Number of times used
1558    #[serde(deserialize_with = "serde_utils::account_int64")]
1559    pub usage_count: i64,
1560    /// Number of uses left
1561    #[serde(deserialize_with = "serde_utils::account_int64")]
1562    pub lave_usage_count: i64,
1563    /// Whether the coupon can be combined with other coupons
1564    #[serde(deserialize_with = "serde_utils::bool_lenient")]
1565    pub superposition: bool,
1566}
1567
1568/// An optional counter of a stock coupon
1569#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1570#[serde(default)]
1571pub struct CouponStockCounter {
1572    /// Counter ID
1573    #[serde(deserialize_with = "serde_utils::string_lenient")]
1574    pub counter_id: String,
1575    /// Shares, as returned by the server
1576    #[serde(deserialize_with = "serde_utils::string_lenient")]
1577    pub shares: String,
1578}
1579
1580/// Fallback of a stock coupon
1581#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1582#[serde(default)]
1583pub struct CouponStockFallback {
1584    /// Whether the fallback is enabled
1585    #[serde(deserialize_with = "serde_utils::bool_lenient")]
1586    pub enabled: bool,
1587    /// Fallback type (the server's `type`), as returned by the server
1588    #[serde(
1589        rename(deserialize = "type"),
1590        alias = "fallback_type",
1591        deserialize_with = "serde_utils::string_lenient"
1592    )]
1593    pub fallback_type: String,
1594    /// Counter ID
1595    #[serde(deserialize_with = "serde_utils::string_lenient")]
1596    pub counter_id: String,
1597    /// Shares, as returned by the server
1598    #[serde(deserialize_with = "serde_utils::string_lenient")]
1599    pub shares: String,
1600}
1601
1602/// Terms of a stock coupon (`stock`)
1603#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1604#[serde(default)]
1605pub struct CouponStock {
1606    /// Counter ID
1607    #[serde(deserialize_with = "serde_utils::string_lenient")]
1608    pub counter_id: String,
1609    /// Counter name
1610    #[serde(deserialize_with = "serde_utils::string_lenient")]
1611    pub counter_name: String,
1612    /// Amount
1613    #[serde(with = "serde_utils::decimal_opt_lenient")]
1614    pub amount: Option<Decimal>,
1615    /// Redemption type (`by_card_value` or `shares_number`), as returned by
1616    /// the server
1617    #[serde(deserialize_with = "serde_utils::string_lenient")]
1618    pub redemption_type: String,
1619    /// Delivery way (`card_exchange` or `account_transfer`), as returned by
1620    /// the server
1621    #[serde(deserialize_with = "serde_utils::string_lenient")]
1622    pub send_way: String,
1623    /// Optional counters
1624    #[serde(deserialize_with = "object_vec")]
1625    pub optional_counters: Vec<CouponStockCounter>,
1626    /// Fallback
1627    #[serde(deserialize_with = "object_or_default")]
1628    pub fallback: CouponStockFallback,
1629}
1630
1631/// Terms of a stock fragment coupon (`stock_fragment`)
1632#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1633#[serde(default, remote = "Self")]
1634pub struct CouponStockFragment {
1635    /// Counter ID
1636    #[serde(deserialize_with = "serde_utils::string_lenient")]
1637    pub counter_id: String,
1638    /// Counter name
1639    #[serde(deserialize_with = "serde_utils::string_lenient")]
1640    pub counter_name: String,
1641    /// Market
1642    #[serde(deserialize_with = "serde_utils::string_lenient")]
1643    pub market: String,
1644    /// Markets
1645    #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1646    pub markets: Vec<String>,
1647    /// Instrument type the coupon applies to
1648    pub underlying_type: CouponTargetType,
1649    /// The server's numeric code of `underlying_type`, also when it is a code
1650    /// this SDK does not know (`underlying_type` is then `Unknown`); `None`
1651    /// when the value is missing or is not a code
1652    pub underlying_type_raw: Option<i32>,
1653    /// Amounts, as returned by the server (key-ordered)
1654    #[serde(deserialize_with = "serde_utils::string_map_lenient")]
1655    pub amounts: std::collections::BTreeMap<String, String>,
1656}
1657
1658/// A coupon (reward card)
1659///
1660/// The type-specific terms are in the field named after the coupon type
1661/// (`commission`, `quote`, `stock`, …); the fields of other types are
1662/// `None`. App styling (cover, background, …) and the server's deprecated
1663/// top-level duplicates of the commission terms are not modelled, nor is the
1664/// `fund_interest` object, which the server does not describe.
1665#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1666#[serde(default, remote = "Self")]
1667pub struct Coupon {
1668    /// Coupon ID (32 hex characters; pass to
1669    /// [`crate::AssetContext::coupon_orders`])
1670    #[serde(deserialize_with = "serde_utils::string_lenient")]
1671    pub card_id: String,
1672    /// Coupon type, e.g. `commission`, `platform_fee_deduct`, `stock`,
1673    /// `quote`, `cash`
1674    #[serde(deserialize_with = "serde_utils::string_lenient")]
1675    pub card_type: String,
1676    /// Title
1677    #[serde(deserialize_with = "serde_utils::string_lenient")]
1678    pub title: String,
1679    /// Secondary title
1680    #[serde(deserialize_with = "serde_utils::string_lenient")]
1681    pub title_sec: String,
1682    /// Description
1683    #[serde(deserialize_with = "serde_utils::string_lenient")]
1684    pub description: String,
1685    /// Terms and details
1686    #[serde(deserialize_with = "serde_utils::string_lenient")]
1687    pub detail: String,
1688    /// Status
1689    pub card_status: CouponStatus,
1690    /// The server's numeric code of `card_status`, also when it is a code this
1691    /// SDK does not know (`card_status` is then `Unknown`); `None` when the
1692    /// value is missing or is not a code
1693    pub card_status_raw: Option<i32>,
1694    /// Start of validity
1695    #[serde(with = "serde_utils::account_time_opt")]
1696    pub start_time: Option<OffsetDateTime>,
1697    /// End of validity (`None` when not set or when the coupon never
1698    /// expires; see [`Self::no_expiry`])
1699    #[serde(with = "serde_utils::account_time_opt")]
1700    pub end_time: Option<OffsetDateTime>,
1701    /// Whether the coupon never expires (the server's end time is in or after
1702    /// 2100)
1703    #[serde(deserialize_with = "serde_utils::bool_lenient")]
1704    pub no_expiry: bool,
1705    /// Activation time (`None` when not activated)
1706    #[serde(with = "serde_utils::account_time_opt")]
1707    pub activate_time: Option<OffsetDateTime>,
1708    /// Amount
1709    #[serde(with = "serde_utils::decimal_opt_lenient")]
1710    pub amount: Option<Decimal>,
1711    /// Currency
1712    #[serde(deserialize_with = "serde_utils::string_lenient")]
1713    pub currency: String,
1714    /// Trading sessions the coupon applies to, as display text
1715    #[serde(deserialize_with = "serde_utils::string_lenient")]
1716    pub available_trade_session: String,
1717    /// Trading sessions the coupon applies to, as returned by the server
1718    #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1719    pub trade_sessions: Vec<String>,
1720    /// Subscription ID, as returned by the server
1721    #[serde(deserialize_with = "serde_utils::string_lenient")]
1722    pub subscription_id: String,
1723    /// Terms of an AI benefit coupon
1724    #[serde(deserialize_with = "object_opt")]
1725    pub ai_benefit: Option<CouponAiBenefit>,
1726    /// Terms of a cash coupon
1727    #[serde(deserialize_with = "object_opt")]
1728    pub cash: Option<CouponCash>,
1729    /// Terms of a coffee coupon
1730    #[serde(deserialize_with = "object_opt")]
1731    pub coffee_coupon: Option<CouponCoffee>,
1732    /// Terms of a commission coupon
1733    #[serde(deserialize_with = "object_opt")]
1734    pub commission: Option<CouponCommission>,
1735    /// Terms of a crypto coupon
1736    #[serde(deserialize_with = "object_opt")]
1737    pub crypto: Option<CouponCrypto>,
1738    /// Terms of a finance interest coupon
1739    #[serde(deserialize_with = "object_opt")]
1740    pub finance_interest: Option<CouponFinanceInterest>,
1741    /// Terms of a fund deduction coupon
1742    #[serde(deserialize_with = "object_opt")]
1743    pub fund_deduct: Option<CouponFundDeduct>,
1744    /// Terms of a fundamental-data coupon
1745    #[serde(deserialize_with = "object_opt")]
1746    pub fundamental: Option<CouponQuote>,
1747    /// Terms of an IPO coupon
1748    #[serde(deserialize_with = "object_opt")]
1749    pub ipo: Option<CouponIpo>,
1750    /// Terms of an IPO commission coupon
1751    #[serde(deserialize_with = "object_opt")]
1752    pub ipo_commission: Option<CouponIpoCommission>,
1753    /// Terms of an IPO interest coupon
1754    #[serde(deserialize_with = "object_opt")]
1755    pub ipo_interest: Option<CouponIpoInterest>,
1756    /// Terms of a platform fee deduction coupon
1757    #[serde(deserialize_with = "object_opt")]
1758    pub platform_fee_deduct: Option<CouponPlatformFeeDeduct>,
1759    /// Terms of a quote (market data) coupon
1760    #[serde(deserialize_with = "object_opt")]
1761    pub quote: Option<CouponQuote>,
1762    /// Terms of a stock coupon
1763    #[serde(deserialize_with = "object_opt")]
1764    pub stock: Option<CouponStock>,
1765    /// Terms of a stock fragment coupon
1766    #[serde(deserialize_with = "object_opt")]
1767    pub stock_fragment: Option<CouponStockFragment>,
1768}
1769
1770/// Response for the coupon list
1771#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1772#[serde(default)]
1773pub struct CouponsResponse {
1774    /// Pinned coupons shown above the list (repeated on every page)
1775    #[serde(deserialize_with = "coupon_list")]
1776    pub top_list: Vec<Coupon>,
1777    /// Coupons on this page
1778    #[serde(deserialize_with = "coupon_list")]
1779    pub list: Vec<Coupon>,
1780    /// Pinned coupons shown below the list (repeated on every page)
1781    #[serde(deserialize_with = "coupon_list")]
1782    pub bottom_list: Vec<Coupon>,
1783    /// Total number of coupons
1784    #[serde(deserialize_with = "serde_utils::account_int64")]
1785    pub total: i64,
1786    /// Number of expired coupons
1787    #[serde(deserialize_with = "serde_utils::account_int64")]
1788    pub expired_count: i64,
1789}
1790
1791/// Decodes a coupon list, setting [`Coupon::no_expiry`] from the server's raw
1792/// `end_time` (which [`Coupon::end_time`] drops when it is past 2100).
1793fn coupon_list<'de, D>(deserializer: D) -> Result<Vec<Coupon>, D::Error>
1794where
1795    D: Deserializer<'de>,
1796{
1797    let items = match serde_json::Value::deserialize(deserializer)? {
1798        serde_json::Value::Array(items) => items,
1799        _ => return Ok(Vec::new()),
1800    };
1801    items
1802        .into_iter()
1803        .map(|item| {
1804            let never_expires = item
1805                .get("end_time")
1806                .is_some_and(serde_utils::account_time_is_far_future);
1807            let mut coupon: Coupon = serde_json::from_value(item).map_err(D::Error::custom)?;
1808            coupon.no_expiry |= never_expires;
1809            Ok(coupon)
1810        })
1811        .collect()
1812}
1813
1814/// An order a coupon was applied to
1815#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1816#[serde(default)]
1817pub struct CouponOrder {
1818    /// Order ID
1819    #[serde(deserialize_with = "serde_utils::string_lenient")]
1820    pub order_id: String,
1821    /// State text, as returned by the server
1822    #[serde(deserialize_with = "serde_utils::string_lenient")]
1823    pub state: String,
1824    /// State value, as returned by the server (e.g. `FilledStatus`)
1825    #[serde(deserialize_with = "serde_utils::string_lenient")]
1826    pub state_val: String,
1827    /// Executed price
1828    #[serde(with = "serde_utils::decimal_opt_lenient")]
1829    pub executed_price: Option<Decimal>,
1830    /// Executed quantity
1831    #[serde(with = "serde_utils::decimal_opt_lenient")]
1832    pub executed_quantity: Option<Decimal>,
1833    /// Currency
1834    #[serde(deserialize_with = "serde_utils::string_lenient")]
1835    pub currency: String,
1836    /// Settlement currency
1837    #[serde(deserialize_with = "serde_utils::string_lenient")]
1838    pub settlement_currency: String,
1839    /// Rebate amount
1840    #[serde(with = "serde_utils::decimal_opt_lenient")]
1841    pub rebate: Option<Decimal>,
1842    /// Rebate date, as returned by the server
1843    #[serde(deserialize_with = "serde_utils::string_lenient")]
1844    pub rebate_dt: String,
1845}
1846
1847#[derive(Debug, Default, Deserialize)]
1848pub(crate) struct CouponOrdersResponse {
1849    #[serde(default, deserialize_with = "serde_utils::null_as_default")]
1850    pub(crate) orders: Vec<CouponOrder>,
1851}
1852
1853/// A deposit record
1854///
1855/// Receipt images uploaded with the deposit are intentionally not modelled;
1856/// only their number is ([`Self::voucher_count`]).
1857#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1858#[serde(default, remote = "Self")]
1859pub struct Deposit {
1860    /// Record ID
1861    #[serde(deserialize_with = "serde_utils::string_lenient")]
1862    pub id: String,
1863    /// Created time
1864    #[serde(with = "serde_utils::account_time_opt")]
1865    pub created_at: Option<OffsetDateTime>,
1866    /// Updated time
1867    #[serde(with = "serde_utils::account_time_opt")]
1868    pub updated_at: Option<OffsetDateTime>,
1869    /// Currency
1870    #[serde(deserialize_with = "serde_utils::string_lenient")]
1871    pub currency: String,
1872    /// Notified (applied) amount
1873    #[serde(with = "serde_utils::decimal_opt_lenient")]
1874    pub amount: Option<Decimal>,
1875    /// Received amount (`0` = not received yet)
1876    #[serde(with = "serde_utils::decimal_opt_lenient")]
1877    pub receivable_amount: Option<Decimal>,
1878    /// State text, as returned by the server
1879    #[serde(deserialize_with = "serde_utils::string_lenient")]
1880    pub state: String,
1881    /// State code
1882    pub state_code: DepositState,
1883    /// The server's numeric code of `state_code`, also when it is a code this
1884    /// SDK does not know (`state_code` is then `Unknown`); `None` when the
1885    /// value is missing or is not a code
1886    pub state_code_raw: Option<i32>,
1887    /// Sub-state code, as returned by the server
1888    #[serde(deserialize_with = "serde_utils::account_int32")]
1889    pub sub_state_code: i32,
1890    /// Deposit method ID
1891    #[serde(deserialize_with = "serde_utils::string_lenient")]
1892    pub bank_operation_type_id: String,
1893    /// Deposit method name
1894    #[serde(deserialize_with = "serde_utils::string_lenient")]
1895    pub bank_operation_type_name: String,
1896    /// Reference number
1897    #[serde(deserialize_with = "serde_utils::string_lenient")]
1898    pub reference_no: String,
1899    /// Whether the deposit can still be cancelled
1900    #[serde(deserialize_with = "serde_utils::bool_lenient")]
1901    pub can_cancel: bool,
1902    /// SWIFT code of the paying bank
1903    #[serde(deserialize_with = "serde_utils::string_lenient")]
1904    pub user_bank_swift_code: String,
1905    /// Number of receipts uploaded with the deposit (the length of the
1906    /// server's `vouchers`)
1907    #[serde(
1908        rename(deserialize = "vouchers"),
1909        alias = "voucher_count",
1910        deserialize_with = "item_count"
1911    )]
1912    pub voucher_count: i64,
1913}
1914
1915/// Decodes the number of items of a JSON array (the server's `vouchers`,
1916/// whose items are not modelled); a number (`voucher_count`, on a round trip)
1917/// is read as the count itself.
1918fn item_count<'de, D>(deserializer: D) -> Result<i64, D::Error>
1919where
1920    D: Deserializer<'de>,
1921{
1922    Ok(match serde_json::Value::deserialize(deserializer)? {
1923        serde_json::Value::Array(items) => i64::try_from(items.len()).unwrap_or(i64::MAX),
1924        other => serde_utils::account_int_opt(&other).unwrap_or_default(),
1925    })
1926}
1927
1928/// One page of deposit records
1929///
1930/// The server also returns a `total`, but it follows the page size rather
1931/// than the record count, so it is not modelled; see [`Self::has_more`].
1932#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1933#[serde(default)]
1934pub struct DepositsResponse {
1935    /// Deposit records, newest first
1936    #[serde(deserialize_with = "serde_utils::null_as_default")]
1937    pub items: Vec<Deposit>,
1938    /// A full page came back (as many records as the page size sent, at
1939    /// most 20), so the next page may hold more
1940    pub has_more: bool,
1941}
1942
1943/// A withdrawal record
1944#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1945#[serde(default, remote = "Self")]
1946pub struct Withdrawal {
1947    /// Record ID
1948    #[serde(deserialize_with = "serde_utils::string_lenient")]
1949    pub id: String,
1950    /// Order ID
1951    #[serde(deserialize_with = "serde_utils::string_lenient")]
1952    pub order_id: String,
1953    /// Created time
1954    #[serde(with = "serde_utils::account_time_opt")]
1955    pub created_at: Option<OffsetDateTime>,
1956    /// Currency
1957    #[serde(deserialize_with = "serde_utils::string_lenient")]
1958    pub currency: String,
1959    /// Applied amount
1960    #[serde(with = "serde_utils::decimal_opt_lenient")]
1961    pub amount: Option<Decimal>,
1962    /// Fee
1963    #[serde(with = "serde_utils::decimal_opt_lenient")]
1964    pub fee: Option<Decimal>,
1965    /// Amount paid out
1966    #[serde(with = "serde_utils::decimal_opt_lenient")]
1967    pub settlement_amount: Option<Decimal>,
1968    /// State code (the server's `state`)
1969    #[serde(rename(deserialize = "state"), alias = "state_code")]
1970    pub state_code: WithdrawalState,
1971    /// The server's numeric code of `state_code`, also when it is a code this
1972    /// SDK does not know (`state_code` is then `Unknown`); `None` when the
1973    /// value is missing or is not a code
1974    pub state_code_raw: Option<i32>,
1975    /// Raw state, as returned by the server
1976    #[serde(deserialize_with = "serde_utils::string_lenient")]
1977    pub raw_state: String,
1978    /// State display text, as returned by the server
1979    #[serde(deserialize_with = "serde_utils::string_lenient")]
1980    pub state_description: String,
1981    /// Receiving bank account number, as returned by the server (not masked)
1982    #[serde(deserialize_with = "serde_utils::string_lenient")]
1983    pub bank_account: String,
1984    /// Receiving bank account, as displayed in the app
1985    #[serde(deserialize_with = "serde_utils::string_lenient")]
1986    pub display_bank_account: String,
1987    /// SWIFT code of the receiving bank
1988    #[serde(deserialize_with = "serde_utils::string_lenient")]
1989    pub user_bank_swift_code: String,
1990    /// Account channel
1991    #[serde(deserialize_with = "serde_utils::string_lenient")]
1992    pub account_channel: String,
1993}
1994
1995/// Response for the withdrawal list
1996#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1997#[serde(default)]
1998pub struct WithdrawalsResponse {
1999    /// Withdrawal records
2000    #[serde(deserialize_with = "serde_utils::null_as_default")]
2001    pub list: Vec<Withdrawal>,
2002    /// Total number of records
2003    #[serde(deserialize_with = "serde_utils::account_int64")]
2004    pub total: i64,
2005    /// A full page came back (as many records as the page size sent), so the
2006    /// next page may hold more
2007    pub has_more: bool,
2008}
2009
2010/// The server's numeric code behind a typed value: the wire value when it is
2011/// a number or an integer string, else the typed value's code when it is a
2012/// known one (the server sent its name), else `None`.
2013fn raw_code<T>(typed: T, wire: Option<&serde_json::Value>) -> Option<i32>
2014where
2015    T: Into<i32> + Copy + Default + PartialEq,
2016{
2017    wire.and_then(serde_utils::account_int_opt)
2018        .and_then(|v| i32::try_from(v).ok())
2019        .or_else(|| (typed != T::default()).then(|| typed.into()))
2020}
2021
2022/// The raw codes of a list decoded with [`enum_vec`]: the same elements are
2023/// skipped, so the result has the same length and order as the typed list.
2024fn raw_codes<T>(_typed: &[T], wire: Option<&serde_json::Value>) -> Vec<i32>
2025where
2026    T: serde::de::DeserializeOwned + Into<i32> + Copy + Default + PartialEq,
2027{
2028    match wire {
2029        Some(serde_json::Value::Array(items)) => items
2030            .iter()
2031            .filter_map(enum_element::<T>)
2032            .map(|(_, code)| code)
2033            .collect(),
2034        _ => Vec::new(),
2035    }
2036}
2037
2038/// Implements `Serialize` / `Deserialize` for a record decoded with
2039/// `#[serde(remote = "Self")]`, filling each `*_raw` companion field with the
2040/// server's numeric code read from the record's own keys (the first key
2041/// present wins). A record that already carries the `*_raw` key (one this SDK
2042/// serialized) keeps that value, so a round trip loses nothing.
2043macro_rules! impl_raw_codes {
2044    (@one $out:ident $value:ident $field:ident $raw:ident [$($key:literal),+] scalar) => {
2045        if $value.get(stringify!($raw)).is_none() {
2046            $out.$raw = raw_code($out.$field, [$($key),+].iter().find_map(|k| $value.get(*k)));
2047        }
2048    };
2049    (@one $out:ident $value:ident $field:ident $raw:ident [$($key:literal),+] vec) => {
2050        if $value.get(stringify!($raw)).is_none() {
2051            $out.$raw = raw_codes(&$out.$field, [$($key),+].iter().find_map(|k| $value.get(*k)));
2052        }
2053    };
2054    (@kind $out:ident $value:ident [$field:ident] => $raw:ident [$($key:literal),+]) => {
2055        impl_raw_codes!(@one $out $value $field $raw [$($key),+] vec);
2056    };
2057    (@kind $out:ident $value:ident $field:ident => $raw:ident [$($key:literal),+]) => {
2058        impl_raw_codes!(@one $out $value $field $raw [$($key),+] scalar);
2059    };
2060    ($($ty:ident { $($spec:tt)* })*) => {
2061        $(
2062            impl Serialize for $ty {
2063                fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2064                    $ty::serialize(self, serializer)
2065                }
2066            }
2067
2068            impl<'de> Deserialize<'de> for $ty {
2069                fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2070                    let value = serde_json::Value::deserialize(deserializer)?;
2071                    #[allow(unused_mut)]
2072                    let mut out = $ty::deserialize(&value).map_err(D::Error::custom)?;
2073                    impl_raw_codes!(@fields out value $($spec)*);
2074                    Ok(out)
2075                }
2076            }
2077        )*
2078    };
2079    (@fields $out:ident $value:ident) => {};
2080    (@fields $out:ident $value:ident [$field:ident] => $raw:ident [$($key:literal),+], $($rest:tt)*) => {
2081        impl_raw_codes!(@kind $out $value [$field] => $raw [$($key),+]);
2082        impl_raw_codes!(@fields $out $value $($rest)*);
2083    };
2084    (@fields $out:ident $value:ident $field:ident => $raw:ident [$($key:literal),+], $($rest:tt)*) => {
2085        impl_raw_codes!(@kind $out $value $field => $raw [$($key),+]);
2086        impl_raw_codes!(@fields $out $value $($rest)*);
2087    };
2088}
2089
2090impl_raw_codes!(
2091    BankCardAuthorization {
2092        status => status_raw ["status"],
2093    }
2094    BankCard {
2095        status => status_raw ["status"],
2096        witness_state => witness_state_raw ["witness_state"],
2097        bind_state => bind_state_raw ["bind_state"],
2098    }
2099    EddaApplication {
2100        status => status_raw ["status"],
2101    }
2102    TransferStock {
2103        state_code => state_code_raw ["state", "state_code"],
2104    }
2105    StockTransferIn {
2106        state_code => state_code_raw ["state_code"],
2107    }
2108    StockTransferOut {
2109        state_code => state_code_raw ["state_code"],
2110    }
2111    CouponCommission {
2112        [bz_types] => bz_types_raw ["bz_types"],
2113        unlimited => unlimited_raw ["unlimited"],
2114    }
2115    CouponQuote {
2116        investor_type => investor_type_raw ["investor_type"],
2117    }
2118    CouponIpoCommission {
2119        [bz_types] => bz_types_raw ["bz_types"],
2120    }
2121    CouponPlatformFeeDeduct {
2122        [bz_types] => bz_types_raw ["bz_types"],
2123    }
2124    CouponStockFragment {
2125        underlying_type => underlying_type_raw ["underlying_type"],
2126    }
2127    Coupon {
2128        card_status => card_status_raw ["card_status"],
2129    }
2130    Deposit {
2131        state_code => state_code_raw ["state_code"],
2132    }
2133    Withdrawal {
2134        state_code => state_code_raw ["state", "state_code"],
2135    }
2136);
2137
2138#[cfg(test)]
2139mod tests {
2140    use std::str::FromStr;
2141
2142    use time::macros::datetime;
2143
2144    use super::*;
2145
2146    fn dec(value: &str) -> Decimal {
2147        Decimal::from_str(value).expect("valid decimal literal")
2148    }
2149
2150    #[test]
2151    fn bank_card_decode_drops_sensitive_fields_and_placeholders() {
2152        let resp: BankCardsResponse = serde_json::from_str(
2153            r#"{"list":[{"id":12345,"bank_id":"7","bank":"HSBC","bank_en":"HSBC",
2154                "account":"012345678901","name":"CHAN TAI MAN","account_type":"saving",
2155                "country":"Hong Kong","status":1,"witness_state":"3","support_witness":true,
2156                "bind_state":1,"created_at":"1767196800","picture_urls":["k1"],
2157                "payee_street":"1 Road","auth_list":[
2158                    {"flow_id":"hk_edda","currency":"HKD","status":3,"message":"rejected",
2159                     "max_amount":"0","daily_max_count":0,"expiry_date":"0",
2160                     "long_term_valid":false,"is_support":1,"id":"0","created_at":"0"},
2161                    {"flow_id":"hk_fps","currency":"HKD","status":1,"max_amount":"50000",
2162                     "daily_max_count":"3","expiry_date":253402214400,"long_term_valid":true}
2163                ]}],"show_add_card_button":true}"#,
2164        )
2165        .expect("bank cards decode");
2166        let card = &resp.list[0];
2167        assert_eq!(card.id, "12345", "numeric id kept as text");
2168        assert_eq!(card.account, "012345678901", "account not masked");
2169        assert_eq!(card.status, BankCardStatus::UnderReview, "status code 1");
2170        assert_eq!(
2171            card.witness_state,
2172            BankCardWitnessState::Witnessed,
2173            "string code"
2174        );
2175        assert_eq!(card.bind_state, BankCardBindState::Bound, "bind code");
2176        assert!(card.support_witness, "bool");
2177        assert_eq!(
2178            card.created_at,
2179            Some(datetime!(2025-12-31 16:00 UTC)),
2180            "time"
2181        );
2182        let json = serde_json::to_string(card).expect("serialize");
2183        for key in ["CHAN TAI MAN", "picture_urls", "payee_street", "1 Road"] {
2184            assert!(!json.contains(key), "{key} must not be modelled");
2185        }
2186        let failed = &card.auth_list[0];
2187        assert_eq!(failed.status, AuthorizationStatus::Failed, "auth status");
2188        assert_eq!(failed.message, "rejected", "failure reason");
2189        assert!(failed.max_amount.is_none(), "\"0\" amount is unset");
2190        assert!(failed.daily_max_count.is_none(), "0 count is unset");
2191        assert!(failed.expiry_date.is_none(), "\"0\" expiry is unset");
2192        assert!(failed.is_support, "numeric bool");
2193        let fps = &card.auth_list[1];
2194        assert_eq!(fps.max_amount, Some(dec("50000")), "amount");
2195        assert_eq!(fps.daily_max_count, Some(3), "count");
2196        assert!(
2197            fps.expiry_date.is_none(),
2198            "9999-12-31 never-expires sentinel is None"
2199        );
2200        assert!(fps.long_term_valid, "long-term flag");
2201    }
2202
2203    #[test]
2204    fn edda_applications_accept_list_and_single_object() {
2205        let list: EddaApplicationsResponse = serde_json::from_str(
2206            r#"{"list":[{"id":"9","flow_id":"hk_sdda","name":"eDDA","currency":"HKD",
2207                "status":2,"message":"","created_at":1764064746,"updated_at":"0"},
2208                {"id":10,"status":42}]}"#,
2209        )
2210        .expect("list decodes");
2211        assert_eq!(list.0.len(), 2, "two applications");
2212        assert_eq!(list.0[0].status, AuthorizationStatus::Authorizing, "known");
2213        assert_eq!(list.0[0].flow_id, "hk_sdda", "flow");
2214        assert_eq!(list.0[0].currency, "HKD", "currency");
2215        assert!(list.0[0].created_at.is_some(), "filed time");
2216        assert!(list.0[0].updated_at.is_none(), "\"0\" placeholder");
2217        assert_eq!(
2218            list.0[1].status,
2219            AuthorizationStatus::Unknown,
2220            "unknown code"
2221        );
2222        assert_eq!(list.0[1].id, "10", "numeric id as text");
2223
2224        let single: EddaApplicationsResponse =
2225            serde_json::from_str(r#"{"id":"1","status":3,"message":"bank refused"}"#)
2226                .expect("single object decodes");
2227        assert_eq!(single.0.len(), 1, "one application");
2228        assert_eq!(single.0[0].message, "bank refused", "message");
2229
2230        let empty: EddaApplicationsResponse = serde_json::from_str("{}").expect("empty");
2231        assert!(empty.0.is_empty(), "no applications");
2232    }
2233
2234    #[test]
2235    fn stock_transfer_in_decode_handles_placeholders() {
2236        let resp: StockTransferInResponse = serde_json::from_str(
2237            r#"{"records":[{"id":"7053","order_id":"o1","market":"US","broker":"B",
2238                "broker_id":88,"broker_en":"B Ltd","code":"B01","account":"11222333444555",
2239                "name":"CHAN TAI MAN","contact_phone":"12345678","attachments":"[\"ai/x\"]",
2240                "state":"已提交","state_code":0,"app_state":"noticed","can_modify":1,
2241                "created_at":1764064746,"updated_at":"1764064746","process_at":0,
2242                "exec_at":"0","cash":[],
2243                "stocks":[{"code":"AAPL","name":"Apple","amount":"100","state":1,
2244                    "usi_attachments":["k"],"street_amount":"0","cost":"150.5"}]}],
2245                "total":"1"}"#,
2246        )
2247        .expect("transfer-in decodes");
2248        assert_eq!(resp.total, 1, "string total");
2249        let record = &resp.records[0];
2250        assert_eq!(record.broker_code, "B01", "broker code from `code`");
2251        assert_eq!(record.broker_id, "88", "numeric broker id as text");
2252        assert!(record.user_notified_broker(), "noticed app state");
2253        assert_eq!(record.state_code, StockTransferInState::Submitted, "state");
2254        assert!(record.can_modify, "can_modify");
2255        assert!(record.created_at.is_some(), "created");
2256        assert!(record.process_at.is_none(), "0 placeholder");
2257        assert!(record.exec_at.is_none(), "\"0\" placeholder");
2258        assert_eq!(
2259            record.stocks[0].state_code,
2260            TransferStockState::Succeeded,
2261            "stock"
2262        );
2263        assert_eq!(record.stocks[0].amount, Some(dec("100")), "quantity");
2264        let json = serde_json::to_string(record).expect("serialize");
2265        for key in ["CHAN TAI MAN", "12345678", "ai/x", "usi_attachments"] {
2266            assert!(!json.contains(key), "{key} must not be modelled");
2267        }
2268    }
2269
2270    #[test]
2271    fn stock_transfer_out_decode() {
2272        let resp: StockTransferOutResponse = serde_json::from_str(
2273            r#"{"records":[{"id":"1","name_en":"Futu Securities","state_code":7,
2274                "app_state":"default","broker_id":"12",
2275                "created_at":"2026-11-25T09:59:06Z","exec_at":"1970-01-01T00:00:00Z",
2276                "cancel_at":-2006054656,"refuse_at":1764064746,"stocks":null}]}"#,
2277        )
2278        .expect("transfer-out decodes");
2279        let record = &resp.records[0];
2280        assert_eq!(record.broker_en, "Futu Securities", "name_en is the broker");
2281        assert_eq!(record.state_code, StockTransferOutState::Rejected, "state");
2282        assert_eq!(record.broker_id, "12", "broker id");
2283        assert_eq!(record.app_state, "default", "app state");
2284        assert!(!record.user_notified_broker(), "not noticed");
2285        assert!(!record.cancellable(), "rejected cannot be cancelled");
2286        assert_eq!(
2287            record.created_at,
2288            Some(datetime!(2026-11-25 09:59:06 UTC)),
2289            "RFC 3339 time"
2290        );
2291        assert!(record.exec_at.is_none(), "1970 placeholder");
2292        assert!(record.cancel_at.is_none(), "negative placeholder");
2293        assert!(record.refuse_at.is_some(), "real time");
2294        assert!(record.stocks.is_empty(), "null stocks");
2295    }
2296
2297    #[test]
2298    fn reward_record_flattens_detail_and_drops_secrets() {
2299        let resp: RewardRecordsResponse = serde_json::from_str(
2300            r#"{"list":[
2301                {"reward_type":1,"prize":{"record_id":"r1","activity_title":"Open account",
2302                    "title":"Coffee","status":12,"deliver_status":11,"prize_type":0,
2303                    "send_time":1790000000,"coupon_secret":{"secret":"ABC-123"},
2304                    "coupon_secret_id":"s1","cash_card_code":"CODE9",
2305                    "express_info":{"phone":"12345678"},"addresses":[{"detail":"x"}]}},
2306                {"reward_type":0,"cash":{"amount":"38.5","currency":"HKD","status":"12",
2307                    "send_time":"0"}},
2308                {"card":{"title":"Commission card","card_type":"commission","status":8,
2309                    "card_status":"2"}},
2310                {"reward_type":3}
2311            ],"total":4}"#,
2312        )
2313        .expect("rewards decode");
2314        assert_eq!(resp.total, 4, "total");
2315        let prize = &resp.list[0];
2316        assert_eq!(prize.reward_type, RewardType::Gift, "gift");
2317        assert_eq!(prize.status, RewardStatus::Issued, "issued");
2318        assert_eq!(
2319            prize.deliver_status,
2320            RewardDeliverStatus::AddressFilled,
2321            "11"
2322        );
2323        assert_eq!(prize.prize_type, Some(0), "physical prize");
2324        assert!(prize.send_time.is_some(), "send time");
2325        let json = serde_json::to_string(prize).expect("serialize");
2326        for key in ["ABC-123", "CODE9", "12345678", "coupon_secret", "addresses"] {
2327            assert!(!json.contains(key), "{key} must not be modelled");
2328        }
2329        let cash = &resp.list[1];
2330        assert_eq!(cash.reward_type, RewardType::Cash, "cash");
2331        assert_eq!(cash.amount, Some(dec("38.5")), "amount");
2332        assert!(cash.send_time.is_none(), "\"0\" placeholder");
2333        assert_eq!(cash.deliver_status, RewardDeliverStatus::Unknown, "absent");
2334        assert!(cash.prize_type.is_none(), "no prize type");
2335        let card = &resp.list[2];
2336        assert_eq!(
2337            card.reward_type,
2338            RewardType::Coupon,
2339            "typed after the detail"
2340        );
2341        assert_eq!(card.status, RewardStatus::Unclaimed, "unclaimed");
2342        assert_eq!(
2343            card.card_status,
2344            CouponStatus::Expired,
2345            "coupon status enum"
2346        );
2347        assert_eq!(cash.card_status, CouponStatus::Unknown, "not a coupon");
2348        assert_eq!(resp.list[3].reward_type, RewardType::Task, "task kept");
2349    }
2350
2351    #[test]
2352    fn coupon_decode_handles_times() {
2353        let resp: CouponsResponse = serde_json::from_str(
2354            r#"{"top_list":null,"list":[{"card_id":"bd6b0000000000000000000000000000",
2355                "card_type":"commission","start_time":1750313704,"end_time":"8061747303",
2356                "card_status":4,"activate_time":"0","cover":"x","trade_sessions":["intraday","overnight"],
2357                "commission":{"markets":["US"],"bz_types":[0,"HkStockWarrant",3],"rebate_rate":"1",
2358                    "commission_expired_time":"0","unlimited":2,"usage_count":"2",
2359                    "amount_limit":"500","superposition":true},
2360                "cash":null,"quote":null,"stock":[]},
2361                {"card_id":"c2","card_status":2,"end_time":1798732800000,"commission":null}],
2362                "bottom_list":[],"total":"2","expired_count":5}"#,
2363        )
2364        .expect("coupons decode");
2365        assert!(resp.top_list.is_empty(), "null list");
2366        assert_eq!(resp.total, 2, "total");
2367        assert_eq!(resp.expired_count, 5, "expired count");
2368        let lifetime = &resp.list[0];
2369        assert_eq!(lifetime.card_status, CouponStatus::InUse, "status");
2370        assert!(lifetime.end_time.is_none(), "far future end time is None");
2371        assert!(lifetime.no_expiry, "far future means never expires");
2372        assert!(lifetime.activate_time.is_none(), "\"0\" placeholder");
2373        let commission = lifetime.commission.as_ref().expect("commission terms");
2374        assert_eq!(
2375            commission.bz_types,
2376            vec![
2377                CouponTargetType::Stock,
2378                CouponTargetType::HkWarrant,
2379                CouponTargetType::Etf
2380            ],
2381            "targets by code or name"
2382        );
2383        assert!(lifetime.cash.is_none(), "null detail is None");
2384        assert!(lifetime.stock.is_none(), "non-object detail is None");
2385        assert_eq!(
2386            lifetime.trade_sessions,
2387            vec!["intraday", "overnight"],
2388            "trade sessions"
2389        );
2390        assert_eq!(
2391            commission.unlimited,
2392            CommissionUnlimitedType::Lifetime,
2393            "unlimited code"
2394        );
2395        assert_eq!(commission.usage_count, 2, "usage count");
2396        assert_eq!(commission.amount_limit, 500, "amount limit");
2397        assert!(commission.superposition, "superposition");
2398        assert!(
2399            commission.commission_expired_time.is_none(),
2400            "nested placeholder"
2401        );
2402        let ms = &resp.list[1];
2403        assert_eq!(
2404            ms.end_time,
2405            Some(datetime!(2026-12-31 16:00 UTC)),
2406            "milliseconds converted"
2407        );
2408        assert!(!ms.no_expiry, "a real end time expires");
2409        assert!(ms.commission.is_none(), "no commission terms");
2410        let json = serde_json::to_value(lifetime).expect("serialize");
2411        assert_eq!(json["no_expiry"], true, "no_expiry serialized");
2412        let back: Coupon = serde_json::from_value(json).expect("round trip");
2413        assert!(back.no_expiry, "no_expiry survives a round trip");
2414        assert_eq!(
2415            back.commission.map(|c| c.unlimited),
2416            Some(CommissionUnlimitedType::Lifetime),
2417            "commission survives a round trip"
2418        );
2419    }
2420
2421    #[test]
2422    fn coupon_type_terms_decode() {
2423        // Synthetic values in the server's wire format: int64 as strings,
2424        // enums as numbers or names, "0" for unset times.
2425        let coupon: Coupon = serde_json::from_str(
2426            r#"{"card_id":"c","card_type":"x","subscription_id":"",
2427                "ai_benefit":{"benefit_days":30,"benefit_start":"1767196800",
2428                    "benefit_end":"0","benefit_tag":"tag"},
2429                "cash":{"receive_duration":"7"},
2430                "coffee_coupon":{"coupon_channel":"chan","coupon_id":"","coupon_no":"N1",
2431                    "is_available_all_store":true,"period_type":"day","settled_store_id":"0",
2432                    "store_id_list":["11",12],"store_list":[{"store_id":"11","store_name":"S"}],
2433                    "threshold":"2","use_limit":"total"},
2434                "crypto":{"fallback":{"enabled":true,"counter_id":"C1"},
2435                    "optional_counters":[{"counter_id":"C2"}]},
2436                "finance_interest":{"discount_mode":1,"discount_rate":"0.5","superposition":false},
2437                "fund_deduct":{"max_risk_level":"3","min_order_amount":"100",
2438                    "order_types":["buy"],"underlying_type":"fund","underlying_values":["F1"],
2439                    "underlying_names":["Fund"]},
2440                "fund_interest":{},
2441                "fundamental":{"investor_type":"INVESTOR_TYPE_PROFESSIONAL","markets":["US"]},
2442                "ipo":{"subscription_id":"S1"},
2443                "ipo_commission":{"bz_types":[1,"CashIPO",0],"counter_id":"C3",
2444                    "counter_name":"IPO","financing_limit":"10"},
2445                "ipo_interest":{"discount_rate":"0.8"},
2446                "platform_fee_deduct":{"bz_types":["UsStockOptions"],"markets":["US"],
2447                    "usage_count":"1","lave_usage_count":"4","superposition":true},
2448                "quote":{"current_end_time":"1767196800","investor_type":1,
2449                    "member_investor_type":"2","quote_duration":"30","quote_tags":["L2"],
2450                    "manual_activate":true},
2451                "stock":{"amount":12.5,"counter_id":"C4","redemption_type":"shares_number",
2452                    "send_way":"account_transfer","optional_counters":[{"counter_id":"C5",
2453                    "shares":"3"}],"fallback":{"enabled":true,"type":"cash","shares":"1"}},
2454                "stock_fragment":{"amounts":{"a":"1"},"market":"US","markets":["US"],
2455                    "underlying_type":"ETF"}}"#,
2456        )
2457        .expect("coupon decodes");
2458        let ai = coupon.ai_benefit.as_ref().expect("ai benefit");
2459        assert_eq!(ai.benefit_days, 30, "days");
2460        assert!(
2461            ai.benefit_start.is_some() && ai.benefit_end.is_none(),
2462            "times"
2463        );
2464        assert_eq!(coupon.cash.as_ref().map(|c| c.receive_duration), Some(7));
2465        let coffee = coupon.coffee_coupon.as_ref().expect("coffee");
2466        assert_eq!(coffee.store_id_list, vec![11, 12], "store ids");
2467        assert_eq!(coffee.store_list[0].store_id, 11, "store");
2468        assert_eq!(coffee.settled_store_id, 0, "unset store");
2469        let crypto = coupon.crypto.as_ref().expect("crypto");
2470        assert!(crypto.fallback.enabled, "fallback");
2471        assert_eq!(crypto.optional_counters[0].counter_id, "C2", "counters");
2472        let finance = coupon.finance_interest.as_ref().expect("finance");
2473        assert_eq!(finance.discount_rate, Some(dec("0.5")), "rate");
2474        assert_eq!(
2475            coupon.fund_deduct.as_ref().map(|f| f.max_risk_level),
2476            Some(3),
2477            "risk level"
2478        );
2479        assert_eq!(
2480            coupon.fundamental.as_ref().map(|q| q.investor_type),
2481            Some(QuoteInvestorType::Professional),
2482            "investor type by name"
2483        );
2484        assert_eq!(
2485            coupon.ipo_commission.as_ref().map(|i| i.bz_types.clone()),
2486            Some(vec![
2487                IpoCouponTargetType::Financing,
2488                IpoCouponTargetType::Cash,
2489                IpoCouponTargetType::Unknown
2490            ]),
2491            "IPO types"
2492        );
2493        assert_eq!(
2494            coupon
2495                .platform_fee_deduct
2496                .as_ref()
2497                .map(|p| p.bz_types.clone()),
2498            Some(vec![CouponTargetType::UsOption]),
2499            "platform fee types"
2500        );
2501        let quote = coupon.quote.as_ref().expect("quote");
2502        assert!(quote.current_end_time.is_some(), "time");
2503        assert_eq!(quote.investor_type, QuoteInvestorType::NonProfessional);
2504        assert_eq!(quote.member_investor_type, 2, "member type");
2505        let stock = coupon.stock.as_ref().expect("stock");
2506        assert_eq!(stock.amount, Some(dec("12.5")), "amount");
2507        assert_eq!(stock.fallback.fallback_type, "cash", "fallback type");
2508        assert_eq!(stock.optional_counters[0].shares, "3", "shares");
2509        let fragment = coupon.stock_fragment.as_ref().expect("fragment");
2510        assert_eq!(fragment.underlying_type, CouponTargetType::Etf, "by name");
2511        assert_eq!(fragment.amounts.get("a").map(String::as_str), Some("1"));
2512        let back: Coupon =
2513            serde_json::from_value(serde_json::to_value(&coupon).expect("serialize"))
2514                .expect("round trip");
2515        assert_eq!(
2516            back.stock.map(|s| s.fallback.fallback_type),
2517            Some("cash".to_string()),
2518            "renamed field survives a round trip"
2519        );
2520    }
2521
2522    #[test]
2523    fn deposit_and_withdrawal_decode() {
2524        let deposits: DepositsResponse = serde_json::from_str(
2525            r#"{"items":[{"id":1,"created_at":1764064746,"currency":"HKD","amount":"1,000.00",
2526                "receivable_amount":"0","state":"处理中","state_code":0,"can_cancel":true,
2527                "vouchers":[{"key":"k","img_url":"https://x/receipt.png"}]}],"total":20}"#,
2528        )
2529        .expect("deposits decode");
2530        let deposit = &deposits.items[0];
2531        assert_eq!(deposit.amount, Some(dec("1000.00")), "thousands separator");
2532        assert_eq!(
2533            deposit.receivable_amount,
2534            Some(dec("0")),
2535            "0 means not received"
2536        );
2537        assert_eq!(deposit.state_code, DepositState::Processing, "state");
2538        let json = serde_json::to_string(deposit).expect("serialize");
2539        assert!(
2540            !json.contains("receipt.png"),
2541            "vouchers must not be modelled"
2542        );
2543        assert_eq!(deposit.voucher_count, 1, "receipts counted");
2544        let back: Deposit = serde_json::from_str(&json).expect("round trip");
2545        assert_eq!(back.voucher_count, 1, "voucher_count survives a round trip");
2546
2547        let withdrawals: WithdrawalsResponse = serde_json::from_str(
2548            r#"{"list":[{"id":"w1","state":15,"state_description":"待确认","amount":"100","fee":"0",
2549                "bank_account":"012345678901","display_bank_account":"尾号 8901"}],"total":1}"#,
2550        )
2551        .expect("withdrawals decode");
2552        let withdrawal = &withdrawals.list[0];
2553        assert_eq!(
2554            withdrawal.state_code,
2555            WithdrawalState::AwaitingConfirmation,
2556            "state 15"
2557        );
2558        assert_eq!(withdrawal.state_description, "待确认", "display text");
2559        let json = serde_json::to_value(withdrawal).expect("serialize");
2560        assert_eq!(json["state_code"], 15, "serialized as state_code");
2561        let back: Withdrawal = serde_json::from_value(json).expect("round trip");
2562        assert_eq!(
2563            back.state_code,
2564            WithdrawalState::AwaitingConfirmation,
2565            "state_code survives a round trip"
2566        );
2567        assert_eq!(withdrawal.bank_account, "012345678901", "not masked");
2568        assert_eq!(withdrawal.fee, Some(dec("0")), "zero fee kept");
2569    }
2570
2571    #[test]
2572    fn raw_codes_keep_undocumented_values() {
2573        let withdrawals: WithdrawalsResponse = serde_json::from_str(
2574            r#"{"list":[{"id":"w1","state":"42"},{"id":"w2","state":4},{"id":"w3"}]}"#,
2575        )
2576        .expect("withdrawals decode");
2577        assert_eq!(
2578            withdrawals.list[0].state_code,
2579            WithdrawalState::Unknown,
2580            "undocumented"
2581        );
2582        assert_eq!(withdrawals.list[0].state_code_raw, Some(42), "raw kept");
2583        assert_eq!(withdrawals.list[1].state_code_raw, Some(4), "known code");
2584        assert_eq!(withdrawals.list[2].state_code_raw, None, "absent");
2585        let json = serde_json::to_value(&withdrawals.list[0]).expect("serialize");
2586        let back: Withdrawal = serde_json::from_value(json).expect("round trip");
2587        assert_eq!(back.state_code_raw, Some(42), "raw survives a round trip");
2588
2589        let cards: BankCardsResponse = serde_json::from_str(
2590            r#"{"list":[{"id":1,"status":9,"witness_state":"2","bind_state":null,
2591                "auth_list":[{"status":7}]}]}"#,
2592        )
2593        .expect("cards decode");
2594        let card = &cards.list[0];
2595        assert_eq!(card.status, BankCardStatus::Unknown, "undocumented");
2596        assert_eq!(card.status_raw, Some(9), "card status raw");
2597        assert_eq!(card.witness_state_raw, Some(2), "string code");
2598        assert_eq!(card.bind_state_raw, None, "null is absent");
2599        assert_eq!(card.auth_list[0].status_raw, Some(7), "auth raw");
2600
2601        let coupon: Coupon = serde_json::from_str(
2602            r#"{"card_id":"c","card_status":9,
2603                "commission":{"bz_types":[0,"LOF",9,"Other"],"unlimited":"ByRatePer"},
2604                "stock_fragment":{"underlying_type":"12"},
2605                "quote":{"investor_type":5}}"#,
2606        )
2607        .expect("coupon decodes");
2608        assert_eq!(coupon.card_status_raw, Some(9), "coupon status raw");
2609        let commission = coupon.commission.expect("commission");
2610        assert_eq!(
2611            commission.bz_types_raw,
2612            vec![0, 4, 9],
2613            "names mapped, unknown name left out"
2614        );
2615        assert_eq!(commission.unlimited_raw, Some(7), "name mapped to its code");
2616        assert_eq!(
2617            coupon.stock_fragment.and_then(|f| f.underlying_type_raw),
2618            Some(12),
2619            "raw underlying type"
2620        );
2621        assert_eq!(
2622            coupon.quote.and_then(|q| q.investor_type_raw),
2623            Some(5),
2624            "raw investor type"
2625        );
2626
2627        let transfers: StockTransferInResponse =
2628            serde_json::from_str(r#"{"records":[{"state_code":11,"stocks":[{"state":"6"}]}]}"#)
2629                .expect("transfers decode");
2630        assert_eq!(transfers.records[0].state_code_raw, Some(11), "record");
2631        assert_eq!(
2632            transfers.records[0].stocks[0].state_code_raw,
2633            Some(6),
2634            "stock"
2635        );
2636        let deposit: Deposit = serde_json::from_str(r#"{"state_code":8}"#).expect("deposit");
2637        assert_eq!(deposit.state_code_raw, Some(8), "deposit");
2638        let app: EddaApplication = serde_json::from_str(r#"{"status":5}"#).expect("edda");
2639        assert_eq!(app.status_raw, Some(5), "edda");
2640    }
2641
2642    #[test]
2643    fn reward_raw_codes_and_detail_kind() {
2644        let resp: RewardRecordsResponse = serde_json::from_str(
2645            r#"{"list":[
2646                {"reward_type":1,"prize":{"status":12,"deliver_status":11,"card_status":"9"}},
2647                {"reward_type":7,"cash":{"status":99}},
2648                {"card":{"status":12}},
2649                {"reward_type":1,"cash":{"status":12},"prize":{"status":12}},
2650                {"reward_type":3,"cash":[],"card":"x"}
2651            ]}"#,
2652        )
2653        .expect("rewards decode");
2654        let prize = &resp.list[0];
2655        assert_eq!(
2656            prize.deliver_status,
2657            RewardDeliverStatus::AddressFilled,
2658            "11 reads as address filled"
2659        );
2660        assert_eq!(prize.deliver_status_raw, Some(11), "and keeps its own code");
2661        assert_eq!(prize.card_status_raw, Some(9), "card status raw");
2662        let unknown = &resp.list[1];
2663        assert_eq!(
2664            unknown.reward_type,
2665            RewardType::Cash,
2666            "named after the detail"
2667        );
2668        assert_eq!(unknown.reward_type_raw, Some(7), "raw type kept");
2669        assert_eq!(unknown.status, RewardStatus::Unknown, "undocumented status");
2670        assert_eq!(unknown.status_raw, Some(99), "raw status kept");
2671        assert_eq!(resp.list[2].reward_type_raw, None, "no type sent");
2672        assert_eq!(resp.list[2].deliver_status_raw, None, "no delivery sent");
2673        assert_eq!(
2674            resp.list[3].reward_type,
2675            RewardType::Cash,
2676            "first detail object wins, as in the app"
2677        );
2678        assert_eq!(
2679            resp.list[4].reward_type,
2680            RewardType::Task,
2681            "non-object details skipped"
2682        );
2683    }
2684
2685    #[test]
2686    fn enum_lists_and_raw_codes_stay_aligned() {
2687        let commission: CouponCommission = serde_json::from_str(
2688            r#"{"bz_types":[0,null,"x",{"a":1},"LOF",9,"3.0",1.5],"unlimited":6.0}"#,
2689        )
2690        .expect("commission decodes");
2691        assert_eq!(
2692            commission.bz_types,
2693            vec![
2694                CouponTargetType::Stock,
2695                CouponTargetType::Lof,
2696                CouponTargetType::Unknown,
2697                CouponTargetType::Etf
2698            ],
2699            "undecodable elements skipped, unknown code kept as Unknown"
2700        );
2701        assert_eq!(commission.bz_types_raw, vec![0, 4, 9, 3], "same order");
2702        assert_eq!(
2703            commission.bz_types.len(),
2704            commission.bz_types_raw.len(),
2705            "same length"
2706        );
2707        assert_eq!(
2708            commission.unlimited,
2709            CommissionUnlimitedType::ByAmountPer,
2710            "integral float accepted"
2711        );
2712        assert_eq!(commission.unlimited_raw, Some(6), "integral float raw");
2713        let deposit: Deposit =
2714            serde_json::from_str(r#"{"state_code":"4.0","sub_state_code":2.0}"#).expect("deposit");
2715        assert_eq!(
2716            deposit.state_code,
2717            DepositState::Invalidated,
2718            "\"4.0\" is 4"
2719        );
2720        assert_eq!(deposit.state_code_raw, Some(4), "raw 4");
2721        assert_eq!(deposit.sub_state_code, 2, "integral float int");
2722        let fractional: Deposit = serde_json::from_str(r#"{"state_code":4.5}"#).expect("deposit");
2723        assert_eq!(
2724            fractional.state_code,
2725            DepositState::Unknown,
2726            "fractional rejected"
2727        );
2728        assert_eq!(fractional.state_code_raw, None, "not a code");
2729    }
2730
2731    #[test]
2732    fn coupon_lists_skip_malformed_elements() {
2733        let coupon: Coupon = serde_json::from_str(
2734            r#"{"coffee_coupon":{"store_list":[{"store_id":"1"},"x",null,2]},
2735                "crypto":{"fallback":"x","optional_counters":[{"counter_id":"C"},[]]},
2736                "stock":{"fallback":[1],"optional_counters":{"a":1}}}"#,
2737        )
2738        .expect("malformed nested elements do not fail the coupon");
2739        assert_eq!(
2740            coupon.coffee_coupon.map(|c| c.store_list.len()),
2741            Some(1),
2742            "non-object stores skipped"
2743        );
2744        let crypto = coupon.crypto.expect("crypto");
2745        assert!(
2746            !crypto.fallback.enabled,
2747            "malformed fallback is the default"
2748        );
2749        assert_eq!(
2750            crypto.optional_counters.len(),
2751            1,
2752            "non-object counter skipped"
2753        );
2754        let stock = coupon.stock.expect("stock");
2755        assert!(
2756            stock.optional_counters.is_empty(),
2757            "non-array counters are empty"
2758        );
2759    }
2760
2761    #[test]
2762    fn go_parity_fields_decode() {
2763        let cards: BankCardsResponse = serde_json::from_str(
2764            r#"{"list":[{"id":"1","country":"Hong Kong","country_display":"HK"}]}"#,
2765        )
2766        .expect("cards decode");
2767        assert_eq!(cards.list[0].country_display, "HK", "country display");
2768        let transfers: StockTransferInResponse = serde_json::from_str(
2769            r#"{"records":[{"stocks":[{"code":"X","street_amount":"100","nominee_amount":"0",
2770                "own_amount":"25.5","certificate_count":"3"},{"code":"Y"}]}]}"#,
2771        )
2772        .expect("transfers decode");
2773        let stock = &transfers.records[0].stocks[0];
2774        assert_eq!(stock.street_amount, Some(dec("100")), "street");
2775        assert_eq!(stock.nominee_amount, Some(dec("0")), "nominee zero kept");
2776        assert_eq!(stock.own_amount, Some(dec("25.5")), "own");
2777        assert_eq!(stock.certificate_count, 3, "certificates");
2778        let bare = &transfers.records[0].stocks[1];
2779        assert!(
2780            bare.street_amount.is_none() && bare.certificate_count == 0,
2781            "absent"
2782        );
2783        let rewards: RewardRecordsResponse = serde_json::from_str(
2784            r#"{"list":[{"cash":{"title":"a"}},{"card":{"title":"b"}},{"prize":{"title":"c"}},
2785                {"reward_type":3}]}"#,
2786        )
2787        .expect("rewards decode");
2788        let kinds: Vec<RewardDetailKind> = rewards.list.iter().map(|r| r.detail_kind).collect();
2789        assert_eq!(
2790            kinds,
2791            vec![
2792                RewardDetailKind::Cash,
2793                RewardDetailKind::Card,
2794                RewardDetailKind::Prize,
2795                RewardDetailKind::None
2796            ],
2797            "detail kinds"
2798        );
2799        assert_eq!(
2800            rewards.list[3].reward_type,
2801            RewardType::Task,
2802            "type from the code"
2803        );
2804        let withdrawals: WithdrawalsResponse =
2805            serde_json::from_str(r#"{"list":[],"total":0,"has_more":true}"#).expect("decode");
2806        assert!(withdrawals.has_more, "has_more round trips");
2807    }
2808
2809    #[test]
2810    fn enums_round_trip_codes() {
2811        assert_eq!(i32::from(DepositState::Rejected), 5, "code");
2812        assert_eq!(DepositState::from(99), DepositState::Unknown, "fallback");
2813        assert_eq!(
2814            serde_json::to_string(&WithdrawalState::Remitted).expect("serialize"),
2815            "4",
2816            "serialized as the code"
2817        );
2818        let state: CouponStatus = serde_json::from_str("\"x\"").expect("lenient");
2819        assert_eq!(state, CouponStatus::Unknown, "non-numeric is unknown");
2820    }
2821}