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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
10pub struct GetStatementListResponse {
11 pub list: Vec<StatementItem>,
13}
14
15#[derive(Debug, Clone, Default, Serialize, Deserialize)]
17pub struct StatementItem {
18 pub dt: i32,
20 pub file_key: String,
23}
24
25#[derive(Debug, Clone, Default, Serialize, Deserialize)]
27pub struct GetStatementResponse {
28 pub url: String,
30}
31
32macro_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#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
60#[repr(i32)]
61pub enum BankCardStatus {
62 #[default]
64 Unknown = -1,
65 Unverified = 0,
67 UnderReview = 1,
69 Verified = 2,
71}
72
73#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
75#[repr(i32)]
76pub enum BankCardWitnessState {
77 #[default]
79 Unknown = -1,
80 NotRequired = 1,
82 Pending = 2,
84 Witnessed = 3,
86}
87
88#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
90#[repr(i32)]
91pub enum BankCardBindState {
92 #[default]
94 Unknown = -1,
95 Binding = 0,
97 Bound = 1,
99 Failed = 2,
101}
102
103#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
106#[repr(i32)]
107pub enum AuthorizationStatus {
108 #[default]
110 Unknown = -1,
111 Unauthorized = 0,
113 Authorized = 1,
115 Authorizing = 2,
117 Failed = 3,
119}
120
121#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
123#[repr(i32)]
124pub enum StockTransferInState {
125 #[default]
127 Unknown = -1,
128 Submitted = 0,
130 Cancelled = 1,
132 Completed = 3,
134 Processing = 5,
136 PartiallyCompleted = 7,
138 Failed = 8,
140}
141
142#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
145#[repr(i32)]
146pub enum StockTransferOutState {
147 #[default]
149 Unknown = -1,
150 Submitted = 0,
153 Processing = 1,
155 Executing = 2,
157 Completed = 3,
159 Cancelled = 4,
161 PartiallyCompleted = 5,
163 Failed = 6,
165 Rejected = 7,
167}
168
169#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
171#[repr(i32)]
172pub enum TransferStockState {
173 #[default]
175 Unknown = -1,
176 Processing = 0,
178 Succeeded = 1,
180 Failed = 2,
182}
183
184#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
186#[repr(i32)]
187pub enum RewardType {
188 #[default]
190 Unknown = -1,
191 Cash = 0,
193 Gift = 1,
195 Coupon = 2,
197 Task = 3,
199}
200
201#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, Serialize, Deserialize)]
203#[serde(rename_all = "snake_case")]
204pub enum RewardDetailKind {
205 #[default]
208 None,
209 Cash,
211 Card,
213 Prize,
215}
216
217#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
219#[repr(i32)]
220pub enum RewardStatus {
221 #[default]
223 Unknown = -1,
224 Upcoming = 0,
226 Cancelled = 1,
228 ExitedActivity = 2,
230 Unclaimed = 8,
232 Issuing = 10,
234 Issued = 12,
236 Failed = 13,
238 Exchanged = 16,
240 Expired = 17,
242 Refunded = 18,
244}
245
246#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
249#[repr(i32)]
250pub enum RewardDeliverStatus {
251 #[default]
253 Unknown = -1,
254 NotActivated = 0,
256 ActivatedOrShipping = 1,
258 Consumed = 2,
260 EVoucherActivating = 5,
262 EVoucherExpired = 6,
264 EVoucherInvalid = 7,
266 AddressMissing = 8,
268 #[num_enum(alternatives = [11])]
270 AddressFilled = 9,
271 Shipping = 10,
273}
274
275#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
277#[repr(i32)]
278pub enum CouponStatus {
279 #[default]
281 Unknown = -1,
282 Unused = 0,
284 Used = 1,
286 Expired = 2,
288 Redeeming = 3,
290 InUse = 4,
292 Processing = 5,
294}
295
296#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
298#[repr(i32)]
299pub enum DepositState {
300 #[default]
302 Unknown = -1,
303 Processing = 0,
305 Credited = 1,
307 Failed = 2,
309 Cancelled = 3,
311 Invalidated = 4,
313 Rejected = 5,
315}
316
317#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
319#[repr(i32)]
320pub enum WithdrawalState {
321 #[default]
323 Unknown = -1,
324 Submitted = 0,
326 Processing = 1,
328 Rejected = 2,
330 Cancelled = 3,
332 Remitted = 4,
334 Failed = 5,
336 Refunded = 6,
338 ApprovedAwaitingPayout = 7,
340 LargeAmountReview = 8,
342 ChangePendingApproval = 9,
344 DeletionPendingApproval = 10,
346 Deleted = 11,
348 RejectionPendingApproval = 12,
350 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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
373#[serde(default, remote = "Self")]
374pub struct BankCardAuthorization {
375 #[serde(deserialize_with = "serde_utils::string_lenient")]
378 pub flow_id: String,
379 #[serde(deserialize_with = "serde_utils::string_lenient")]
381 pub name: String,
382 #[serde(deserialize_with = "serde_utils::string_lenient")]
384 pub currency: String,
385 pub status: AuthorizationStatus,
387 pub status_raw: Option<i32>,
391 #[serde(deserialize_with = "serde_utils::string_lenient")]
393 pub message: String,
394 #[serde(deserialize_with = "serde_utils::bool_lenient")]
396 pub is_support: bool,
397 #[serde(with = "serde_utils::decimal_opt_lenient_0_is_none")]
399 pub max_amount: Option<Decimal>,
400 #[serde(deserialize_with = "serde_utils::bool_lenient")]
402 pub max_amount_unlimited: bool,
403 #[serde(with = "serde_utils::int64_opt_lenient_0_is_none")]
405 pub daily_max_count: Option<i64>,
406 #[serde(deserialize_with = "serde_utils::bool_lenient")]
408 pub daily_max_count_unlimited: bool,
409 #[serde(with = "serde_utils::account_time_opt")]
414 pub expiry_date: Option<OffsetDateTime>,
415 #[serde(deserialize_with = "serde_utils::bool_lenient")]
417 pub long_term_valid: bool,
418 #[serde(deserialize_with = "serde_utils::bool_lenient")]
420 pub doc_reviewing: bool,
421 #[serde(deserialize_with = "serde_utils::bool_lenient")]
423 pub no_prior_deposit_reviewing: bool,
424}
425
426#[derive(Debug, Clone, Default, Serialize, Deserialize)]
432#[serde(default, remote = "Self")]
433pub struct BankCard {
434 #[serde(deserialize_with = "serde_utils::string_lenient")]
436 pub id: String,
437 #[serde(deserialize_with = "serde_utils::string_lenient")]
439 pub bank_id: String,
440 #[serde(deserialize_with = "serde_utils::string_lenient")]
442 pub bank: String,
443 #[serde(deserialize_with = "serde_utils::string_lenient")]
445 pub bank_en: String,
446 #[serde(deserialize_with = "serde_utils::string_lenient")]
448 pub bank_code: String,
449 #[serde(deserialize_with = "serde_utils::string_lenient")]
451 pub account: String,
452 #[serde(deserialize_with = "serde_utils::string_lenient")]
454 pub account_type: String,
455 #[serde(deserialize_with = "serde_utils::string_lenient")]
457 pub country: String,
458 #[serde(deserialize_with = "serde_utils::string_lenient")]
460 pub country_display: String,
461 #[serde(deserialize_with = "serde_utils::string_lenient")]
463 pub region: String,
464 #[serde(deserialize_with = "serde_utils::string_lenient")]
466 pub region_name: String,
467 #[serde(deserialize_with = "serde_utils::string_lenient")]
469 pub swift_code: String,
470 #[serde(deserialize_with = "serde_utils::string_lenient")]
472 pub remark: String,
473 pub status: BankCardStatus,
475 pub status_raw: Option<i32>,
479 pub witness_state: BankCardWitnessState,
481 pub witness_state_raw: Option<i32>,
485 #[serde(deserialize_with = "serde_utils::bool_lenient")]
487 pub support_witness: bool,
488 pub bind_state: BankCardBindState,
490 pub bind_state_raw: Option<i32>,
494 #[serde(deserialize_with = "serde_utils::string_lenient")]
496 pub bind_tip: String,
497 #[serde(deserialize_with = "serde_utils::string_lenient")]
499 pub withdraw_fee: String,
500 #[serde(with = "serde_utils::account_time_opt")]
502 pub created_at: Option<OffsetDateTime>,
503 #[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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
516#[serde(default, remote = "Self")]
517pub struct EddaApplication {
518 #[serde(deserialize_with = "serde_utils::string_lenient")]
520 pub id: String,
521 #[serde(deserialize_with = "serde_utils::string_lenient")]
524 pub flow_id: String,
525 #[serde(deserialize_with = "serde_utils::string_lenient")]
527 pub name: String,
528 #[serde(deserialize_with = "serde_utils::string_lenient")]
530 pub currency: String,
531 pub status: AuthorizationStatus,
533 pub status_raw: Option<i32>,
537 #[serde(deserialize_with = "serde_utils::string_lenient")]
539 pub message: String,
540 #[serde(with = "serde_utils::account_time_opt")]
542 pub created_at: Option<OffsetDateTime>,
543 #[serde(with = "serde_utils::account_time_opt")]
545 pub updated_at: Option<OffsetDateTime>,
546}
547
548#[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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
578#[serde(default, remote = "Self")]
579pub struct TransferStock {
580 #[serde(deserialize_with = "serde_utils::string_lenient")]
582 pub code: String,
583 #[serde(deserialize_with = "serde_utils::string_lenient")]
585 pub name: String,
586 #[serde(deserialize_with = "serde_utils::string_lenient")]
588 pub name_en: String,
589 #[serde(deserialize_with = "serde_utils::string_lenient")]
591 pub market: String,
592 #[serde(deserialize_with = "serde_utils::string_lenient")]
594 pub counter_id: String,
595 #[serde(with = "serde_utils::decimal_opt_lenient")]
597 pub amount: Option<Decimal>,
598 #[serde(deserialize_with = "serde_utils::string_lenient")]
600 pub currency: String,
601 #[serde(with = "serde_utils::decimal_opt_lenient")]
603 pub cost: Option<Decimal>,
604 #[serde(rename(deserialize = "state"), alias = "state_code")]
606 pub state_code: TransferStockState,
607 pub state_code_raw: Option<i32>,
611 #[serde(with = "serde_utils::decimal_opt_lenient")]
613 pub street_amount: Option<Decimal>,
614 #[serde(with = "serde_utils::decimal_opt_lenient")]
616 pub nominee_amount: Option<Decimal>,
617 #[serde(with = "serde_utils::decimal_opt_lenient")]
619 pub own_amount: Option<Decimal>,
620 #[serde(deserialize_with = "serde_utils::account_int64")]
622 pub certificate_count: i64,
623 #[serde(deserialize_with = "serde_utils::string_lenient")]
625 pub position_side: String,
626}
627
628pub const APP_STATE_NOTICED: &str = "noticed";
632
633#[derive(Debug, Clone, Default, Serialize, Deserialize)]
638#[serde(default, remote = "Self")]
639pub struct StockTransferIn {
640 #[serde(deserialize_with = "serde_utils::string_lenient")]
642 pub id: String,
643 #[serde(deserialize_with = "serde_utils::string_lenient")]
645 pub order_id: String,
646 #[serde(deserialize_with = "serde_utils::string_lenient")]
648 pub market: String,
649 #[serde(deserialize_with = "serde_utils::string_lenient")]
651 pub broker: String,
652 #[serde(deserialize_with = "serde_utils::string_lenient")]
654 pub broker_id: String,
655 #[serde(deserialize_with = "serde_utils::string_lenient")]
657 pub broker_en: String,
658 #[serde(rename = "code", deserialize_with = "serde_utils::string_lenient")]
660 pub broker_code: String,
661 #[serde(deserialize_with = "serde_utils::string_lenient")]
664 pub account: String,
665 #[serde(deserialize_with = "serde_utils::string_lenient")]
667 pub state: String,
668 pub state_code: StockTransferInState,
670 pub state_code_raw: Option<i32>,
674 #[serde(deserialize_with = "serde_utils::string_lenient")]
679 pub app_state: String,
680 #[serde(deserialize_with = "serde_utils::bool_lenient")]
682 pub can_modify: bool,
683 #[serde(with = "serde_utils::account_time_opt")]
685 pub created_at: Option<OffsetDateTime>,
686 #[serde(with = "serde_utils::account_time_opt")]
688 pub updated_at: Option<OffsetDateTime>,
689 #[serde(with = "serde_utils::account_time_opt")]
691 pub process_at: Option<OffsetDateTime>,
692 #[serde(with = "serde_utils::account_time_opt")]
694 pub exec_at: Option<OffsetDateTime>,
695 #[serde(deserialize_with = "serde_utils::string_lenient")]
697 pub remark: String,
698 #[serde(deserialize_with = "serde_utils::string_lenient")]
700 pub reason: String,
701 #[serde(deserialize_with = "serde_utils::null_as_default")]
703 pub stocks: Vec<TransferStock>,
704}
705
706#[derive(Debug, Clone, Default, Serialize, Deserialize)]
708#[serde(default)]
709pub struct StockTransferInResponse {
710 #[serde(deserialize_with = "serde_utils::null_as_default")]
712 pub records: Vec<StockTransferIn>,
713 #[serde(deserialize_with = "serde_utils::account_int64")]
715 pub total: i64,
716}
717
718#[derive(Debug, Clone, Default, Serialize, Deserialize)]
723#[serde(default, remote = "Self")]
724pub struct StockTransferOut {
725 #[serde(deserialize_with = "serde_utils::string_lenient")]
727 pub id: String,
728 #[serde(deserialize_with = "serde_utils::string_lenient")]
730 pub order_id: String,
731 #[serde(deserialize_with = "serde_utils::string_lenient")]
733 pub market: String,
734 #[serde(deserialize_with = "serde_utils::string_lenient")]
736 pub broker: String,
737 #[serde(deserialize_with = "serde_utils::string_lenient")]
739 pub broker_id: String,
740 #[serde(rename = "name_en", deserialize_with = "serde_utils::string_lenient")]
742 pub broker_en: String,
743 #[serde(rename = "code", deserialize_with = "serde_utils::string_lenient")]
745 pub broker_code: String,
746 #[serde(deserialize_with = "serde_utils::string_lenient")]
749 pub account: String,
750 #[serde(deserialize_with = "serde_utils::string_lenient")]
752 pub state: String,
753 pub state_code: StockTransferOutState,
757 pub state_code_raw: Option<i32>,
761 #[serde(deserialize_with = "serde_utils::string_lenient")]
766 pub app_state: String,
767 #[serde(with = "serde_utils::account_time_opt")]
769 pub created_at: Option<OffsetDateTime>,
770 #[serde(with = "serde_utils::account_time_opt")]
772 pub updated_at: Option<OffsetDateTime>,
773 #[serde(with = "serde_utils::account_time_opt")]
775 pub process_at: Option<OffsetDateTime>,
776 #[serde(with = "serde_utils::account_time_opt")]
778 pub exec_at: Option<OffsetDateTime>,
779 #[serde(with = "serde_utils::account_time_opt")]
781 pub agree_at: Option<OffsetDateTime>,
782 #[serde(with = "serde_utils::account_time_opt")]
784 pub refuse_at: Option<OffsetDateTime>,
785 #[serde(with = "serde_utils::account_time_opt")]
787 pub cancel_at: Option<OffsetDateTime>,
788 #[serde(deserialize_with = "serde_utils::string_lenient")]
790 pub remark: String,
791 #[serde(deserialize_with = "serde_utils::string_lenient")]
793 pub reason: String,
794 #[serde(deserialize_with = "serde_utils::null_as_default")]
796 pub stocks: Vec<TransferStock>,
797}
798
799impl StockTransferIn {
800 #[inline]
803 pub fn user_notified_broker(&self) -> bool {
804 self.app_state == APP_STATE_NOTICED
805 }
806}
807
808impl StockTransferOut {
809 #[inline]
812 pub fn user_notified_broker(&self) -> bool {
813 self.app_state == APP_STATE_NOTICED
814 }
815
816 #[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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
837#[serde(from = "RawRewardRecord")]
838pub struct RewardRecord {
839 pub reward_type: RewardType,
843 pub reward_type_raw: Option<i32>,
847 pub detail_kind: RewardDetailKind,
849 pub record_id: String,
851 pub activity_title: String,
853 pub title: String,
855 pub description: String,
857 pub card_type: String,
859 pub card_status: CouponStatus,
861 pub card_status_raw: Option<i32>,
865 pub prize_type: Option<i32>,
868 pub amount: Option<Decimal>,
870 pub currency: String,
872 pub status: RewardStatus,
874 pub status_raw: Option<i32>,
878 pub deliver_status: RewardDeliverStatus,
882 pub deliver_status_raw: Option<i32>,
887 pub exit_status: i32,
889 #[serde(with = "serde_utils::account_time_opt")]
891 pub send_time: Option<OffsetDateTime>,
892 #[serde(with = "serde_utils::account_time_opt")]
894 pub start_time: Option<OffsetDateTime>,
895 #[serde(with = "serde_utils::account_time_opt")]
897 pub end_time: Option<OffsetDateTime>,
898 #[serde(with = "serde_utils::account_time_opt")]
900 pub effective_time: Option<OffsetDateTime>,
901 #[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
953fn 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 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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1012#[serde(default)]
1013pub struct RewardRecordsResponse {
1014 #[serde(deserialize_with = "serde_utils::null_as_default")]
1016 pub list: Vec<RewardRecord>,
1017 #[serde(deserialize_with = "serde_utils::account_int64")]
1019 pub total: i64,
1020}
1021
1022macro_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#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
1058#[repr(i32)]
1059pub enum CouponTargetType {
1060 #[default]
1062 Unknown = -1,
1063 Stock = 0,
1065 UsOption = 1,
1067 HkWarrant = 2,
1069 Etf = 3,
1071 Lof = 4,
1073}
1074
1075#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
1077#[repr(i32)]
1078pub enum IpoCouponTargetType {
1079 #[default]
1081 Unknown = -1,
1082 Financing = 1,
1084 Cash = 2,
1086}
1087
1088#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
1093#[repr(i32)]
1094pub enum CommissionUnlimitedType {
1095 #[default]
1097 Unknown = -1,
1098 Proportionate = 0,
1100 Full = 1,
1102 Lifetime = 2,
1104 ByAmountPer = 6,
1107 ByRatePer = 7,
1110}
1111
1112#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Default, FromPrimitive, IntoPrimitive)]
1114#[repr(i32)]
1115pub enum QuoteInvestorType {
1116 #[default]
1118 Unknown = -1,
1119 Any = 0,
1121 NonProfessional = 1,
1123 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
1153fn 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
1169fn 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
1187fn 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
1203fn 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
1221fn 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
1231fn 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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1248#[serde(default, remote = "Self")]
1249pub struct CouponCommission {
1250 #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1252 pub markets: Vec<String>,
1253 #[serde(deserialize_with = "serde_utils::string_lenient")]
1255 pub rebate_rate: String,
1256 #[serde(deserialize_with = "enum_vec")]
1258 pub bz_types: Vec<CouponTargetType>,
1259 pub bz_types_raw: Vec<i32>,
1264 #[serde(with = "serde_utils::decimal_opt_lenient")]
1266 pub commission_balance: Option<Decimal>,
1267 #[serde(deserialize_with = "serde_utils::account_int64")]
1270 pub commission_duration: i64,
1271 pub unlimited: CommissionUnlimitedType,
1273 pub unlimited_raw: Option<i32>,
1277 #[serde(with = "serde_utils::account_time_opt")]
1279 pub commission_expired_time: Option<OffsetDateTime>,
1280 #[serde(deserialize_with = "serde_utils::account_int64")]
1282 pub usage_count: i64,
1283 #[serde(deserialize_with = "serde_utils::account_int64")]
1285 pub lave_usage_count: i64,
1286 #[serde(deserialize_with = "serde_utils::string_lenient")]
1288 pub settlement_model: String,
1289 #[serde(deserialize_with = "serde_utils::account_int64")]
1292 pub amount_limit: i64,
1293 #[serde(deserialize_with = "serde_utils::bool_lenient")]
1295 pub superposition: bool,
1296}
1297
1298#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1300#[serde(default)]
1301pub struct CouponAiBenefit {
1302 #[serde(deserialize_with = "serde_utils::account_int32")]
1304 pub benefit_days: i32,
1305 #[serde(with = "serde_utils::account_time_opt")]
1307 pub benefit_start: Option<OffsetDateTime>,
1308 #[serde(with = "serde_utils::account_time_opt")]
1310 pub benefit_end: Option<OffsetDateTime>,
1311 #[serde(deserialize_with = "serde_utils::string_lenient")]
1313 pub benefit_tag: String,
1314}
1315
1316#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1318#[serde(default)]
1319pub struct CouponCash {
1320 #[serde(deserialize_with = "serde_utils::account_int64")]
1323 pub receive_duration: i64,
1324}
1325
1326#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1328#[serde(default)]
1329pub struct CouponCoffeeStore {
1330 #[serde(deserialize_with = "serde_utils::account_int64")]
1332 pub store_id: i64,
1333 #[serde(deserialize_with = "serde_utils::string_lenient")]
1335 pub store_name: String,
1336}
1337
1338#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1340#[serde(default)]
1341pub struct CouponCoffee {
1342 #[serde(deserialize_with = "serde_utils::string_lenient")]
1344 pub coupon_channel: String,
1345 #[serde(deserialize_with = "serde_utils::string_lenient")]
1347 pub coupon_id: String,
1348 #[serde(deserialize_with = "serde_utils::string_lenient")]
1351 pub coupon_no: String,
1352 #[serde(deserialize_with = "serde_utils::bool_lenient")]
1354 pub is_available_all_store: bool,
1355 #[serde(deserialize_with = "serde_utils::string_lenient")]
1357 pub period_type: String,
1358 #[serde(deserialize_with = "serde_utils::account_int64")]
1360 pub settled_store_id: i64,
1361 #[serde(deserialize_with = "int64_vec")]
1363 pub store_id_list: Vec<i64>,
1364 #[serde(deserialize_with = "object_vec")]
1366 pub store_list: Vec<CouponCoffeeStore>,
1367 #[serde(deserialize_with = "serde_utils::account_int64")]
1369 pub threshold: i64,
1370 #[serde(deserialize_with = "serde_utils::string_lenient")]
1372 pub use_limit: String,
1373}
1374
1375#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1377#[serde(default)]
1378pub struct CouponCryptoCounter {
1379 #[serde(deserialize_with = "serde_utils::string_lenient")]
1381 pub counter_id: String,
1382}
1383
1384#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1386#[serde(default)]
1387pub struct CouponCryptoFallback {
1388 #[serde(deserialize_with = "serde_utils::bool_lenient")]
1390 pub enabled: bool,
1391 #[serde(deserialize_with = "serde_utils::string_lenient")]
1393 pub counter_id: String,
1394}
1395
1396#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1398#[serde(default)]
1399pub struct CouponCrypto {
1400 #[serde(deserialize_with = "object_or_default")]
1402 pub fallback: CouponCryptoFallback,
1403 #[serde(deserialize_with = "object_vec")]
1405 pub optional_counters: Vec<CouponCryptoCounter>,
1406}
1407
1408#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1413#[serde(default)]
1414pub struct CouponFinanceInterest {
1415 #[serde(deserialize_with = "serde_utils::account_int32")]
1417 pub discount_mode: i32,
1418 #[serde(with = "serde_utils::decimal_opt_lenient")]
1420 pub discount_rate: Option<Decimal>,
1421 #[serde(deserialize_with = "serde_utils::bool_lenient")]
1423 pub superposition: bool,
1424}
1425
1426#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1428#[serde(default)]
1429pub struct CouponFundDeduct {
1430 #[serde(deserialize_with = "serde_utils::account_int32")]
1432 pub max_risk_level: i32,
1433 #[serde(deserialize_with = "serde_utils::string_lenient")]
1435 pub min_order_amount: String,
1436 #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1438 pub order_types: Vec<String>,
1439 #[serde(deserialize_with = "serde_utils::string_lenient")]
1441 pub underlying_type: String,
1442 #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1444 pub underlying_values: Vec<String>,
1445 #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1447 pub underlying_names: Vec<String>,
1448}
1449
1450#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1453#[serde(default, remote = "Self")]
1454pub struct CouponQuote {
1455 #[serde(with = "serde_utils::account_time_opt")]
1457 pub current_end_time: Option<OffsetDateTime>,
1458 #[serde(deserialize_with = "serde_utils::bool_lenient")]
1460 pub inapplicable: bool,
1461 pub investor_type: QuoteInvestorType,
1463 pub investor_type_raw: Option<i32>,
1467 #[serde(deserialize_with = "serde_utils::bool_lenient")]
1469 pub manual_activate: bool,
1470 #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1472 pub markets: Vec<String>,
1473 #[serde(deserialize_with = "serde_utils::account_int32")]
1475 pub member_investor_type: i32,
1476 #[serde(deserialize_with = "serde_utils::string_lenient")]
1478 pub pair_spu_no: String,
1479 #[serde(deserialize_with = "serde_utils::account_int64")]
1482 pub quote_duration: i64,
1483 #[serde(deserialize_with = "serde_utils::string_lenient")]
1485 pub quote_market: String,
1486 #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1488 pub quote_tags: Vec<String>,
1489 #[serde(deserialize_with = "serde_utils::bool_lenient")]
1491 pub superposition: bool,
1492}
1493
1494#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1496#[serde(default)]
1497pub struct CouponIpo {
1498 #[serde(deserialize_with = "serde_utils::string_lenient")]
1500 pub subscription_id: String,
1501}
1502
1503#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1505#[serde(default, remote = "Self")]
1506pub struct CouponIpoCommission {
1507 #[serde(deserialize_with = "enum_vec")]
1509 pub bz_types: Vec<IpoCouponTargetType>,
1510 pub bz_types_raw: Vec<i32>,
1515 #[serde(deserialize_with = "serde_utils::string_lenient")]
1517 pub counter_id: String,
1518 #[serde(deserialize_with = "serde_utils::string_lenient")]
1520 pub counter_name: String,
1521 #[serde(deserialize_with = "serde_utils::string_lenient")]
1523 pub financing_limit: String,
1524}
1525
1526#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1528#[serde(default)]
1529pub struct CouponIpoInterest {
1530 #[serde(deserialize_with = "serde_utils::string_lenient")]
1533 pub discount_rate: String,
1534}
1535
1536#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1538#[serde(default, remote = "Self")]
1539pub struct CouponPlatformFeeDeduct {
1540 #[serde(deserialize_with = "enum_vec")]
1542 pub bz_types: Vec<CouponTargetType>,
1543 pub bz_types_raw: Vec<i32>,
1548 #[serde(deserialize_with = "serde_utils::string_lenient")]
1550 pub counter_id: String,
1551 #[serde(deserialize_with = "serde_utils::string_lenient")]
1553 pub counter_name: String,
1554 #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1556 pub markets: Vec<String>,
1557 #[serde(deserialize_with = "serde_utils::account_int64")]
1559 pub usage_count: i64,
1560 #[serde(deserialize_with = "serde_utils::account_int64")]
1562 pub lave_usage_count: i64,
1563 #[serde(deserialize_with = "serde_utils::bool_lenient")]
1565 pub superposition: bool,
1566}
1567
1568#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1570#[serde(default)]
1571pub struct CouponStockCounter {
1572 #[serde(deserialize_with = "serde_utils::string_lenient")]
1574 pub counter_id: String,
1575 #[serde(deserialize_with = "serde_utils::string_lenient")]
1577 pub shares: String,
1578}
1579
1580#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1582#[serde(default)]
1583pub struct CouponStockFallback {
1584 #[serde(deserialize_with = "serde_utils::bool_lenient")]
1586 pub enabled: bool,
1587 #[serde(
1589 rename(deserialize = "type"),
1590 alias = "fallback_type",
1591 deserialize_with = "serde_utils::string_lenient"
1592 )]
1593 pub fallback_type: String,
1594 #[serde(deserialize_with = "serde_utils::string_lenient")]
1596 pub counter_id: String,
1597 #[serde(deserialize_with = "serde_utils::string_lenient")]
1599 pub shares: String,
1600}
1601
1602#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1604#[serde(default)]
1605pub struct CouponStock {
1606 #[serde(deserialize_with = "serde_utils::string_lenient")]
1608 pub counter_id: String,
1609 #[serde(deserialize_with = "serde_utils::string_lenient")]
1611 pub counter_name: String,
1612 #[serde(with = "serde_utils::decimal_opt_lenient")]
1614 pub amount: Option<Decimal>,
1615 #[serde(deserialize_with = "serde_utils::string_lenient")]
1618 pub redemption_type: String,
1619 #[serde(deserialize_with = "serde_utils::string_lenient")]
1622 pub send_way: String,
1623 #[serde(deserialize_with = "object_vec")]
1625 pub optional_counters: Vec<CouponStockCounter>,
1626 #[serde(deserialize_with = "object_or_default")]
1628 pub fallback: CouponStockFallback,
1629}
1630
1631#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1633#[serde(default, remote = "Self")]
1634pub struct CouponStockFragment {
1635 #[serde(deserialize_with = "serde_utils::string_lenient")]
1637 pub counter_id: String,
1638 #[serde(deserialize_with = "serde_utils::string_lenient")]
1640 pub counter_name: String,
1641 #[serde(deserialize_with = "serde_utils::string_lenient")]
1643 pub market: String,
1644 #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1646 pub markets: Vec<String>,
1647 pub underlying_type: CouponTargetType,
1649 pub underlying_type_raw: Option<i32>,
1653 #[serde(deserialize_with = "serde_utils::string_map_lenient")]
1655 pub amounts: std::collections::BTreeMap<String, String>,
1656}
1657
1658#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1666#[serde(default, remote = "Self")]
1667pub struct Coupon {
1668 #[serde(deserialize_with = "serde_utils::string_lenient")]
1671 pub card_id: String,
1672 #[serde(deserialize_with = "serde_utils::string_lenient")]
1675 pub card_type: String,
1676 #[serde(deserialize_with = "serde_utils::string_lenient")]
1678 pub title: String,
1679 #[serde(deserialize_with = "serde_utils::string_lenient")]
1681 pub title_sec: String,
1682 #[serde(deserialize_with = "serde_utils::string_lenient")]
1684 pub description: String,
1685 #[serde(deserialize_with = "serde_utils::string_lenient")]
1687 pub detail: String,
1688 pub card_status: CouponStatus,
1690 pub card_status_raw: Option<i32>,
1694 #[serde(with = "serde_utils::account_time_opt")]
1696 pub start_time: Option<OffsetDateTime>,
1697 #[serde(with = "serde_utils::account_time_opt")]
1700 pub end_time: Option<OffsetDateTime>,
1701 #[serde(deserialize_with = "serde_utils::bool_lenient")]
1704 pub no_expiry: bool,
1705 #[serde(with = "serde_utils::account_time_opt")]
1707 pub activate_time: Option<OffsetDateTime>,
1708 #[serde(with = "serde_utils::decimal_opt_lenient")]
1710 pub amount: Option<Decimal>,
1711 #[serde(deserialize_with = "serde_utils::string_lenient")]
1713 pub currency: String,
1714 #[serde(deserialize_with = "serde_utils::string_lenient")]
1716 pub available_trade_session: String,
1717 #[serde(deserialize_with = "serde_utils::string_vec_lenient")]
1719 pub trade_sessions: Vec<String>,
1720 #[serde(deserialize_with = "serde_utils::string_lenient")]
1722 pub subscription_id: String,
1723 #[serde(deserialize_with = "object_opt")]
1725 pub ai_benefit: Option<CouponAiBenefit>,
1726 #[serde(deserialize_with = "object_opt")]
1728 pub cash: Option<CouponCash>,
1729 #[serde(deserialize_with = "object_opt")]
1731 pub coffee_coupon: Option<CouponCoffee>,
1732 #[serde(deserialize_with = "object_opt")]
1734 pub commission: Option<CouponCommission>,
1735 #[serde(deserialize_with = "object_opt")]
1737 pub crypto: Option<CouponCrypto>,
1738 #[serde(deserialize_with = "object_opt")]
1740 pub finance_interest: Option<CouponFinanceInterest>,
1741 #[serde(deserialize_with = "object_opt")]
1743 pub fund_deduct: Option<CouponFundDeduct>,
1744 #[serde(deserialize_with = "object_opt")]
1746 pub fundamental: Option<CouponQuote>,
1747 #[serde(deserialize_with = "object_opt")]
1749 pub ipo: Option<CouponIpo>,
1750 #[serde(deserialize_with = "object_opt")]
1752 pub ipo_commission: Option<CouponIpoCommission>,
1753 #[serde(deserialize_with = "object_opt")]
1755 pub ipo_interest: Option<CouponIpoInterest>,
1756 #[serde(deserialize_with = "object_opt")]
1758 pub platform_fee_deduct: Option<CouponPlatformFeeDeduct>,
1759 #[serde(deserialize_with = "object_opt")]
1761 pub quote: Option<CouponQuote>,
1762 #[serde(deserialize_with = "object_opt")]
1764 pub stock: Option<CouponStock>,
1765 #[serde(deserialize_with = "object_opt")]
1767 pub stock_fragment: Option<CouponStockFragment>,
1768}
1769
1770#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1772#[serde(default)]
1773pub struct CouponsResponse {
1774 #[serde(deserialize_with = "coupon_list")]
1776 pub top_list: Vec<Coupon>,
1777 #[serde(deserialize_with = "coupon_list")]
1779 pub list: Vec<Coupon>,
1780 #[serde(deserialize_with = "coupon_list")]
1782 pub bottom_list: Vec<Coupon>,
1783 #[serde(deserialize_with = "serde_utils::account_int64")]
1785 pub total: i64,
1786 #[serde(deserialize_with = "serde_utils::account_int64")]
1788 pub expired_count: i64,
1789}
1790
1791fn 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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1816#[serde(default)]
1817pub struct CouponOrder {
1818 #[serde(deserialize_with = "serde_utils::string_lenient")]
1820 pub order_id: String,
1821 #[serde(deserialize_with = "serde_utils::string_lenient")]
1823 pub state: String,
1824 #[serde(deserialize_with = "serde_utils::string_lenient")]
1826 pub state_val: String,
1827 #[serde(with = "serde_utils::decimal_opt_lenient")]
1829 pub executed_price: Option<Decimal>,
1830 #[serde(with = "serde_utils::decimal_opt_lenient")]
1832 pub executed_quantity: Option<Decimal>,
1833 #[serde(deserialize_with = "serde_utils::string_lenient")]
1835 pub currency: String,
1836 #[serde(deserialize_with = "serde_utils::string_lenient")]
1838 pub settlement_currency: String,
1839 #[serde(with = "serde_utils::decimal_opt_lenient")]
1841 pub rebate: Option<Decimal>,
1842 #[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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1858#[serde(default, remote = "Self")]
1859pub struct Deposit {
1860 #[serde(deserialize_with = "serde_utils::string_lenient")]
1862 pub id: String,
1863 #[serde(with = "serde_utils::account_time_opt")]
1865 pub created_at: Option<OffsetDateTime>,
1866 #[serde(with = "serde_utils::account_time_opt")]
1868 pub updated_at: Option<OffsetDateTime>,
1869 #[serde(deserialize_with = "serde_utils::string_lenient")]
1871 pub currency: String,
1872 #[serde(with = "serde_utils::decimal_opt_lenient")]
1874 pub amount: Option<Decimal>,
1875 #[serde(with = "serde_utils::decimal_opt_lenient")]
1877 pub receivable_amount: Option<Decimal>,
1878 #[serde(deserialize_with = "serde_utils::string_lenient")]
1880 pub state: String,
1881 pub state_code: DepositState,
1883 pub state_code_raw: Option<i32>,
1887 #[serde(deserialize_with = "serde_utils::account_int32")]
1889 pub sub_state_code: i32,
1890 #[serde(deserialize_with = "serde_utils::string_lenient")]
1892 pub bank_operation_type_id: String,
1893 #[serde(deserialize_with = "serde_utils::string_lenient")]
1895 pub bank_operation_type_name: String,
1896 #[serde(deserialize_with = "serde_utils::string_lenient")]
1898 pub reference_no: String,
1899 #[serde(deserialize_with = "serde_utils::bool_lenient")]
1901 pub can_cancel: bool,
1902 #[serde(deserialize_with = "serde_utils::string_lenient")]
1904 pub user_bank_swift_code: String,
1905 #[serde(
1908 rename(deserialize = "vouchers"),
1909 alias = "voucher_count",
1910 deserialize_with = "item_count"
1911 )]
1912 pub voucher_count: i64,
1913}
1914
1915fn 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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1933#[serde(default)]
1934pub struct DepositsResponse {
1935 #[serde(deserialize_with = "serde_utils::null_as_default")]
1937 pub items: Vec<Deposit>,
1938 pub has_more: bool,
1941}
1942
1943#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1945#[serde(default, remote = "Self")]
1946pub struct Withdrawal {
1947 #[serde(deserialize_with = "serde_utils::string_lenient")]
1949 pub id: String,
1950 #[serde(deserialize_with = "serde_utils::string_lenient")]
1952 pub order_id: String,
1953 #[serde(with = "serde_utils::account_time_opt")]
1955 pub created_at: Option<OffsetDateTime>,
1956 #[serde(deserialize_with = "serde_utils::string_lenient")]
1958 pub currency: String,
1959 #[serde(with = "serde_utils::decimal_opt_lenient")]
1961 pub amount: Option<Decimal>,
1962 #[serde(with = "serde_utils::decimal_opt_lenient")]
1964 pub fee: Option<Decimal>,
1965 #[serde(with = "serde_utils::decimal_opt_lenient")]
1967 pub settlement_amount: Option<Decimal>,
1968 #[serde(rename(deserialize = "state"), alias = "state_code")]
1970 pub state_code: WithdrawalState,
1971 pub state_code_raw: Option<i32>,
1975 #[serde(deserialize_with = "serde_utils::string_lenient")]
1977 pub raw_state: String,
1978 #[serde(deserialize_with = "serde_utils::string_lenient")]
1980 pub state_description: String,
1981 #[serde(deserialize_with = "serde_utils::string_lenient")]
1983 pub bank_account: String,
1984 #[serde(deserialize_with = "serde_utils::string_lenient")]
1986 pub display_bank_account: String,
1987 #[serde(deserialize_with = "serde_utils::string_lenient")]
1989 pub user_bank_swift_code: String,
1990 #[serde(deserialize_with = "serde_utils::string_lenient")]
1992 pub account_channel: String,
1993}
1994
1995#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1997#[serde(default)]
1998pub struct WithdrawalsResponse {
1999 #[serde(deserialize_with = "serde_utils::null_as_default")]
2001 pub list: Vec<Withdrawal>,
2002 #[serde(deserialize_with = "serde_utils::account_int64")]
2004 pub total: i64,
2005 pub has_more: bool,
2008}
2009
2010fn 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
2022fn 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
2038macro_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 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}