rusaint 0.16.3

Easy-to-use SSU u-saint client
Documentation
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
use self::model::{ClassGrade, CourseType, GradeSummary, GradesByClassification, SemesterGrade};
use crate::application::utils::input_field::InputFieldExt as _;
use crate::application::utils::oz::{
    extract_oz_url_from_script_calls, fetch_data_module, parse_oz_url_params,
};
use crate::application::utils::popup::close_popups;
use crate::application::utils::sap_table::try_table_into_with_scroll;
use crate::application::utils::semester::get_selected_semester;
use crate::client::{USaintApplication, USaintClient};
use crate::{ApplicationError, RusaintError, model::SemesterType};
use std::collections::HashMap;
use wdpe::body::Body;
use wdpe::command::WebDynproCommandExecutor;
use wdpe::command::element::action::ButtonPressEventCommand;
use wdpe::element::action::Button;
use wdpe::element::complex::sap_table::cell::SapTableCellWrapper;
use wdpe::element::parser::ElementParser;
use wdpe::scraper::Selector;
use wdpe::state::EventProcessResult;
use wdpe::{
    command::element::{
        complex::SapTableBodyCommand,
        selection::{ComboBoxLSDataCommand, ComboBoxSelectEventCommand},
    },
    define_elements,
    element::{
        Element, ElementDefWrapper, ElementWrapper,
        complex::sap_table::{SapTable, cell::SapTableCell},
        definition::ElementDefinition,
        selection::ComboBox,
        text::InputField,
    },
    error::{BodyError, ElementError, WebDynproError},
    event::Event,
};

/// [학생 성적 조회](https://ecc.ssu.ac.kr/sap/bc/webdynpro/SAP/ZCMB3W0017)
#[derive(Debug)]
pub struct CourseGradesApplication {
    client: USaintClient,
}

impl USaintApplication for CourseGradesApplication {
    const APP_NAME: &'static str = "ZCMB3W0017";

    fn from_client(client: USaintClient) -> Result<Self, RusaintError> {
        if client.name() != Self::APP_NAME {
            Err(RusaintError::InvalidClientError)
        } else {
            Ok(Self { client })
        }
    }
}

