Skip to main content

financial_api/types/
fund.rs

1use std::str::FromStr;
2
3use serde::{Deserialize, Deserializer, Serialize};
4
5use super::wire::wire_enum;
6use crate::ValidationError;
7
8macro_rules! identifier_type {
9    ($(#[$meta:meta])* $name:ident, $field:literal) => {
10        $(#[$meta])*
11        #[derive(
12            Debug,
13            Clone,
14            PartialEq,
15            Eq,
16            PartialOrd,
17            Ord,
18            Hash,
19            Serialize,
20            derive_more::Display,
21        )]
22        #[serde(transparent)]
23        pub struct $name(String);
24
25        impl $name {
26            pub fn new(value: impl Into<String>) -> Result<Self, ValidationError> {
27                let value = value.into();
28                let trimmed = value.trim();
29                if trimmed.is_empty() {
30                    return Err(ValidationError::new($field, "must not be empty"));
31                }
32                if trimmed.len() == value.len() {
33                    Ok(Self(value))
34                } else {
35                    Ok(Self(trimmed.to_owned()))
36                }
37            }
38
39            #[must_use]
40            pub fn as_str(&self) -> &str {
41                &self.0
42            }
43        }
44
45        impl FromStr for $name {
46            type Err = ValidationError;
47
48            fn from_str(value: &str) -> Result<Self, Self::Err> {
49                Self::new(value)
50            }
51        }
52
53        impl AsRef<str> for $name {
54            fn as_ref(&self) -> &str {
55                self.as_str()
56            }
57        }
58
59        impl<'de> Deserialize<'de> for $name {
60            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
61                let value = String::deserialize(deserializer)?;
62                Self::new(value).map_err(serde::de::Error::custom)
63            }
64        }
65    };
66}
67
68identifier_type!(
69    /// 从基金资料数据中发现的不透明基金经理标识。
70    ManagerId,
71    "manager_id"
72);
73identifier_type!(
74    /// 从基金资料数据中发现的不透明基金公司标识。
75    CompanyId,
76    "company_id"
77);
78identifier_type!(
79    /// 从报告期端点中发现的基金披露报告类型。
80    ReportType,
81    "report_type"
82);
83identifier_type!(
84    /// 在诊断数据中观察到的不透明基金分类代码。
85    FundCategoryCode,
86    "fund_type"
87);
88
89impl ReportType {
90    pub(crate) fn into_string(self) -> String {
91        self.0
92    }
93}
94
95/// 游标分页端点返回的不透明分页游标。
96#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, derive_more::Display)]
97#[serde(transparent)]
98pub struct Cursor(String);
99
100impl Cursor {
101    pub fn new(value: impl Into<String>) -> Result<Self, ValidationError> {
102        let value = value.into();
103        if value.trim().is_empty() {
104            return Err(ValidationError::new("offset", "must not be empty"));
105        }
106        Ok(Self(value))
107    }
108
109    #[must_use]
110    pub fn as_str(&self) -> &str {
111        &self.0
112    }
113
114    pub(crate) fn into_string(self) -> String {
115        self.0
116    }
117}
118
119impl FromStr for Cursor {
120    type Err = ValidationError;
121
122    fn from_str(value: &str) -> Result<Self, Self::Err> {
123        Self::new(value)
124    }
125}
126
127impl AsRef<str> for Cursor {
128    fn as_ref(&self) -> &str {
129        self.as_str()
130    }
131}
132
133impl<'de> Deserialize<'de> for Cursor {
134    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
135        let value = String::deserialize(deserializer)?;
136        Self::new(value).map_err(serde::de::Error::custom)
137    }
138}
139
140wire_enum! {
141    /// 基金标的宇宙。
142    pub enum FundType {
143        Otc => "otc",
144        Exchange => "exchange",
145        Reits => "reits",
146    }
147}
148
149wire_enum! {
150    /// 持有人记录合并策略。
151    pub enum HolderMergeScope {
152        All => "all",
153        Merged => "merged",
154        Separate => "separate",
155    }
156}
157
158wire_enum! {
159    /// 基金历史净值区间。
160    pub enum FundRange {
161        Week => "week",
162        Month => "month",
163        ThreeMonths => "tmonth",
164        HalfYear => "hyear",
165        Year => "year",
166        TwoYears => "twoyear",
167        ThreeYears => "tyear",
168        FiveYears => "fyear",
169    }
170}
171
172wire_enum! {
173    /// 基金净值序列选择。
174    pub enum FundNavType {
175        Unit => "unit",
176        Adjusted => "adj",
177        UnitAndAdjusted => "unit,adj",
178    }
179}
180
181wire_enum! {
182    /// 基金经理业绩区间。
183    pub enum ManagerPerformanceRange {
184        Month => "month",
185        ThreeMonths => "tmonth",
186        Year => "year",
187        CurrentYear => "nowyear",
188        SinceInception => "now",
189    }
190}
191
192wire_enum! {
193    /// 新发基金认购状态。
194    pub enum OfferingStatus {
195        Active => "active",
196        Upcoming => "upcoming",
197    }
198}
199
200wire_enum! {
201    /// 基金持有人记录返回的实际披露范围。
202    pub enum HolderRecordScope {
203        Merged => "merged",
204        Separate => "separate",
205    }
206}
207
208wire_enum! {
209    /// 基金持仓披露使用的资产类别。
210    pub enum PortfolioAssetType {
211        Stock => "stock",
212        Bond => "bond",
213        Fund => "fund",
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use super::{CompanyId, Cursor, FundCategoryCode, ManagerId, ReportType};
220
221    #[test]
222    fn endpoint_identifiers_have_distinct_validated_types() {
223        assert_eq!(ManagerId::new("manager-1").unwrap().as_str(), "manager-1");
224        assert_eq!(CompanyId::new("company-1").unwrap().as_str(), "company-1");
225        assert_eq!(
226            Cursor::new("opaque+/cursor==").unwrap().as_str(),
227            "opaque+/cursor=="
228        );
229        assert_eq!(ReportType::new("quarter").unwrap().as_str(), "quarter");
230        assert_eq!(
231            FundCategoryCode::new("282001003").unwrap().as_str(),
232            "282001003"
233        );
234        assert_eq!(ManagerId::new(" manager-1 ").unwrap().as_str(), "manager-1");
235        assert_eq!(
236            CompanyId::new("\tcompany-1\n").unwrap().as_str(),
237            "company-1"
238        );
239        assert_eq!(ReportType::new(" quarter ").unwrap().as_str(), "quarter");
240        assert_eq!(
241            Cursor::new(" opaque+/cursor== ").unwrap().as_str(),
242            " opaque+/cursor== "
243        );
244
245        assert!(ManagerId::new(" ").is_err());
246        assert!(CompanyId::new("").is_err());
247        assert!(Cursor::new("\t").is_err());
248        assert!(ReportType::new("\n").is_err());
249        assert!(FundCategoryCode::new(" ").is_err());
250    }
251}