1use serde::de::DeserializeOwned;
2
3use crate::endpoints;
4use crate::types::TEN_YEARS_MS;
5use crate::{
6 AShareCode, BalanceSheetsData, CashFlowStatementsData, Client, Error, FinancialIndicatorsData,
7 FinancialPeriod, FinancialReport, IncomeStatementsData, Response, UnixMillis, ValidationError,
8};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct FinancialRange(FinancialRangeKind);
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15enum FinancialRangeKind {
16 Recent { limit: u8 },
17 Between { start: UnixMillis, end: UnixMillis },
18}
19
20impl FinancialRange {
21 pub const fn recent(limit: u8) -> Result<Self, ValidationError> {
22 if limit == 0 || limit > 20 {
23 return Err(ValidationError::new("limit", "must be in the range 1..=20"));
24 }
25 Ok(Self(FinancialRangeKind::Recent { limit }))
26 }
27
28 pub fn between(
29 start: impl TryInto<UnixMillis, Error: Into<ValidationError>>,
30 end: impl TryInto<UnixMillis, Error: Into<ValidationError>>,
31 ) -> Result<Self, ValidationError> {
32 let start: UnixMillis = start.try_into().map_err(Into::into)?;
33 let end: UnixMillis = end.try_into().map_err(Into::into)?;
34 if end.get() < start.get() {
35 return Err(ValidationError::new(
36 "end",
37 "must not be earlier than start",
38 ));
39 }
40 if end.get() - start.get() > TEN_YEARS_MS {
41 return Err(ValidationError::new(
42 "end",
43 "requested time window exceeds ten years",
44 ));
45 }
46 Ok(Self(FinancialRangeKind::Between { start, end }))
47 }
48}
49
50impl Client {
51 #[doc = concat!(
55 "```no_run\n",
56 include_str!("../../examples/financials_income_statements.rs"),
57 "\n```"
58 )]
59 pub async fn financials_income_statements(
60 &self,
61 thscode: impl TryInto<AShareCode, Error: Into<ValidationError>>,
62 period: FinancialPeriod,
63 range: FinancialRange,
64 ) -> Result<Response<IncomeStatementsData>, Error> {
65 self.financial_statements(endpoints::INCOME_STATEMENTS, thscode, period, range)
66 .await
67 }
68
69 #[doc = concat!(
73 "```no_run\n",
74 include_str!("../../examples/financials_balance_sheets.rs"),
75 "\n```"
76 )]
77 pub async fn financials_balance_sheets(
78 &self,
79 thscode: impl TryInto<AShareCode, Error: Into<ValidationError>>,
80 period: FinancialPeriod,
81 range: FinancialRange,
82 ) -> Result<Response<BalanceSheetsData>, Error> {
83 self.financial_statements(endpoints::BALANCE_SHEETS, thscode, period, range)
84 .await
85 }
86
87 #[doc = concat!(
91 "```no_run\n",
92 include_str!("../../examples/financials_cash_flow_statements.rs"),
93 "\n```"
94 )]
95 pub async fn financials_cash_flow_statements(
96 &self,
97 thscode: impl TryInto<AShareCode, Error: Into<ValidationError>>,
98 period: FinancialPeriod,
99 range: FinancialRange,
100 ) -> Result<Response<CashFlowStatementsData>, Error> {
101 self.financial_statements(endpoints::CASH_FLOW_STATEMENTS, thscode, period, range)
102 .await
103 }
104
105 async fn financial_statements<T: DeserializeOwned>(
106 &self,
107 path: &str,
108 thscode: impl TryInto<AShareCode, Error: Into<ValidationError>>,
109 period: FinancialPeriod,
110 range: FinancialRange,
111 ) -> Result<Response<T>, Error> {
112 let thscode: AShareCode = thscode.try_into().map_err(Into::into)?;
113 let mut query = vec![
114 ("thscode", thscode.into_string()),
115 ("period", period.to_string()),
116 ];
117 match range.0 {
118 FinancialRangeKind::Recent { limit } => {
119 query.push(("limit", limit.to_string()));
120 }
121 FinancialRangeKind::Between { start, end } => {
122 query.push(("start", start.to_string()));
123 query.push(("end", end.to_string()));
124 }
125 }
126 self.get(path, &query).await
127 }
128
129 #[doc = concat!(
133 "```no_run\n",
134 include_str!("../../examples/financials_indicators.rs"),
135 "\n```"
136 )]
137 pub async fn financials_indicators(
138 &self,
139 thscode: impl TryInto<AShareCode, Error: Into<ValidationError>>,
140 report: impl TryInto<FinancialReport, Error: Into<ValidationError>>,
141 ) -> Result<Response<FinancialIndicatorsData>, Error> {
142 let thscode: AShareCode = thscode.try_into().map_err(Into::into)?;
143 let report: FinancialReport = report.try_into().map_err(Into::into)?;
144 let query = [("thscode", thscode.as_str()), ("report", report.as_str())];
145 self.get(endpoints::FINANCIAL_INDICATORS, &query).await
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use super::FinancialRange;
152
153 #[test]
154 fn financial_range_rejects_invalid_limits_and_reversed_windows() {
155 assert!(FinancialRange::recent(1).is_ok());
156 assert!(FinancialRange::recent(20).is_ok());
157 assert!(FinancialRange::recent(0).is_err());
158 assert!(FinancialRange::recent(21).is_err());
159
160 assert!(FinancialRange::between(1_700_000_000_000, 1_600_000_000_000).is_err());
161 }
162
163 #[test]
164 fn financial_range_rejects_windows_over_ten_years_at_construction() {
165 assert!(FinancialRange::between(1_000_000_000_000, 1_315_576_000_001).is_err());
166 }
167}