1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
use crate::client::{ErrorResponse, CCParser, SuccessResponse, Client};
use std::collections::HashMap;
use chrono::NaiveDate;
use serde::Deserialize;
use serde_json::Value;
pub struct AttendanceOptions {
pub from: NaiveDate,
pub to: NaiveDate,
}
#[derive(Deserialize, Debug)]
pub enum AttendancePeriodStatus {
#[serde(rename = "present")]
Present,
#[serde(rename = "ignore")]
Ignore,
}
#[derive(Debug)]
pub enum LateMinutes {
String(String),
Number(usize),
}
impl<'de> Deserialize<'de> for LateMinutes {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value: Value = Deserialize::deserialize(deserializer)?;
match value {
Value::String(s) => Ok(LateMinutes::String(s)),
Value::Number(num) if num.is_u64() => {
Ok(LateMinutes::Number(num.as_u64().unwrap() as usize))
}
_ => Err(serde::de::Error::custom(
"Invalid format for 'late_minutes' field",
)),
}
}
}
#[derive(Deserialize, Debug)]
pub struct AttendancePeriod {
pub code: String,
pub status: AttendancePeriodStatus,
pub late_minutes: LateMinutes,
pub lesson_name: Option<String>,
pub room_name: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct AttendanceMeta {
pub dates: Vec<String>,
pub sessions: Vec<String>,
pub start_date: String,
pub percentage: String,
pub percentage_singe_august: String,
}
pub type AttendanceData = HashMap<String, HashMap<String, AttendancePeriod>>;
pub type Attendance = SuccessResponse<AttendanceData, AttendanceMeta>;
impl Client {
/// Gets the current student's attendance
/// This is using `chrono` for parsing the date.
///
/// Example:
/// ```ignore
/// // Gets attendance from yesterday day to today.
/// client.get_attendance(Some(
/// AttendanceOptions {
/// from: chrono::Utc::now().checked_sub_days(chrono::Days(1)).date(),
/// to: chrono::Utc::now().date(),
/// }
/// ));
/// ```
pub async fn get_attendance(
&mut self,
options: Option<AttendanceOptions>,
) -> Result<Attendance, ErrorResponse> {
let mut params = url::form_urlencoded::Serializer::new(String::new());
if let Some(options) = options {
params.append_pair("to", &options.to.format("%Y-%m-%d").to_string());
params.append_pair("from", &options.from.format("%Y-%m-%d").to_string());
}
let params = params.finish();
let request = self
.build_get(format!("/attendance/{}?{}", self.student_id, params))
.await?
.send()
.await?;
let text = request.cc_parse().await?;
let data: Attendance = serde_json::from_str(&text)?;
return Ok(data);
}
}
#[cfg(test)]
mod tests {
use super::*;
use httpmock::prelude::*;
use serde_json::json;
#[tokio::test]
async fn get_attendance_test() {
// Start a lightweight mock server.
let server = MockServer::start();
// Create a mock on the server.
let attendance_response = server.mock(|when, then| {
when.method(GET).path("/apiv2student/attendance/student_id");
then.status(200)
.header("content-type", "application/json")
.json_body(json!({
"success": 1,
"data": {
"2023-08-25": {
"AM": {
"code": "#",
"status": "ignore",
"late_minutes": 0
},
"PM": {
"code": "#",
"status": "ignore",
"late_minutes": 0
},
"Period 1": {
"code": "",
"late_minutes": "",
"status": "ignore"
},
"Period 2": {
"code": "",
"late_minutes": "",
"status": "ignore"
},
"Period Tut": {
"code": "",
"late_minutes": "",
"status": "ignore"
},
"Period 3": {
"code": "",
"late_minutes": "",
"status": "ignore"
},
"Period 4": {
"code": "",
"late_minutes": "",
"status": "ignore"
},
"Period 5": {
"code": "",
"late_minutes": "",
"status": "ignore"
}
},
},
"meta": {
"dates": [
"2023-08-25",
],
"sessions": [
"AM",
"PM",
"Period 1",
"Period 2",
"Period Tut",
"Period 3",
"Period 4",
"Period 5",
"Period 6",
],
"start_date": "2023-08-25T00:00:00+00:00",
"end_date": "2023-08-25T16:00:00+00:00",
"percentage": "100",
"percentage_singe_august": "100"
}
}));
});
let mut client = Client::generate_mock(server.base_url());
let _ = client.get_attendance(None).await.unwrap();
attendance_response.assert();
}
}