#[allow(unused)]
impl<'a> CourseGradesApplication {
    define_elements! {
        BTN_SEARCH: Button<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.BTN_SEARCH";
        // Button to see grades by course classification
        BTN_PRINT_CP: Button<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.BTN_PRINT_CP";
    }

    // Elements for Grade Summaries
    define_elements!(
        // Grade summaries by semester
        GRADES_SUMMARY_TABLE: SapTable<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.TABLE";
        // Progress type
        PROGRESS_TYPE: ComboBox<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.PROGC_VAR";
        // Attempted Credits in Record
        ATTM_CRD1: InputField<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.ATTM_CRD1";
        // Earned Credits in Record
        EARN_CRD1: InputField<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.EARN_CRD1";
        // GPA in Record
        GT_GPA1: InputField<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.GT_GPA1";
        // Class GPA in Record
        CGPA1: InputField<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.CGPA1";
        // Average Points in Record
        AVG1: InputField<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.AVG1";
        // Credits earned in P/F Classes in Record
        PF_EARN_CRD: InputField<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.PF_EARN_CRD";
        // Attempted Credits in Certificate
        ATTM_CRD2: InputField<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.ATTM_CRD2";
        // Earned Credits in Certificate
        EARN_CRD2: InputField<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.EARN_CRD2";
        // GPA in Certificate
        GT_GPA2: InputField<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.GT_GPA2";
        // Class GPA in Certificate
        CGPA2: InputField<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.CGPA2";
        // Average Points in Certificate
        AVG2: InputField<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.AVG2";
        // Credits earned in P/F Classes in Certificate
        PF_EARN_CRD1: InputField<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.T_PF_ERN_CRD1";
    );

    // Elements for Class Grades
    define_elements!(
        PERIOD_YEAR: ComboBox<'a> = "ZCMW_PERIOD_RE.ID_0DC742680F42DA9747594D1AE51A0C69:VIW_MAIN.PERYR";
        PERIOD_SEMESTER: ComboBox<'a> = "ZCMW_PERIOD_RE.ID_0DC742680F42DA9747594D1AE51A0C69:VIW_MAIN.PERID";
        GRADE_BY_CLASSES_TABLE: SapTable<'a> = "ZCMB3W0017.ID_0001:VIW_MAIN.TABLE_1";
    );

    async fn close_popups(&mut self) -> Result<(), WebDynproError> {
        close_popups(&mut self.client).await
    }

    fn semester_to_key(semester: SemesterType) -> &'static str {
        match semester {
            SemesterType::One => "090",
            SemesterType::Summer => "091",
            SemesterType::Two => "092",
            SemesterType::Winter => "093",
        }
    }

    fn course_type_to_key(course_type: CourseType) -> &'static str {
        match course_type {
            CourseType::Phd => "DR",
            CourseType::Master => "MA",
            CourseType::PhdIntergrated => "MP",
            CourseType::Research => "RE",
            CourseType::Bachelor => "UG",
        }
    }

    async fn select_course(
        &mut self,
        parser: &ElementParser,
        course: CourseType,
    ) -> Result<(), WebDynproError> {
        let course = Self::course_type_to_key(course);
        let combobox_lsdata = parser.read(ComboBoxLSDataCommand::new(Self::PROGRESS_TYPE))?;
        if combobox_lsdata.key().map(String::as_str) != Some(course) {
            let select_event = parser.read(ComboBoxSelectEventCommand::new(
                Self::PROGRESS_TYPE,
                course,
                false,
            ))?;
            self.client.process_event(false, select_event).await?;
        }
        Ok(())
    }

    async fn select_semester(
        &mut self,
        parser: &ElementParser,
        year: &str,
        semester: SemesterType,
    ) -> Result<(), WebDynproError> {
        let semester = Self::semester_to_key(semester);
        let year_combobox_lsdata = parser.read(ComboBoxLSDataCommand::new(Self::PERIOD_YEAR))?;
        let semester_combobox_lsdata =
            parser.read(ComboBoxLSDataCommand::new(Self::PERIOD_SEMESTER))?;
        if year_combobox_lsdata.key().map(String::as_str) != Some(year) {
            let year_select_event = parser.read(ComboBoxSelectEventCommand::new(
                Self::PERIOD_YEAR,
                year,
                false,
            ))?;
            self.client.process_event(false, year_select_event).await?;
        }
        if semester_combobox_lsdata.key().map(String::as_str) != Some(semester) {
            let semester_select_event = parser.read(ComboBoxSelectEventCommand::new(
                Self::PERIOD_SEMESTER,
                semester,
                false,
            ))?;
            self.client
                .process_event(false, semester_select_event)
                .await?;
        }
        Ok(())
    }

    /// 현재 페이지에 선택된 년도와 학기를 가져옵니다. 최초 로드 시 현재 학기를 가져올 가능성이 있습니다.
    /// 하지만 이 애플리케이션의 다른 함수를 호출하여 한번 정보를 가져왔다면 마지막으로 가져온 정보의 학기가 반환되므로 주의하여야 하며, 신뢰할 수 있는 현재 학기의 원천으로 사용되어서는 안됩니다.
    pub fn get_selected_semester(&self) -> Result<(u32, SemesterType), RusaintError> {
        Ok(get_selected_semester(
            &self.client,
            &Self::PERIOD_YEAR,
            &Self::PERIOD_SEMESTER,
        )?)
    }

    /// 최신 정보를 조회합니다. 새로고침 시 유용합니다.
    pub async fn lookup(&mut self) -> Result<(), RusaintError> {
        let parser = ElementParser::new(self.client.body());
        let button_press_event = parser.read(ButtonPressEventCommand::new(Self::BTN_SEARCH))?;
        self.client.process_event(false, button_press_event).await?;
        Ok(())
    }

    /// 페이지를 새로고침합니다.
    pub async fn reload(&mut self) -> Result<(), RusaintError> {
        self.client.reload().await?;
        Ok(())
    }

    /// 전체 학기의 학적부 평점 정보를 가져옵니다.
    /// ### 예시
    /// ```no_run
    /// # tokio_test::block_on(async {
    /// # use std::sync::Arc;
    /// # use rusaint::USaintSession;
    /// # use rusaint::application::course_grades::{ model::CourseType, CourseGradesApplication };
    /// # use rusaint::client::USaintClientBuilder;
    /// # let session = Arc::new(USaintSession::with_password("20212345", "password").await.unwrap());
    /// let mut app = USaintClientBuilder::new().session(session).build_into::<CourseGradesApplication>().await.unwrap();
    /// let summary = app.recorded_summary(CourseType::Bachelor).await.unwrap();
    /// println!("{:?}", summary);
    /// // GradeSummary { ... }
    /// # })
    /// ```
    pub async fn recorded_summary(
        &mut self,
        course_type: CourseType,
    ) -> Result<GradeSummary, RusaintError> {
        self.close_popups().await?;
        let parser = ElementParser::new(self.client.body());
        self.select_course(&parser, course_type).await?;
        self.read_recorded_summary()
    }

    fn read_recorded_summary(&self) -> Result<GradeSummary, RusaintError> {
        let parser = ElementParser::new(self.client.body());
        let attempted_credits = parser
            .element_from_def(&Self::ATTM_CRD1)?
            .value_into_f32()?;
        let earned_credits = parser
            .element_from_def(&Self::EARN_CRD1)?
            .value_into_f32()?;
        let gpa = parser.element_from_def(&Self::GT_GPA1)?.value_into_f32()?;
        let cgpa = parser.element_from_def(&Self::CGPA1)?.value_into_f32()?;
        let avg = parser.element_from_def(&Self::AVG1)?.value_into_f32()?;
        let pf_earned_credits = parser
            .element_from_def(&Self::PF_EARN_CRD)?
            .value_into_f32()?;
        Ok(GradeSummary::new(
            attempted_credits,
            earned_credits,
            gpa,
            cgpa,
            avg,
            pf_earned_credits,
        ))
    }

    /// 전체 학기의 증명 평점 정보를 가져옵니다.
    /// ### 예시
    /// ```no_run
    /// # tokio_test::block_on(async {
    /// # use std::sync::Arc;
    /// # use rusaint::USaintSession;
    /// # use rusaint::client::USaintClientBuilder;
    /// # use rusaint::application::course_grades::{ model::CourseType, CourseGradesApplication };
    /// # let session = Arc::new(USaintSession::with_password("20212345", "password").await.unwrap());
    /// let mut app = USaintClientBuilder::new().session(session).build_into::<CourseGradesApplication>().await.unwrap();
    /// let summary = app.certificated_summary(CourseType::Bachelor).await.unwrap();
    /// println!("{:?}", summary);
    /// // GradeSummary { ... }
    /// # })
    /// ```
    pub async fn certificated_summary(
        &mut self,
        course_type: CourseType,
    ) -> Result<GradeSummary, RusaintError> {
        self.close_popups().await?;
        let parser = ElementParser::new(self.client.body());
        self.select_course(&parser, course_type).await?;
        self.read_certificated_summary()
    }

    fn read_certificated_summary(&self) -> Result<GradeSummary, RusaintError> {
        let parser = ElementParser::new(self.client.body());
        let attempted_credits = parser
            .element_from_def(&Self::ATTM_CRD2)?
            .value_into_f32()?;
        let earned_credits = parser
            .element_from_def(&Self::EARN_CRD2)?
            .value_into_f32()?;
        let gpa = parser.element_from_def(&Self::GT_GPA2)?.value_into_f32()?;
        let cgpa = parser.element_from_def(&Self::CGPA2)?.value_into_f32()?;
        let avg = parser.element_from_def(&Self::AVG2)?.value_into_f32()?;
        let pf_earned_credits = parser
            .element_from_def(&Self::PF_EARN_CRD1)?
            .value_into_f32()?;
        Ok(GradeSummary::new(
            attempted_credits,
            earned_credits,
            gpa,
            cgpa,
            avg,
            pf_earned_credits,
        ))
    }

    /// 이수구분별 성적 데이터를 OZ 서버에서 가져옵니다.
    pub async fn grades_by_classification(
        &mut self,
        course_type: CourseType,
    ) -> Result<GradesByClassification, RusaintError> {
        self.close_popups().await?;

        let parser = ElementParser::new(self.client.body());
        let button_press_event = parser.read(ButtonPressEventCommand::new(Self::BTN_PRINT_CP))?;
        let result = self.client.process_event(true, button_press_event).await?;

        let script_calls = match result {
            EventProcessResult::Sent(body_update_result) => {
                body_update_result.script_calls.unwrap_or_default()
            }
            EventProcessResult::Enqueued => {
                return Err(ApplicationError::OzDataFetchError(
                    "BTN_PRINT_CP event was enqueued but not sent".to_string(),
                )
                .into());
            }
        };

        let oz_url = extract_oz_url_from_script_calls(&script_calls)?;
        let mut oz_params = parse_oz_url_params(&oz_url)?;

        if let Some(uname) = oz_params
            .params
            .iter()
            .find(|(k, _)| k == "UNAME")
            .map(|(_, v)| v.clone())
        {
            if !oz_params.params.iter().any(|(k, _)| k == "arg4") {
                oz_params.params.push(("arg4".to_string(), uname.clone()));
            }
            if !oz_params.params.iter().any(|(k, _)| k == "ADMIN") {
                oz_params.params.push(("ADMIN".to_string(), uname));
            }
        }

        let response = fetch_data_module(&oz_params, Some(self.client.http_client())).await?;
        let result = GradesByClassification::from_datasets(&response.datasets)?;
        Ok(result)
    }

    /// 학기별 평점 정보를 가져옵니다.
    /// ### 예시
    /// ```no_run
    /// # tokio_test::block_on(async {
    /// # use std::sync::Arc;
    /// # use rusaint::USaintSession;
    /// # use rusaint::application::course_grades::{ model::CourseType, CourseGradesApplication };
    /// # use rusaint::client::USaintClientBuilder;
    /// # let session = Arc::new(USaintSession::with_password("20212345", "password").await.unwrap());
    /// let mut app = USaintClientBuilder::new().session(session).build_into::<CourseGradesApplication>().await.unwrap();
    /// let semesters = app.semesters(CourseType::Bachelor).await.unwrap();
    /// println!("{:?}", semesters);
    /// // [SemesterGrade { ... }, SemesterGrade { ... }]
    /// # })
    /// ```
    pub async fn semesters(
        &mut self,
        course_type: CourseType,
    ) -> Result<Vec<SemesterGrade>, RusaintError> {
        self.close_popups().await?;
        let parser = ElementParser::new(self.client.body());
        self.select_course(&parser, course_type).await?;
        self.read_semesters().await
    }

    async fn read_semesters(&mut self) -> Result<Vec<SemesterGrade>, RusaintError> {
        let parser = ElementParser::new(self.client.body());
        let ret = try_table_into_with_scroll::<SemesterGrade>(
            &mut self.client,
            parser,
            Self::GRADES_SUMMARY_TABLE,
        )
        .await?;
        Ok(ret)
    }

    async fn class_detail_in_popup(
        &mut self,
        press_event: Event,
    ) -> Result<HashMap<String, f32>, RusaintError> {
        self.client.process_event(false, press_event).await?;

        let parse_table_in_popup = |body: &Body| -> Result<HashMap<String, f32>, WebDynproError> {
            let table_inside_popup_selector = Selector::parse(r#"[ct="PW"] [ct="ST"]"#).unwrap();
            let parser = ElementParser::new(body);
            let mut table_inside_popup = parser.document().select(&table_inside_popup_selector);
            let table_ref = table_inside_popup
                .next()
                .ok_or(BodyError::NoSuchElement("Table in popup".to_string()))?;
            let table_elem: SapTable<'_> = ElementWrapper::from_ref(table_ref)?.try_into()?;
            let table_body = table_elem.table()?;
            let zip = table_body
                .iter()
                .next()
                .ok_or(ElementError::InvalidContent {
                    element: table_elem.id().to_string(),
                    content: "header and first row".to_string(),
                })?
                .try_row_into::<Vec<(String, String)>>(table_body.header(), &parser)?
                .into_iter();
            zip.skip(4)
                .map(|(key, val)| {
                    let str = val.trim();
                    if str.is_empty() {
                        return Ok((key, -1.0));
                    }
                    let float = str.parse::<f32>().or(Err(ElementError::InvalidContent {
                        element: format!("TABLE: {}, key: {}", table_elem.id(), key),
                        content: "(not an correct f32)".to_string(),
                    }))?;
                    Ok((key, float))
                })
                .collect::<Result<HashMap<String, f32>, WebDynproError>>()
        };
        let table = parse_table_in_popup(self.client.body())?;
        self.close_popups().await?;
        Ok(HashMap::from_iter(table))
    }

    /// 주어진 학기의 수업별 성적을 가져옵니다. `include_details`가 `true`인 경우 수업의 상세 성적도 가져옵니다.
    /// 수업의 상세 성적까지 가져올 경우 상세 성적이 있는 수업의 수 만큼 서버에 요청을 보내므로 반드시 상세 성적도 한번에 가져와야 할 때에만 사용하십시오.
    ///
    /// 수업 성적을 가져온 이후 상세 성적 또한 가져오려면 [`class_detail()`]함수를 이용하십시오.
    /// ### 예시
    /// 상세 성적을 가져오지 않을 경우
    /// ```no_run
    /// # tokio_test::block_on(async {
    /// # use std::sync::Arc;
    /// # use rusaint::USaintSession;
    /// # use rusaint::application::course_grades::{ model::CourseType, CourseGradesApplication };
    /// # use rusaint::client::USaintClientBuilder;
    /// # use rusaint::model::SemesterType;
    /// # let session = Arc::new(USaintSession::with_password("20212345", "password").await.unwrap());
    /// let mut app = USaintClientBuilder::new().session(session).build_into::<CourseGradesApplication>().await.unwrap();
    /// let classes = app.classes(CourseType::Bachelor, 2022, SemesterType::Two, false).await.unwrap();
    /// println!("{:?}", classes); // around 3s(depends on network environment)
    /// // [ClassGrade { ... }, ClassGrade { ... }]
    /// # })
    /// ```
    /// 상세 성적을 가져올 경우
    /// ```no_run
    /// # tokio_test::block_on(async {
    /// # use std::sync::Arc;
    /// # use rusaint::USaintSession;
    /// # use rusaint::application::course_grades::{ model::CourseType, CourseGradesApplication };
    /// # use rusaint::model::SemesterType;
    /// # use rusaint::client::USaintClientBuilder;
    /// # let session = Arc::new(USaintSession::with_password("20212345", "password").await.unwrap());
    /// let mut app = USaintClientBuilder::new().session(session).build_into::<CourseGradesApplication>().await.unwrap();
    /// let classes = app.classes(CourseType::Bachelor, 2022, SemesterType::Two, true).await.unwrap();
    /// println!("{:?}", classes); // around 10s(depends on network environment)
    /// // [ClassGrade { ... }, ClassGrade { ... }]
    /// # })
    /// ```
    pub async fn classes(
        &mut self,
        course_type: CourseType,
        year: u32,
        semester: SemesterType,
        include_details: bool,
    ) -> Result<Vec<ClassGrade>, RusaintError> {
        {
            self.close_popups().await?;
            let parser = ElementParser::new(self.client.body());
            self.select_course(&parser, course_type).await?;
            self.select_semester(&parser, &year.to_string(), semester)
                .await?;
        }
        let parser = ElementParser::new(self.client.body());
        let class_grades: Vec<(Option<Event>, HashMap<String, String>)> = {
            let grade_table_body =
                parser.read(SapTableBodyCommand::new(Self::GRADE_BY_CLASSES_TABLE))?;
            let iter = grade_table_body.iter();
            iter.map(|row| {
                let btn_event = SapTableCellWrapper::from_def(&row[4], &parser)
                    .ok()
                    .and_then(|cell| {
                        if let Some(ElementDefWrapper::Button(btn)) = cell.content() {
                            parser.element_from_def(&btn).ok()?.press().ok()
                        } else {
                            None
                        }
                    });
                (btn_event, row)
            })
            .filter_map(|(btn_event, row)| {
                row.try_row_into::<HashMap<String, String>>(grade_table_body.header(), &parser)
                    .ok()
                    .map(|row| (btn_event, row))
            })
            .collect()
        };
        let mut ret: Vec<ClassGrade> = vec![];
        for (btn_event, values) in class_grades {
            let detail: Option<HashMap<String, f32>> = if let Some(btn_event) = btn_event {
                if include_details {
                    Some(self.class_detail_in_popup(btn_event).await?)
                } else {
                    None
                }
            } else {
                None
            };
            let parsed: Option<ClassGrade> = (|| {
                Some(ClassGrade::new(
                    year,
                    semester,
                    values["과목코드"].trim().to_owned(),
                    values["과목명"].trim().to_owned(),
                    values["과목학점"].parse().ok()?,
                    values["성적"].parse().ok()?,
                    values["등급"].trim().to_owned(),
                    values["교수명"].trim().to_owned(),
                    detail,
                ))
            })();
            if let Some(parsed) = parsed {
                ret.push(parsed);
            }
        }
        Ok(ret)
    }

    /// 주어진 수업의 상세 성적 정보를 가져옵니다. 만약 상세 성적이 음수라면, 성적이 비어 있다는 의미입니다.
    /// ### 예시
    /// ```no_run
    /// # tokio_test::block_on(async {
    /// # use std::sync::Arc;
    /// # use rusaint::USaintSession;
    /// # use rusaint::model::SemesterType;
    /// # use rusaint::application::course_grades::{ model::CourseType, CourseGradesApplication };
    /// # use rusaint::client::USaintClientBuilder;
    /// # let session = Arc::new(USaintSession::with_password("20212345", "password").await.unwrap());
    /// let mut app = USaintClientBuilder::new().session(session).build_into::<CourseGradesApplication>().await.unwrap();
    /// let classes = app.classes(CourseType::Bachelor, 2022, SemesterType::Two, false).await.unwrap();
    /// let class = classes.iter().next().unwrap();
    /// let class_detail = app.class_detail(CourseType::Bachelor, 2022, SemesterType::Two, class.code()).await.unwrap();
    /// println!("{:?}", class_detail);
    /// // {"출석(20.000)": 20.0, "중간고사(30.000)": 30.0, "과제(20.000)": 20.0, "기말고사(30.000)": 28.0}
    /// # })
    /// ```
    pub async fn class_detail(
        &mut self,
        course_type: CourseType,
        year: u32,
        semester: SemesterType,
        code: &str,
    ) -> Result<HashMap<String, f32>, RusaintError> {
        let year = year.to_string();
        {
            self.close_popups().await?;
            let parser = ElementParser::new(self.client.body());
            self.select_course(&parser, course_type).await?;
            self.select_semester(&parser, &year, semester).await?;
        }
        let parser = ElementParser::new(self.client.body());
        let table = parser.read(SapTableBodyCommand::new(Self::GRADE_BY_CLASSES_TABLE))?;
        let Some(btn) = ({
            table
                .iter()
                .find(
                    |row| match SapTableCellWrapper::from_def(&row[8], &parser) {
                        Ok(cell) => {
                            if let Some(ElementDefWrapper::TextView(code_elem)) = cell.content() {
                                parser
                                    .element_from_def(&code_elem)
                                    .is_ok_and(|elem| elem.text() == code)
                            } else {
                                false
                            }
                        }
                        Err(_) => false,
                    },
                )
                .and_then(
                    |row| match SapTableCellWrapper::from_def(&row[4], &parser) {
                        Ok(cell) => {
                            if let Some(ElementDefWrapper::Button(btn)) = cell.content() {
                                parser.element_from_def(&btn).ok()?.press().ok()
                            } else {
                                None
                            }
                        }
                        Err(_) => None,
                    },
                )
        }) else {
            return Err(WebDynproError::from(ElementError::NoSuchData {
                element: Self::GRADE_BY_CLASSES_TABLE.id().to_string(),
                field: format!("details of class {code}"),
            }))?;
        };
        self.class_detail_in_popup(btn).await
    }

    fn body(&self) -> &Body {
        self.client.body()
    }
}

/// [`CourseGradesApplication`]에서 사용하는 데이터
pub mod model;

#[cfg(test)]
mod test {
    use crate::{
        application::course_grades::CourseGradesApplication, client::USaintClientBuilder,
        global_test_utils::get_session,
    };
    use wdpe::element::{Element, layout::PopupWindow, parser::ElementParser};

    #[tokio::test]
    async fn close_popups() {
        let session = get_session().await.unwrap();
        let mut app = USaintClientBuilder::new()
            .session(session)
            .build_into::<CourseGradesApplication>()
            .await
            .unwrap();
        app.close_popups().await.unwrap();
        let popup_selector = wdpe::scraper::Selector::parse(
            format!(r#"[ct="{}"]"#, PopupWindow::CONTROL_ID).as_str(),
        )
        .unwrap();
        let parser = ElementParser::new(app.client.body());
        let result = parser.document().select(&popup_selector).next().is_none();
        assert!(result);
    }
}