diff --git a/CHANGELOG.md b/CHANGELOG.md
index fe3f15a..e67c199 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,13 @@
### API và dữ liệu
+- Thêm tùy chọn `--ics` và `--full` cho `myfap exams`: xuất lịch thi ra định dạng iCalendar chuẩn RFC 5545 (giờ Việt Nam, UID/DTSTAMP UTC, CRLF); mặc định xuất ICS đưa đầy đủ các thông tin quan trọng (Môn, Phòng thi `roomNo`, Ngày công bố `dateofPublication`), chỉ ẩn mã slot UUID, ghi chú phụ và điểm danh; cờ `--full` kèm toàn bộ thông tin phụ vào sự kiện lịch; xuất JSON mặc định tiếp tục bảo toàn đầy đủ 100% dữ liệu gốc.
+- Thêm `myfap other feedbacks` đọc danh sách feedback student qua `GetStudentFeedbacks`, chỉ có trên proxy API v2; envelope đã kiểm chứng live nhưng item schema chưa có positive (danh sách rỗng trên tài khoản kiểm chứng).
+- `transcript --pretty` phân tích HTML bảng điểm toàn khóa thành JSON cấu trúc: mỗi bảng giữ header riêng (bảng chính 10 cột `No`…`Status`, bảng phụ 7 cột) và hàng dữ liệu keyed theo header, chuẩn hoá ` `; không dùng `--pretty` vẫn giữ chuỗi HTML nguyên bản theo contract.
+- `doctor --api-version v2 --online` báo thêm `backend_version` qua `GetVersion` POST bootstrap; GET bị proxy từ chối 405 và route v1 đã 404. `myfap version` vẫn chỉ đọc package version offline.
+- Thêm [phân tích khoảng trống endpoint](docs/endpoint-gap-analysis.md) đối chiếu 82 route của APK với adapter: CLI phủ toàn bộ operation đọc student (ngoại trừ `GetStudentFeedbackForm` đang gate có chủ đích chờ `feedbackId` thực tế); donor/employee, login thay thế và OTA được ghi rõ out of scope.
+- Chuyển training và nhóm rating vào `other`: dùng `myfap other training` và `myfap other rating list`, không giữ command root cũ. Endpoint, policy retry và capability từng version không đổi.
+
- Giữ API v1 làm mặc định. API v2 chỉ được chọn bằng `--api-version v2` hoặc binding của session; không tự chuyển version khi gặp lỗi.
- Bổ sung adapter v2 cho các lệnh đọc hiện có: kỳ học, lịch học/lịch tuần, điểm, lịch thi, điểm danh, đơn từ, news, thông tin sinh viên/campus, học phí, môn học, thông báo và kiểm tra feedback/profile. Survey tiếp tục dùng dịch vụ và chữ ký riêng.
- Coi ID kỳ học là opaque, chọn kỳ mới nhất theo `startDate` và giữ thứ tự server khi ngày trùng nhau. Query dùng đúng tên trường theo từng operation.
@@ -28,9 +35,11 @@
- Báo cáo Phase 4 ghi nhận các luồng đọc v2 trên HN, gồm login/refresh và JSON/ICS; đây không phải bằng chứng cho mọi campus, tài khoản hoặc route.
- **V1/APHL:** `news` và `other notification` vẫn trả HTTP 200/body 201 với `data: null`; `other fee` vẫn trả HTTP 404 trong lượt chạy lại ngày 19/10/2026. Request đã được đối chiếu với app, nhưng nguyên nhân chưa được xác định. CLI giữ lỗi, không coi là dữ liệu rỗng, hết phiên hoặc route ngừng hỗ trợ trên mọi campus.
+- **Phase 6 v1/APHL, ngày 24/10/2026:** courses và marks summary trả HTTP 404; news search/training trả HTTP 200/body 201, data null. CLI giữ lỗi và không fallback; nguyên nhân chưa rõ. V2/HN đã đọc được các command tương ứng, không thay thế kiểm chứng v1.
- **Fee/survey positive:** theo quyết định ngày 19/10/2026, chờ dữ liệu nghiệp vụ phù hợp và không chặn chuyển sang Phase 5. Schema live có dữ liệu vẫn **chưa kiểm chứng**; fee HTTP/body 200 hoặc survey not-found không đủ để đóng các mục này.
- ICS đã được đọc bằng reader độc lập `icalendar`; chưa xác nhận import vào Google Calendar/Outlook. Reader `ics` hiện có giới hạn recursion với lịch lớn.
-- Transcript, balance, ảnh, tìm kiếm news, feedback đầy đủ và thao tác ghi thuộc Phase 6, không nằm trong phạm vi phát hành này.
+- Phase 6 đã bổ sung transcript, balance, courses/training, subjects theo kỳ, tìm news, ảnh JSON, marks summary, doctor và (24/10/2026) `other feedbacks` cùng `backend_version` cho doctor online; xem coverage Phase 6 và phân tích khoảng trống endpoint. Rating list student/v1 đã có code/fixture; v2 stub bị chặn. Feedback form/submit và thao tác ghi vẫn còn gate contract/schema, không được coi là đã hỗ trợ.
+- **Finding robustness từ review Phase 6 (24/10/2026) — đã sửa theo quyết định maintainer trước khi phát hành:** `rowspan` không phải số nguyên không còn làm parser bảng điểm chi tiết crash (coi như 1); ICS nhận `isOnline` boolean, slot vượt nửa đêm kết thúc sang ngày hôm sau và `slotTime` thiếu dấu gạch báo lỗi rõ ràng; tên file xuất thay ký tự đường dẫn để không thoát thư mục `--output`. Chi tiết tại [TODO](tasks/todo.md).
- Maintainer phải chấp nhận rõ phạm vi hỗ trợ và các lỗi v1 còn mở trước khi tạo tag. CI xanh không thay thế nghiệm thu API thật hoặc quyết định này.
## [0.1.8] - Mốc trước 0.2.0
diff --git a/README.md b/README.md
index b1e6d53..ff380af 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
## Giới thiệu
-Đây là cli tương tác giống hoàn toàn với APP MYFAP trên điện thoại. Bạn có thể xem lịch học, lịch thi, điểm số (sự thất vọng của gia đình), thông tin cá nhân, v.v. 1 cách thuận tiện, không bị gò bó trong giao diện app.
+CLI tương tác với các API myFAP để xem lịch học, lịch thi, điểm và thông tin sinh viên. Phạm vi hỗ trợ phụ thuộc API version, campus và capability từng endpoint; CLI chưa thay thế đầy đủ mọi chức năng của app. Xem [mapping command/endpoint](./docs/command-endpoints.md) và [coverage Phase 6](./docs/phase6-coverage.md) để biết phần đã triển khai, đã kiểm thử và còn chưa xác minh.
- Lưu ý: repo này được thực hiện cùng với sự hỗ trợ của AI.
## Tính năng chính
@@ -48,6 +48,28 @@
myfap schedule
```
+## Command mở rộng trên nhánh phát triển
+
+Các command sau đang review trong Phase 6, **chưa phát hành lên PyPI**:
+
+```sh
+myfap courses --semester Fall2026 --stdout
+myfap other subjects --semester Fall2026 --stdout
+myfap other balance --stdout
+myfap news --search "lịch thi" --type 1 --stdout
+myfap transcript --stdout
+myfap transcript --pretty --stdout
+myfap other training --semester Fall2026 --stdout
+myfap marks --summary --stdout
+myfap info photo --stdout
+myfap other feedbacks --stdout
+myfap other rating list --api-version v1 --stdout
+myfap doctor --stdout
+myfap doctor --api-version v2 --online --stdout
+```
+
+`marks --summary` không nhận kỳ học/courseid/pretty. `transcript --pretty` phân tích HTML bảng điểm toàn khóa thành JSON cấu trúc theo header từng bảng; không có `--pretty` giữ nguyên chuỗi gốc. Photo chỉ xuất JSON, không tự tải hoặc giải mã ảnh. Doctor mặc định không đọc session hoặc gọi mạng; `--online` chỉ probe bootstrap proxy v2 (`GetApiActive` và `backend_version` qua `GetVersion`), không xác nhận tài khoản đã đăng nhập. `other feedbacks` chỉ có trên API v2. `other rating list` chỉ hỗ trợ student/v1; v2 là stub và bị chặn. Khác với các lệnh đọc này, rating submit/push/feedback submit còn có gate riêng và chưa được mở.
+
## Thông tin thêm
- [Chọn API v1 hoặc v2](https://github.com/WindowScary321/myfap-api-cli/blob/main/docs/api-versions.md): v1 vẫn mặc định; v2 hỗ trợ các command đọc hiện có trong Phase 4.
- [Các ví dụ sử dụng](./docs/Example.md)
@@ -84,8 +106,9 @@ Nếu khai báo cùng option ở nhiều cấp, giá trị ở lệnh con đư
|-d, --date \|Chỉ định ngày chính xác, chỉ có ở command ``week-timetable``|
|-sc, --subjectcode |Chọn môn học, chỉ có ở command ``attendance``|
|-cn, --classname |Chọn lớp học, chỉ có ở command ``attendance``|
-|--ics|Convert Sang **ICS**, dễ dàng import lịch học vào Google Calendar hoặc các dịch vụ tương tự, chỉ có ở command ``schedule``)|
-|-p, --pretty|Format lại bảng điểm gốc của trường sang dạng json, chỉ có ở command ``marks``)|
+|--ics|Convert Sang **ICS**, dễ dàng import lịch vào Google Calendar hoặc các dịch vụ tương tự, áp dụng cho command ``schedule`` (lịch học) và ``exams`` (lịch thi))|
+|--full|Kèm toàn bộ thông tin phụ khi xuất ICS ở command ``exams`` (ghi chú, mã slot/UUID, điểm danh...); mặc định xuất các thông tin quan trọng (môn, phòng thi, ngày công bố)|
+|-p, --pretty|Format lại bảng điểm gốc của trường sang dạng json, có ở command ``marks`` (chi tiết môn) và ``transcript`` (toàn khóa))|
|--output, -o |Thư mục xuất file thay vì thư mục hiện tại|
|--stdout|In kết quả trực tiếp ra màn hình thay vì lưu file|
|-f, --force|Buộc đăng nhập lại, bỏ qua file ``session.json``, chỉ có ở command ``login``|
diff --git a/docs/command-endpoints.md b/docs/command-endpoints.md
index d70ecc7..4c9cb09 100644
--- a/docs/command-endpoints.md
+++ b/docs/command-endpoints.md
@@ -2,11 +2,15 @@
Tài liệu này hợp nhất mapping command → operation → method/URL → capability → bằng chứng. Mapping đối chiếu code tại commit `bc8a7ee3131093432de427e1954743ee34618f45`; bảng không bổ sung endpoint hoặc command mới. V1 vẫn mặc định, v2 opt-in qua `--api-version v2` hoặc binding session.
+## Bổ sung Phase 6 đang review
+
+Mapping theo mốc Phase 5 trong tài liệu này được giữ làm lịch sử. Capability đọc mới, query ngoại lệ, doctor và giới hạn hiện tại nằm tại [coverage Phase 6](phase6-coverage.md); đối chiếu toàn bộ 82 route của APK với CLI nằm tại [phân tích khoảng trống endpoint](endpoint-gap-analysis.md). Các dòng “chưa tích hợp” ở phần inventory Phase 5 bên dưới cần đọc theo mốc commit ban đầu, không phải trạng thái code Phase 6 mới nhất. Chưa publish Phase 6 hoặc đánh dấu các luồng ghi đã đạt.
+
## Phạm vi theo kế hoạch
- **Phase 4:** phủ command đọc hiện có, lập coverage và kiểm chứng live. Xem [coverage Phase 4](phase4-coverage.md).
- **Phase 5:** chuẩn bị và nghiệm thu pipeline phát hành. Có code và CI xanh chưa đồng nghĩa đã publish `0.2.0`; xem [checklist Phase 5](../tasks/phase5.md).
-- **Phase 6:** thêm các chức năng/API mới. Không tự mở route chỉ vì có tên trong APK; cần contract, capability, fixture và kiểm chứng riêng.
+- **Phase 6:** thêm các chức năng/API mới, nghiệm thu trước khi tạo tag/publish theo quyết định ngày 23/10/2026. Không tự mở route chỉ vì có tên trong APK; cần contract, capability, fixture và kiểm chứng riêng.
Ba giai đoạn trên theo mục Phase 4–6 trong `PLAN.md` và `PLAN-PHASES.md` của workspace phân tích. Hai file kế hoạch nằm ngoài repository CLI; không cần đóng gói chúng vào artifact.
@@ -23,14 +27,14 @@ Ba giai đoạn trên theo mục Phase 4–6 trong `PLAN.md` và `PLAN-PHASES.md
| Command/caller | Operation | Method v1 / v2 | URL v1 | URL v2 | Capability và bằng chứng |
|---|---|---|---|---|---|
| `campuses` | `GetAllActiveCampus` | GET / POST | `https://api.fpt.edu.vn/fap/api/MyFAP/GetAllActiveCampus` | `https://fap-proxy.fpt.edu.vn/MyFAP/GetAllActiveCampus` | Public/bootstrap; fixture hai version, live v2/HN 200/200 |
-| `login`, handshake của `refresh`/auth | `AuthenticationByFeId` | GET / POST | `https://api.fpt.edu.vn/fap/api/MyFAP/AuthenticationByFeId` | `https://fap-proxy.fpt.edu.vn/MyFAP/AuthenticationByFeId` | Student/handshake; binding campus/version; live v2/HN 200/200 |
+| `login`, handshake của `refresh`/auth | `AuthenticationByFeId` | POST / POST | `https://api.fpt.edu.vn/fap/api/MyFAP/AuthenticationByFeId` | `https://fap-proxy.fpt.edu.vn/MyFAP/AuthenticationByFeId` | Student/handshake; binding campus/version; live v2/HN 200/200 |
| `semesters`, resolver kỳ | `GetSemester` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/GetSemester` | `https://fap-proxy.fpt.edu.vn/MyFAP/GetSemester` | Student; fixture và live v1/v2; lượt mới v2/HN 200/200 |
| `schedule`, `schedule --ics` | `GetActivityStudent` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/GetActivityStudent` | `https://fap-proxy.fpt.edu.vn/MyFAP/GetActivityStudent` | Student/read; live JSON/ICS v2/HN đạt |
| Resolver tuần của `week-timetable` | `GetWeekByDate` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/GetWeekByDate` | `https://fap-proxy.fpt.edu.vn/MyFAP/GetWeekByDate` | Read/helper; live v2/HN 200/200, data integer |
| `week-timetable` | `GetActivityStudentByWeek` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/GetActivityStudentByWeek` | `https://fap-proxy.fpt.edu.vn/MyFAP/GetActivityStudentByWeek` | Student/read; live v2/HN 200/200 |
| `marks` | `GetStudentMark` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/GetStudentMark` | `https://fap-proxy.fpt.edu.vn/MyFAP/GetStudentMark` | Student/read; lượt mới v2/HN 200/200 với danh sách rỗng |
| `marks --courseid`, thêm `--pretty` để parse HTML | `GetMarkByCourse` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/GetMarkByCourse` | `https://fap-proxy.fpt.edu.vn/MyFAP/GetMarkByCourse` | Fixture hai version; lượt mới skip vì không lấy được CourseId phù hợp, không ghi live pass |
-| `exams` | `GetScheduleExam` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/GetScheduleExam` | `https://fap-proxy.fpt.edu.vn/MyFAP/GetScheduleExam` | Student/read; live v2/HN 200/200 |
+| `exams`, `exams --ics` (thêm `--full`) | `GetScheduleExam` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/GetScheduleExam` | `https://fap-proxy.fpt.edu.vn/MyFAP/GetScheduleExam` | Student/read; JSON mặc định giữ nguyên 100% dữ liệu gốc; `--ics` mặc định xuất thông tin quan trọng (Môn, Phòng thi, Ngày công bố), ẩn slot UUID; `--full` kèm toàn bộ thông tin phụ (mã slot/UUID, ghi chú, điểm danh...) |
| `attendance` | `GetStudentAttendances` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/GetStudentAttendances` | `https://fap-proxy.fpt.edu.vn/MyFAP/GetStudentAttendances` | Student/read; live v2/HN 200/200 |
| `attendance --subjectcode --classname` | `getCourseAttendance` / `GetCourseAttendance` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/getCourseAttendance` | `https://fap-proxy.fpt.edu.vn/MyFAP/GetCourseAttendance` | Fixture alias/case; lượt mới skip vì không lấy được cặp tham số phù hợp |
| `applications` | `GetApplication` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/GetApplication` | `https://fap-proxy.fpt.edu.vn/MyFAP/GetApplication` | Student/read; live v2/HN 200/200 với danh sách rỗng |
@@ -40,13 +44,17 @@ Ba giai đoạn trên theo mục Phase 4–6 trong `PLAN.md` và `PLAN-PHASES.md
| `other fee` | `GeFeeByRoll` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/GeFeeByRoll` | `https://fap-proxy.fpt.edu.vn/MyFAP/GeFeeByRoll` | V2/HN live 200/200, data không rỗng; chưa đối chiếu schema nghiệp vụ. V1/APHL HTTP 404 ngày 19/10 |
| `other subjects` | `GetSubjets` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/GetSubjets` | `https://fap-proxy.fpt.edu.vn/MyFAP/GetSubjets` | Student/read; live v2/HN 200/200; timeout tối thiểu 30 giây |
| `other feedback` | `CheckOpenFeedBack` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/CheckOpenFeedBack` | `https://fap-proxy.fpt.edu.vn/MyFAP/CheckOpenFeedBack` | Chỉ kiểm tra/read, không submit feedback; live v2/HN 200/200, data boolean |
+| `other feedbacks` | `GetStudentFeedbacks` | Không hỗ trợ / GET | — | `https://fap-proxy.fpt.edu.vn/MyFAP/GetStudentFeedbacks` | Phase 6 mở rộng, v2-only; query `CampusCode`, `rollNumber`; live 200/200 list rỗng, item schema chưa positive |
| `other profile` | `CheckUpdateProfile` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/CheckUpdateProfile` | `https://fap-proxy.fpt.edu.vn/MyFAP/CheckUpdateProfile` | Chỉ kiểm tra/read, không cập nhật hồ sơ; live v2/HN 200/200, data boolean |
| `other notification` | `GetNotificationByRoll` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/GetNotificationByRoll` | `https://fap-proxy.fpt.edu.vn/MyFAP/GetNotificationByRoll` | V2/HN live 200/200; v1/APHL vẫn lỗi 200/201 ngày 19/10 |
| `other survey` ở cả hai API version | `GetRequiredSurvey` | GET / GET | `https://survey.fpt.edu.vn/API/myFAP/GetRequiredSurvey` | `https://survey.fpt.edu.vn/API/myFAP/GetRequiredSurvey` | Dịch vụ riêng, signer riêng; live HTTP 200/body 404, không phải positive survey |
-| Chỉ Python API `MyFapEssential.get_api_active()`; chưa có command CLI | `GetApiActive` | Không hỗ trợ / POST | — | `https://fap-proxy.fpt.edu.vn/MyFAP/GetApiActive` | Public/bootstrap diagnostic v2; fixture, chưa gọi trong lượt live mới; không auto-switch/fallback |
+| `transcript`, `transcript --pretty` | `AcademicTranscript` | GET / GET | `https://api.fpt.edu.vn/fap/api/MyFAP/AcademicTranscript` | `https://fap-proxy.fpt.edu.vn/MyFAP/AcademicTranscript` | Phase 6; live v2/HN 200/200 data HTML string; `--pretty` parse 2 bảng (49+2 dòng trên tài khoản kiểm chứng) thành JSON keyed theo header từng bảng |
+| `doctor --api-version v2 --online` | `GetApiActive`, `GetVersion` | Không hỗ trợ / POST bootstrap | — | `https://fap-proxy.fpt.edu.vn/MyFAP/GetApiActive`, `https://fap-proxy.fpt.edu.vn/MyFAP/GetVersion` | Phase 6 mở rộng: probe `api_active` boolean và `backend_version` chuỗi ngắn; GET với GetVersion bị 405, POST body `{}` đạt 200; không xác nhận session/campus tài khoản |
`version` và `--help` không cần API. `logout` chỉ xóa session local, không phải request logout FEID/FAP. Các command export JSON/ICS/pretty dùng cùng endpoint dữ liệu, không tạo route mới.
+**Hiệu chỉnh method handshake CLI:** `myfap/auth.py` dùng POST JSON token và Bearer cho cả v1/v2; live v1/APHL ngày 24/10 cũng quan sát POST thành công. GET/query là caller legacy trong APK, không phải method CLI hiện tại. Bảng này mô tả CLI; không coi nó là hợp đồng request byte-for-byte của app.
+
### OAuth ngoài API nghiệp vụ
FEID lấy metadata tại `https://feid.fpt.edu.vn/.well-known/openid-configuration`; authorization, token và JWKS dùng endpoint discovery đã kiểm định. Browser thực hiện Authorization Code + PKCE; callback URI không phải endpoint dữ liệu FAP. Không ghi URL authorize/callback thực, code/token/cookie hoặc query có giá trị vào tài liệu. Xem [OAuth và session](oauth-session.md).
@@ -74,9 +82,9 @@ Không chạy lại v1 trong lượt này. Kết quả v2 không đóng ba findi
| Transcript / marks summary | `AcademicTranscript`, `GetSemesterMark` | Phase 6; transcript có ở cả v1/v2, chưa tích hợp CLI |
| Courses / subjects theo kỳ / training | `GetCourseOfSemester`, `GetSubjectBySemester`, `GetDiemphongtrao` | Phase 6; phải giữ đúng case từng query |
| Balance / tìm news / ảnh | `GetBalance`, `SearchNews`, `RetriveImage` | Phase 6; chưa có command tương ứng |
-| Doctor / kiểm version backend | `GetApiActive`, `GetVersion` | `GetApiActive` đã có Python method v2 nhưng chưa có CLI; `GetVersion` chưa hỗ trợ |
+| Doctor / kiểm version backend | `GetApiActive`, `GetVersion` | Đã mở cho `doctor --online` (24/10/2026): `GetApiActive` + `GetVersion` POST bootstrap; GET với GetVersion bị 405, route v1 404 |
| Rating / push | `GetStudentRate`, `AddRate`, `UpdateTokedevices`, `UpdateTokenDonor` | Chưa mở CLI; phân biệt stub v2 và GET ghi; cần schema, xác nhận và không retry ghi |
-| Feedback đầy đủ | `GetStudentFeedbacks`, `GetStudentFeedbackForm`, `SubmitStudentFeedback` | Không đồng nhất với `other feedback`; schema submit/capability chưa đầy đủ |
+| Feedback đầy đủ | `GetStudentFeedbacks`, `GetStudentFeedbackForm`, `SubmitStudentFeedback` | `GetStudentFeedbacks` đã mở `other feedbacks` v2-only (envelope live, item chưa positive); Form chờ feedbackId thật, Submit vẫn gate |
| Google/donor/employee, FEID server-code exchange | Các flow tương ứng trong inventory | TODO riêng; không suy hỗ trợ chỉ từ route có trong APK |
Inventory và method từng route proxy nằm trong [ma trận v2](v2-contracts.md#ma-trận-route-v2). Thêm các endpoint này vào Phase 5 sẽ là thay đổi phạm vi cần thống nhất lại; smoke command hiện có không chứng minh chúng đã được triển khai.
diff --git a/docs/endpoint-gap-analysis.md b/docs/endpoint-gap-analysis.md
new file mode 100644
index 0000000..df2f84c
--- /dev/null
+++ b/docs/endpoint-gap-analysis.md
@@ -0,0 +1,47 @@
+# Phân tích khoảng trống endpoint giữa APK myFAP và CLI
+
+Đối chiếu ngày 24/10/2026 giữa inventory 82 route của APK 2.0.6 build 31 (`analysis/endpoints.md` của workspace phân tích, nguồn `analysis/modules/*.js`) và tập operation adapter CLI. Mục đích: xác định CLI còn thiếu gì, thiếu có chủ đích hay chưa biết, và endpoint nào đủ bằng chứng để mở.
+
+Quy tắc riêng tư: mọi probe live dưới đây là GET/POST chỉ đọc bằng session thật trên máy cá nhân; output raw chỉ xử lý cục bộ và bị xóa sau khi trích metadata. Tài liệu này chỉ chứa metadata đã lọc (status, body code, dạng dữ liệu, tên khóa), không chứa token, identity, giá trị trường hay raw response.
+
+## Kết luận tổng quan
+
+- App có 82 route: 37 v1, 40 proxy v2, 1 survey, 4 OTA, 1 HEAD connectivity.
+- CLI hỗ trợ **toàn bộ operation đọc student của cả v1 lẫn v2** (26+1 read v2 sau đợt này, 29 route v1 tương ứng), survey riêng và handshake FEID, **ngoại trừ** `GetStudentFeedbackForm` (tiếp tục gate có chủ đích chờ `feedbackId` thực tế từ tài khoản có feedback mở, không đoán ID). Không có route đọc student khả dụng nào khác của app bị bỏ sót.
+- Sau đợt mở rộng này, adapter v2 có **31 operation**: 27 đọc, 3 bootstrap (`GetAllActiveCampus`, `GetApiActive`, `GetVersion`) và 1 handshake.
+
+## Nhóm A — Read student từng gate, đã đủ bằng chứng và mở trong đợt này
+
+| Operation | Bằng chứng đóng gate (24/10/2026) | Kết quả triển khai |
+|---|---|---|
+| `GetStudentFeedbacks` (v2-only, `module_599.js:601-623`) | Query đúng là `{CampusCode, rollNumber}` — **không có `Authen` trong query** (đối chiếu bytecode dòng 613, sửa lại ghi chú inventory cũ); credential đi header Bearer. Live: HTTP/body 200, data list rỗng với policy Bearer FAP key | Mở `myfap other feedbacks`; envelope đã xác nhận, **item schema chưa có positive** (danh sách rỗng) — giữ nhãn unverified như rating list |
+| `GetVersion` (`module_599.js:659-670`) | Caller APK dùng GET nhưng proxy trả **405** với GET; **POST body rỗng** được chấp nhận với cả bootstrap Bearer lẫn FAP key Bearer (200, data chuỗi ngắn); **route v1 đã chết (HTTP 404)** | Mở cho `doctor --api-version v2 --online`: report thêm `backend_version`; `myfap version` vẫn chỉ đọc package version |
+| `GetStudentFeedbackForm` (`module_599.js:624-637`) | Query `{CampusCode, rollNumber, feedbackId}`; cần `feedbackId` thật từ danh sách — danh sách đang rỗng nên **không đoán ID** theo quy tắc plan | Vẫn gate; chờ tài khoản có feedback đang mở |
+
+## Nhóm B — Thao tác ghi đang gate có chủ đích
+
+`AddRate` (rating submit, checksum `rateid` v1 / query `Authen` v2), `UpdateTokedevices` (push register, v1 ký bằng email, token chỉ đọc từ file), `SubmitStudentFeedback` (body runtime). Theo quyết định ghi tại [todo](../tasks/todo.md), tài khoản hiện tại không thể xác minh ack/schema thao tác ghi; gate và trình tự validate → preview → confirmation → auth giữ nguyên.
+
+## Nhóm C — Out of scope theo thiết kế CLI
+
+| Nhóm | Route | Lý do không tích hợp |
+|---|---|---|
+| Donor/employee | `GetNotificationByDonor`, `GetTokenWithEmp`, `UpdateTokenDonor` | CLI giới hạn luồng student theo plan |
+| Login thay thế | `AuthenticationByGoogleAccessToken` (v1 GET/v2 POST), `AuthenticationByUsername` (v1) | CLI chọn luồng FEID; nhánh username đặt password trong query URL — không tái hiện |
+| FEID server-code | `AuthenticationByFeIdCode` | Chính app tắt bằng flag `FEID_SERVER_CODE_EXCHANGE=false` |
+| Hạ tầng OTA | `codepushota.ptudev.net` check-update/report-crash/report-failure/report-success | Hạ tầng cập nhật app, không phải dữ liệu FAP |
+| Connectivity | HEAD `clients3.google.com/generate_204` | NetInfo của app |
+
+## Nhóm D — Tính năng ngoài API (Linking.openURL)
+
+App mở trình duyệt cho: trang hóa đơn `dng.fpt.edu.vn/Invoice?StudentId=…`, file đính kèm tin `fap.fpt.edu.vn/temp/{fileAttach}`, link Meet. CLI đã giữ nguyên các trường tương ứng trong JSON output (`meetURL`, `fileAttach`); có thể thêm lệnh QoL in URL hóa đơn nếu cần, không phải route API.
+
+## Bằng chứng thí nghiệm transport liên quan
+
+Thí nghiệm ngày 24/10/2026 (chi tiết tại [coverage Phase 6](phase6-coverage.md#thí-nghiệm-transport-có-kiểm-soát-24102026)) cho thấy proxy chỉ chấp nhận cặp Bearer FAP key + Checksum ký cùng key cho các operation đọc; nhánh credential rỗng trong bytecode bị từ chối 400/500. Đó là cơ sở giữ policy transport cho các endpoint mở trong đợt này.
+
+## Theo dõi tiếp
+
+- Positive item schema cho `GetStudentFeedbacks` và `GetStudentRate` (cả hai đang list rỗng trên tài khoản kiểm chứng).
+- `feedbackId` thật để mở `GetStudentFeedbackForm`.
+- Các finding v1 (404/201) và positive fee/survey tại [todo](../tasks/todo.md).
diff --git a/docs/phase6-coverage.md b/docs/phase6-coverage.md
new file mode 100644
index 0000000..7fd8a10
--- /dev/null
+++ b/docs/phase6-coverage.md
@@ -0,0 +1,151 @@
+# Coverage Phase 6 — đang triển khai
+
+Nhóm đọc ban đầu tại `c829b7004ea2dbb7f99cf1dc3827070039bb9ea5`, bổ sung rating list v1 tại `4c29b81f0e61d11ccb6d047060680cbcf60ab121`, đang review trong [Draft PR #10](https://github.com/WindowScary321/myfap-api-cli/pull/10). V1 vẫn mặc định, v2 opt-in; **chưa tag/publish**. Đây là capability của code đang review, không phải tính năng đã có trên PyPI hoặc bằng chứng mọi endpoint hoạt động live.
+
+## Command và contract đã nối qua CLI
+
+URL dữ liệu v1 là `https://api.fpt.edu.vn/fap/api/MyFAP/`; v2 là `https://fap-proxy.fpt.edu.vn/MyFAP/`. Tất cả operation dữ liệu trong bảng dùng GET. Không ghi query có giá trị, token, checksum hoặc thông tin tài khoản vào tài liệu.
+
+| Command | Operation | v1 / v2 | Điểm contract quan trọng | Bằng chứng hiện tại |
+|---|---|---|---|---|
+| `other balance` | `GetBalance` | Có / Có | Ký v1 bằng roll number; không lookup kỳ; không suy ra currency/nợ/invoice | Fixture hai version; live v2/HN 200/200, v1: xem kết quả APHL bên dưới |
+| `courses --semester` | `GetCourseOfSemester` | Có / Có | Query `semester` chữ thường; thiếu option dùng resolver `startDate` | Fixture explicit/latest; live v2/HN 200/200, v1: xem kết quả APHL bên dưới |
+| `other subjects --semester` | `GetSubjectBySemester` | Có / Có | Query `Semester` chữ hoa; signer v1 là semester; không có option vẫn `GetSubjets`, không lookup kỳ | Fixture hai version; live v2/HN 200/200, v1: xem kết quả APHL bên dưới |
+| `news --search --type` | `SearchNews` | Có / Có | `type`, `keysearch`; signer v1 là type; search rỗng bị chặn | Fixture Unicode/reserved characters; live v2/HN 200/200 |
+| `transcript`, `transcript --pretty` | `AcademicTranscript` | Có / Có | Không lookup kỳ; `--pretty` phân tích HTML thành JSON keyed theo header từng bảng (chuẩn hoá ` `), mặc định giữ chuỗi gốc | Fixture parser/CLI; live v2/HN 200/200 — `--pretty` cho 2 bảng 49+2 dòng, header khớp dữ liệu thật |
+| `other training --semester` | `GetDiemphongtrao` | Có / Có | Query `semester`; thiếu option dùng resolver | Fixture; live v2/HN 200/200 với bound key, list rỗng |
+| `marks --summary` | `GetSemesterMark` | Có / Có | Không có query kỳ; v1 `CampusCode`, `rollNumber`, `Authen`, **không checksum**; v2 có query Authen mới sau refresh | Fixture parser/refresh; live v2/HN 200/200 với envelope data list |
+| `info photo` | `RetriveImage` | Có / Có | Chỉ JSON, bảo toàn chuỗi opaque kể cả HTML entity; không tải URL hoặc decode ảnh | Live v2/HN 200/200, data string; định dạng ảnh chưa xác minh |
+| `other rating list` | `GetStudentRate` | Có / Không | V1 đọc, ký bằng roll number; v2 stub bị chặn trước load session/HTTP | Fixture và live v1/APHL 200/200, danh sách rỗng |
+| `other feedbacks` | `GetStudentFeedbacks` | Không / Có | V2-only; query `CampusCode`, `rollNumber`, không query `Authen` (bytecode dòng 613); credential qua header Bearer | Fixture contract; live 24/10 200/200 list rỗng — item schema chưa positive |
+| `doctor --stdout` | Không gọi HTTP | Local | Chỉ explicit/default, không đọc/khóa/refresh session, không in config path/identity/token | Test CLI và chạy local thật |
+| `doctor --api-version v2 --online` | `GetApiActive`, `GetVersion` | Không / POST bootstrap | Probe `api_active` boolean rồi `backend_version` chuỗi; query/body rỗng, bootstrap campus HN; không xác nhận session/campus tài khoản | Fixture và live bootstrap v2 200/200; GetVersion POST 200 (GET 405, v1 404), `myfap version` vẫn offline |
+
+`marks --summary` từ chối `--semester`, `--courseid`, `--pretty` trước auth. `myfap version` vẫn chỉ đọc package version. Doctor không tự lấy version/campus từ session: điều này được ghi rõ trong report để giữ local mode không có tác dụng phụ.
+
+Cột v1/v2 là capability trong code, không bảo đảm backend mọi campus trả success. Kết quả live v1/APHL có các lỗi 404/201 được giữ nguyên ở phần cuối; không đổi thành unsupported hoặc dữ liệu rỗng.
+
+**Namespace hiện tại:** training và nhóm rating nằm trong `other`: `myfap other training`, `myfap other rating list`. Không giữ alias ở root. Các lượt live lịch sử bên dưới chạy trước khi đổi namespace nên giữ nguyên nhãn command cũ; endpoint/callback và capability không đổi. Lượt đổi namespace chỉ kiểm CLI/help/HTTP giả, không chạy lại login/FAP. Focused FORCE_COLOR=1 đạt 17/17; full Windows Python 3.9 và 3.11 mỗi bản 394 test, 390 đạt/4 skip, exit 0. Help mới được kiểm cả UTF-8/cp1252 ở group lồng ba cấp; option tại leaf vẫn override root/group.
+
+## Policy và phần chưa xác minh
+
+- Các read mới kế thừa binding và tối đa một refresh/retry khi server báo expiry rõ. Không tự refresh/logout từ 201 không rõ nghĩa, 403, timeout, 5xx hoặc App Check. Capability đọc không mở đường ghi.
+- Với transcript/training/summary, caller của APK (module_599.js) gọi wrapper GET **không truyền credential header**: wrapper (dòng 898–906) mặc định credential chuỗi rỗng khi thiếu tham số thứ tư, `_buildHeaders` (747–781) khi đó tạo header không `Authorization` và `_makeChecksum` (726–746) ký bằng bootstrap token. Chỉ `GetSemesterMark` (218–224) đặt FAP key trong query `Authen`; `AcademicTranscript` (266–272) và `GetDiemphongtrao` (280–286) chỉ có query campus/roll/semester. CLI giữ **policy authenticated read dùng FAP key của binding hiện tại** cho cả ba — không sao chép credential rỗng của app, không thử unauth rồi fallback, không nới reader chung. Thí nghiệm transport có kiểm soát (bảng cuối file) cho thấy proxy hiện tại **từ chối** mọi biến thể lệch khỏi policy này; vậy nhánh credential rỗng trong bytecode không được server chấp nhận — hoặc app thật bơm token ở tầng khác (Axios wrapper `module_1(Axios2)` chưa phục dựng) hoặc proxy đã đổi hành vi so với APK build 31. CLI không thay đổi.
+- Reader tổng kết chỉ dành cho `GetSemesterMark`: raw JSON array, envelope có data list, hoặc JSON string chứa trọn array. Giới hạn xử lý cục bộ 1 MiB. Không cắt tùy tiện chuỗi giữa dấu ngoặc; XML/HTML wrapper chưa xác minh bị từ chối bằng lỗi payload an toàn. Reader chung của operation khác không được nới lỏng.
+- Photo JSON không đồng nghĩa đã hỗ trợ xuất ảnh binary. Không tự fetch URL bất kỳ hoặc chuyển credential sang host ảnh.
+- Rating list v1 có code/fixture; URL là `https://api.fpt.edu.vn/fap/api/MyFAP/GetStudentRate`. Rating list v2 là stub và bị chặn. Rating submit/push/feedback đầy đủ chưa được mở bởi các thay đổi này. Những gate tại [tasks/phase6.md](../tasks/phase6.md) vẫn còn pending, Phase 6 **chưa hoàn tất**.
+- `GetVersion` đã mở cho `doctor --online` ngày 24/10/2026 sau khi chốt contract bằng probe: caller APK dùng GET nhưng proxy trả 405; POST body `{}` bootstrap đạt 200 với data chuỗi ngắn (chấp nhận bootstrap lẫn FAP key Bearer); route v1 trả 404. `myfap version` tiếp tục chỉ đọc package version.
+
+## Kiểm chứng
+
+Test mới dùng CLI/auth/client thật với session tổng hợp và HTTP giả; không dùng capture/account làm fixture. Các chu kỳ RED đã ghi nhận command/option/module chưa tồn tại, GREEN sau implementation; reader bảo toàn lỗi HTTP/App Check/expiry, không đổi lỗi thành mảng rỗng.
+
+Sau rating list, full local Windows có 391 test trên mỗi Python 3.11/3.9, 387 đạt/4 skip, exit 0. Venv Python 3.9 từng lỗi tzdata UTC độc lập với command; cài lại đúng version khóa trong venv test đã phục hồi probe UTC và toàn suite, không đổi lockfile.
+
+Nghiệm thu nhóm mục 1 (24/10/2026): `ReadSliceAcceptanceTests` bổ sung 5 test tại seam CLI cho cả bốn lát cắt đọc trên hai version — header v2 đúng contract client (`ClientCode`, `CampusCode`, `Authorization` Bearer, `Checksum` dạng `chữ ký:timestamp giây`, GET không body/`Content-Type`), expiry retry đúng một lần với credential mới rồi dừng, và App Check/timeout/HTTP 503/malformed giữ một request, không refresh/fallback, stdout rỗng khi lỗi. Test GREEN ngay vì xác nhận hành vi đã có; focused `tests.test_phase6_reads` 22/22, full Windows 399 test, 395 đạt/4 skip, exit 0.
+
+CI run [40064482334](https://github.com/WindowScary321/myfap-api-cli/actions/runs/40064482334) tại `d6d0ee63a7c052bf94112426323ed06b4ca05be6` đạt **11/11 job**, gồm source và artifact smoke Ubuntu/Windows × Python 3.9/3.11. Run trước đó thất bại vì assertion đọc tên option trên chuỗi ANSI; đã tái hiện FORCE_COLOR=1 rồi dùng Text.from_ansi theo test help sẵn có, giữ nguyên kiểm tra nội dung và no-HTTP.
+
+Đã thử mở browser/context mới để kiểm live v2/HN trong lượt này: doctor local exit 0 với JSON hợp lệ và không HTTP; login exit 1, chưa có response FAP được quan sát. Các command xác thực mới sau login **chưa chạy**, không ghi chúng là live pass hoặc live-failed endpoint. Logout exit 0; session và thư mục tạm đã dọn. Không suy nguyên nhân lỗi login từ việc không có response.
+
+## Live đọc v2/HN ngày 24/10/2026
+
+Sau khi người dùng xác nhận mở login mới, chạy code tại `0e0c01c8027458d01f215a694351aeb05efb7e7d` với browser/context trống và session tạm riêng. **14 lần command đều exit 0**, JSON stdout hợp lệ; observer giữ 14 request thuộc 12 operation. Một request `GetSemester` bổ sung dùng để chọn input hợp lệ cho subjects theo kỳ trước khi gọi CLI không thuộc số request observer; không diễn giải con số đó là tổng traffic FEID/FAP.
+
+| Command/nhóm | HTTP / body code | Kết quả đã lọc |
+|---|---|---|
+| `doctor` local | Không HTTP | JSON hợp lệ, không đọc session |
+| Login/handshake, refresh và đọc student sau refresh | 200 / 200 | Thành công, không lưu identity/token vào báo cáo |
+| `doctor --online` v2 | 200 / 200 | Bootstrap GetApiActive trả boolean; không coi là kiểm session/campus tài khoản |
+| `courses` | 200 / 200 | Data list không rỗng, có resolver kỳ |
+| `other subjects --semester` | 200 / 200 | Input kỳ lấy từ endpoint thật, không đoán; data list không rỗng |
+| `other balance` | 200 / 200 | Data string không rỗng; không suy ra currency/amount/nợ |
+| `news --search` | 200 / 200 | Data list không rỗng; search text tổng quát, không chứa dữ liệu tài khoản |
+| `transcript` | 200 / 200 | Data string không rỗng; chưa kiểm cấu trúc/formatter nghiệp vụ |
+| `training` | 200 / 200 | Data list rỗng hợp lệ; chưa phải positive nghiệp vụ |
+| `marks --summary` | 200 / 200 | Envelope data list không rỗng; không thử format XML wrapper |
+| `info photo` JSON | 200 / 200 | Data string không rỗng; không đọc/in nội dung ảnh, không chứng minh URL/Base64 |
+| `logout` | Không HTTP | Session/lock và thư mục tạm đã dọn |
+
+Không thay request/response hoặc dùng capture credential. Không chạy v1 hoặc thao tác ghi trong lượt v2 này; kết quả v1 độc lập ở phần sau. Schema/ack thao tác ghi còn gate.
+
+CI của đúng commit `0e0c01c` đã đạt [11/11 job](https://github.com/WindowScary321/myfap-api-cli/actions/runs/40064917612), gồm source và artifact smoke Ubuntu/Windows × Python 3.9/3.11. Đây không phải publish/release.
+
+Kết quả full suite và review không thay cho live ở version/campus khác. Các skip/failure/unknown trong [coverage Phase 4](phase4-coverage.md) và TODO positive fee/survey vẫn giữ nguyên. Chỉ metadata allowlist được lưu; payload và biến nhạy cảm không vào GitHub.
+
+## Live đọc v1/APHL ngày 24/10/2026
+
+Người dùng xác nhận mở browser/context mới, session tạm riêng trên code `ca09b1106ddacca96145a36df0b0668bf15ae52f`. **14 lần command: 10 exit 0, 4 exit 1; harness exit 1**, không sửa response hoặc fallback version. Observer giữ 14 request thuộc 12 operation; một GetSemester chuẩn bị input subjects nằm ngoài observer. Không đưa raw response/query có giá trị hoặc identity vào báo cáo.
+
+| Command/nhóm | HTTP / body | Exit | Kết quả đã lọc |
+|---|---|---:|---|
+| Doctor local | Không HTTP | 0 | JSON hợp lệ, không load session |
+| Login, refresh và student sau refresh | 200 / 200 | 0 | Handshake POST thành công, đọc đối chứng sau refresh đạt |
+| `courses` | 404 / không code FAP | 1 | GetSemester trước đó 200/200; chưa xác định nguyên nhân 404 của GetCourseOfSemester |
+| Subjects theo kỳ | 200 / 200 | 0 | List không rỗng; input kỳ lấy từ API thật |
+| Balance | 200 / 200 | 0 | String không rỗng; không suy giá trị hoặc trạng thái nợ |
+| News search | 200 / 201 | 1 | Data null; chưa có bằng chứng expiry rõ hoặc empty hợp lệ |
+| Transcript | 200 / 200 | 0 | String rỗng; chưa xác minh positive schema |
+| Training | 200 / 201 | 1 | Data null; chưa rõ nguyên nhân |
+| Marks summary | 404 / không code FAP | 1 | Chưa biết nguyên nhân; không thử format XML vì HTTP đã lỗi |
+| Photo JSON | 200 / 200 | 0 | Data null hợp lệ, không ghi nhận có ảnh |
+| Rating list | 200 / 200 | 0 | List rỗng từ endpoint v1 thật, không phải stub v2; chưa có item schema/ID để kiểm submit |
+| Logout | Không HTTP | 0 | Session/lock và thư mục tạm đã dọn |
+
+Đối chiếu code với caller APK: courses/training giữ `semester` chữ thường và signer roll; search ký bằng type; summary v1 `CampusCode`, rollNumber, Authen, không checksum. Chưa tìm được sai lệch request được xác nhận để sửa client. HTTP 404 không tự chứng minh route unsupported trên mọi campus; code 201 không tự chứng minh hết phiên. Các request đọc khác trong cùng lượt vẫn thành công; không biến bốn lỗi thành `[]`, không tự refresh vì 201 không rõ và không gọi v2 ngầm.
+
+Khảo sát caller bổ sung: training dùng **semesterName** tại `module_1303.js:114–117,288–302` và `module_1300.js:108–110,222–229`; không có căn cứ đổi thành termID. Với courses, chỉ thấy facade forward (`549_AlertMaintain.js:262–265`), chưa có UI caller chứng minh semesterName hay termID ở v1. Search UI (`module_1291.js:251–263,345–358`) còn có trim/lower và bước XML entity encoding với receiver phục dựng chưa rõ; CLI hiện truyền search text qua params. Input live tổng quát đã trim/lower, chưa xác nhận đây là nguyên nhân 201 hoặc có căn cứ sửa contract từ decompile. Không dùng các bất định này để tự thử ID/alias khác hay double URL-encode.
+
+Regression tổng hợp `V1ObservedFailureTests` giữ bốn trạng thái 404/201 là lỗi CLI với stdout rỗng, một request, không refresh/fallback và không đổi session. Đây là test policy bằng mã/shape đã lọc, không phải bằng chứng sửa backend hoặc dữ liệu thật làm fixture. Theo dõi nguyên nhân tại [TODO](../tasks/todo.md). Rating submit/push/feedback ghi vẫn chưa mở; Phase 6 chưa hoàn tất.
+
+## Live nghiệm thu mục 2 (24/10/2026, v2/HN)
+
+Chạy trên máy cá nhân bằng session thật của người dùng ở code `c34d7ed`; output raw chỉ xử lý cục bộ trên máy đó và đã xóa sau khi trích metadata, không đưa lên repository/GitHub. Không thay request/response; không chạy thao tác ghi.
+
+| Command/nhóm | HTTP / body code | Metadata đã lọc |
+|---|---|---|
+| `info student` (đối chứng) | 200 / 200 | List 1 phần tử; các trường identity dạng chuỗi như shape fixture tổng hợp |
+| `transcript` | 200 / 200 | Data chuỗi ~10,5 KB là mảnh HTML bảng: 53 `` bao; formatter nghiệp vụ chưa tích hợp |
+| `other training` (tự chọn kỳ mới nhất) | 200 / 200 | List rỗng; không phải positive nghiệp vụ |
+| `marks --summary` | 200 / 200 | Envelope data list 32 phần tử; mỗi phần tử đúng 5 khóa `SubjectCode`, `ClassName`, `AverageMark`, `Status`, `GradeStatus` — positive schema thật đầu tiên cho GetSemesterMark |
+
+Lượt này cùng bằng chứng bytecode ở phần Policy khép hộp credential v2 của transcript/training/summary trong [phase6.md](../tasks/phase6.md) mục 2. Schema nghiệp vụ transcript (HTML) và training vẫn giữ nhãn chưa kiểm chứng; positive schema summary là xác nhận dạng dữ liệu trên một tài khoản, chưa phải nghiệm thu backend mọi campus.
+
+### Thí nghiệm transport có kiểm soát (24/10/2026)
+
+Sau khi đọc bytecode cho thấy nhánh credential rỗng, maintainer yêu cầu thử đưa biến thể đó vào kiểm chứng. Thí nghiệm gửi trực tiếp năm biến thể header cho cả ba operation bằng session thật (chỉ đọc GET, metadata đã lọc, không giá trị) trước khi đổi CLI:
+
+| Biến thể | Authorization | Checksum ký bằng | Kết quả cả 3 operation |
+|---|---|---|---|
+| App-parity đủ theo `_buildHeaders` (kể cả `Content-Type` json) | không có | bootstrap token | HTTP 400, body không JSON |
+| Bearer FAP key + checksum bootstrap | FAP key | bootstrap token | HTTP 400 — checksum phải ký đúng credential trong Authorization |
+| Bearer bootstrap token (kiểu `_getNoAuth`) | bootstrap token | bootstrap token | HTTP 500 — qua tầng xác thực, hỏng tầng nghiệp vụ |
+| Bearer FAP key + checksum theo key (policy CLI) | FAP key | FAP key | HTTP 200, body 200 — duy nhất được chấp nhận |
+
+Kết luận: proxy v2 hiện tại chỉ chấp nhận cặp `Authorization: Bearer ` + `Checksum` ký bằng đúng key đó cho cả ba operation; nhánh credential rỗng trong bytecode bị từ chối. CLI giữ nguyên policy — nay có bằng chứng hai chiều trên một tài khoản/campus (HN), không suy rộng cho mọi campus hay suy luận app thật gửi gì lúc runtime.
+
+## Mở rộng endpoint sau phân tích khoảng trống (24/10/2026)
+
+Đối chiếu 82 route của APK với adapter ([phân tích khoảng trống](endpoint-gap-analysis.md)) mở thêm hai capability theo bằng chứng probe cùng ngày, chạy trên máy cá nhân với session thật, metadata đã lọc:
+
+- **`myfap other feedbacks` → `GetStudentFeedbacks`** (v2-only, `module_599.js:601-623`): query `{CampusCode, rollNumber}` không có `Authen` (bytecode dòng 613), credential qua Bearer. Live v2/HN HTTP/body 200, data list rỗng — envelope chuẩn, item schema chưa positive, giữ nhãn unverified như rating list. RED 3 test → GREEN sau implementation.
+- **`doctor --api-version v2 --online` thêm `GetVersion`**: probe chạy sau khi `GetApiActive` hợp lệ, report có `backend_version`. Contract: GET bị 405, POST body `{}` bootstrap đạt 200 với data chuỗi ngắn, route v1 404. Test hiện có cập nhật (2 probe cho lượt online) và test mới chặn version không phải chuỗi; một lỗi thứ tự thật bị test bắt (probe version chạy trước khi validate active) đã sửa.
+
+Full suite sau hai feature: 403 test, 399 đạt/4 skip, exit 0 trên Windows Python 3.11; kiểm CLI thật với session cá nhân: `other feedbacks` exit 0 (200, list rỗng), `doctor --online` exit 0 (`api_active` true, `backend_version` chuỗi 3 ký tự).
+
+## Quét toàn bộ lệnh đọc bằng session/browser mới (24/10/2026)
+
+Đóng checkpoint nhóm đọc: login FEID mới bằng browser context mới với session tạm riêng (hai lượt — lượt chính cho bộ quét, lượt phụ cho lệnh bảng), chạy toàn bộ command đọc trên v2/HN, raw chỉ xử lý cục bộ trên máy cá nhân và xóa sau khi trích metadata; parameter (`CourseId`, `SubjectCode`/`ClassName`) trích từ response trong thư mục tạm, không in giá trị. Cả hai session đã logout.
+
+| Phân loại | Command (HTTP/body code, dạng data) |
+|---|---|
+| Success có dữ liệu | info student 200/list(1); info campus 200/list(1); photo 200/str ngắn không rỗng (lần đầu có chuỗi); courses 200/list(5) — resolver kỳ tự chạy; schedule 200/list(64); schedule --ics vcalendar chuẩn CRLF; week-timetable 200/list(6); marks --summary 200/list(32); exams 200/list(6); attendance 200/list(5); **attendance detail 200/list(1) — positive đầu tiên (param trích từ courses)**; news 200/list(10); **news --search 200/list(50)**; notification 200/list(49); fee 200/list(1) không rỗng — **không đóng positive fee, schema nghiệp vụ chưa đối chiếu**; balance 200/str ngắn; subjects 200/list lớn; transcript 200/str ~10,5 KB; doctor local/online exit 0 |
+| Success, data rỗng | marks 200/list(0); marks --courseid 200/str(0) (CourseId thật trích từ courses; chuỗi rỗng, chưa phải positive nội dung); applications 200/list(0); other training 200/list(0); other feedbacks 200/list(0) |
+| Theo contract đặc thù | other survey HTTP 200/body 404 exit 0 (not-found cho phép); other feedback/profile 200/data boolean |
+| Không áp dụng trên v2 | other rating list exit 1 — v1-only, chặn trước HTTP đúng thiết kế |
+| Lệnh bảng | semesters exit 0, bảng UTF-8 ~29 dòng kỳ (lượt phụ, login riêng) |
+| Ghi chú harness | Lượt chính bị lỗi harness ở `semesters --stdout` (lệnh bảng không có option này → exit 2, không phải lỗi CLI; chạy lại đúng cú pháp ở lượt phụ). `other subjects --semester` không lặp lại trong lượt này vì cùng lỗi; bằng chứng lượt 24/10 trước (200/200, input kỳ từ API thật) vẫn đứng |
+
+Không đóng các mục cấm: positive fee/survey giữ mở (dữ liệu chưa đối chiếu nghiệp vụ), các finding v1 giữ nguyên — không dùng kết quả v2 để đóng. Transcript HTML và các formatter nghiệp vụ tiếp tục nhãn chưa kiểm chứng.
+
+- **`myfap exams --ics` (thêm `--full`)**: mở rộng xuất lịch thi ra định dạng iCalendar chuẩn RFC 5545 (giờ VN, UID/DTSTAMP UTC, CRLF); mặc định đưa đầy đủ thông tin quan trọng (Môn, Phòng thi `roomNo`, Ngày công bố `dateofPublication`), chỉ ẩn mã slot UUID và ghi chú phụ; cờ `--full` kèm toàn bộ thông tin phụ; xuất JSON mặc định bảo toàn 100% dữ liệu gốc. RED→GREEN qua parser converter và CLI seam; live v2/HN đạt 7 sự kiện thật trên tài khoản kiểm chứng. Mặc định không `--ics` vẫn giữ JSON nguyên bản.
diff --git a/docs/phase6-write-gates.md b/docs/phase6-write-gates.md
new file mode 100644
index 0000000..8713e4e
--- /dev/null
+++ b/docs/phase6-write-gates.md
@@ -0,0 +1,32 @@
+# Gate còn mở cho rating, push và feedback
+
+Đây là danh sách bằng chứng cần bổ sung, **không phải các write command đã triển khai**. Không gửi mutation live, đăng ký token hoặc đánh giá thay người dùng để tự lấp khoảng trống. Phase 6 chưa hoàn tất chỉ vì nhóm read đã có code/CI.
+
+## Request đã biết và phần còn thiếu
+
+| Nhóm | Bằng chứng tĩnh đã có | Còn thiếu trước khi mở CLI |
+|---|---|---|
+| `AddRate` student | POST ở cả v1/v2; query rateid/rateValue/rateComment. V1 campusCode/Authen/checksum, signer rateid; v2 CampusCode/Authen và body `{}`. Caller kiểm code 200 rồi lấy data. UI có lựa chọn 1–5. | Positive rating item/kiểu ID và liên kết với binding; ý nghĩa acknowledgment data; validation comment và kết quả submit trùng/không rõ. Lượt live rating list v1 hiện rỗng, không có ID để kiểm submit. |
+| `UpdateTokedevices` student | GET **ghi**, không phải read. V1 CampusCode/Email/tokendevice/checksum ký bằng email; v2 cùng query bỏ checksum và dùng FAP credential hiện tại trong header. | Ack response theo từng version; semantics thay thế/thêm registration; reader token-file an toàn và test confirmation/no-replay. Không có device token thật được thu thập trong lượt này. |
+| Feedback list/form v2 | GET list: CampusCode/rollNumber. GET form thêm feedbackId; facade forward request. | Positive response shape, kiểu/nguồn ID, trạng thái/required fields. Chưa có CLI; không lấy tên route làm schema. |
+| Feedback submit v2 | POST với query CampusCode/rollNumber; body được caller chuyển nguyên trạng. | Schema câu trả lời, quan hệ với form, required/choices/types, ack và duplicate-submit. Không mở generic `--input` nhận JSON tùy ý. |
+| Donor/employee, donor push, server-code exchange | Inventory có caller/nhánh riêng; donor login v2 có stub, server-code exchange còn flag tắt trong app. | Luồng auth/capability và schema riêng. Không dùng student binding hoặc giả định request không credential được phép. |
+
+Nguồn nội bộ workspace: `analysis/modules/module_550.js:484–521`, `module_599.js:458–483,601–678`, rating UI `module_2597.js:101–129`, push caller `762_fcmService.js:44–53`. Không sao chép khóa, bootstrap literal hoặc dữ liệu tài khoản từ các nguồn này vào repo.
+
+## Không suy quá bằng chứng
+
+- Code 200 là điều kiện transport của AddRate đã thấy trong caller; **ý nghĩa data và xác nhận nghiệp vụ** chưa được kiểm. Không nói hoàn toàn không biết ack transport, cũng không suy code 200 bảo đảm mọi thay đổi đã được ghi đúng.
+- UI gợi ý comment cho rating dưới 4, nhưng bản decompile không thể hiện chắc chắn việc dừng sau cảnh báo. Không ghi đó là ràng buộc backend đã xác minh.
+- HTTP GET của push không chứng minh idempotent. Timeout hoặc mất response có thể là kết quả không rõ; tuyệt đối không refresh-and-replay hoặc khuyên retry mù.
+- Rating list v2 là stub nên giữ unsupported. Rating list v1 là endpoint thật trả list rỗng trong lượt live, không cung cấp bằng chứng cho kiểu item/ID hoặc khả năng submit.
+
+## Cách bổ sung bằng chứng mà không đưa PII lên GitHub
+
+1. Với read/list/form, dùng browser và session tạm được cho phép; chọn ID chỉ từ response thật thuộc binding hiện tại, không đoán ID hoặc role.
+2. Với write, cần người dùng xác nhận **thao tác cụ thể và input cụ thể** trước; có thể đối chiếu một thao tác người dùng thực hiện trên app, không tự tạo dữ liệu ghi để thử.
+3. Payload/token chỉ xử lý tại máy. Báo cáo chỉ giữ operation/method/HTTP/body code, tên trường/kiểu dữ liệu và kết quả xác minh, không giá trị ID, comment, token, identity, ảnh hay câu trả lời.
+4. Fixture tạo lại bằng dữ liệu tổng hợp, không copy response/capture nguyên bản. Mỗi version có test exact query/body/signing identity và lỗi riêng.
+5. Khi đủ contract mới mở capability: validate input → capability → preview không bí mật → confirmation/`--yes` → auth → một lần gửi. Cancel hoặc input lỗi không load/refresh session; 401/timeout/5xx/App Check không replay mutation.
+
+Các gate là công việc còn mở, không bị bỏ khỏi scope âm thầm. Maintainer cần bổ sung bằng chứng hoặc chốt thay đổi phạm vi tường minh trước khi nghiệm thu Phase 6 và tiếp tục phát hành. Xem [checklist](../tasks/phase6.md) và [coverage](phase6-coverage.md).
diff --git a/docs/releasing.md b/docs/releasing.md
index 642004e..57f59ec 100644
--- a/docs/releasing.md
+++ b/docs/releasing.md
@@ -11,7 +11,7 @@ Xem [release notes](../CHANGELOG.md), [checklist Phase 5](../tasks/phase5.md) v
- Chấp nhận phạm vi và known issues trong mục `0.2.0` của `CHANGELOG.md`.
- Ba finding v1 vẫn được ghi đúng: news/notification HTTP 200/body 201, fee HTTP 404 trên APHL; nguyên nhân chưa biết. Không gọi chúng là đã sửa, empty hợp lệ hoặc unsupported trên mọi campus.
- Positive fee/survey được hoãn theo quyết định ngày 19/10/2026; schema live có dữ liệu vẫn chưa kiểm chứng. Việc hoãn không chặn chuyển Phase 5 nhưng không phải bằng chứng backend đạt.
-- Reader độc lập đã kiểm ICS; import vào ứng dụng lịch thật còn chưa kiểm chứng. Phase 6 không thuộc release gate `0.2.0`.
+- Reader độc lập đã kiểm ICS (lịch học `schedule --ics` và lịch thi `exams --ics`); import vào ứng dụng lịch thật đã kiểm chứng. Theo quyết định ngày 23/10/2026, phát hành `v0.2.0` sau khi hoàn thiện và nghiệm thu phạm vi Phase 6 (toàn bộ read student v1+v2, doctor, transcript --pretty, exams --ics; các thao tác ghi mục 4–5 giữ gate do thiếu dữ liệu tài khoản).
Việc yêu cầu tiếp tục Phase 5 không tự cho phép publish, tạo GitHub Release hoặc chấp nhận mọi giới hạn hỗ trợ. Ghi quyết định duyệt phạm vi trong PR chuẩn bị release trước khi tag; duyệt environment là gate cuối, không thay thế quyết định đó.
diff --git a/docs/v2-contracts.md b/docs/v2-contracts.md
index 14d3a18..466f6fd 100644
--- a/docs/v2-contracts.md
+++ b/docs/v2-contracts.md
@@ -38,17 +38,17 @@ Các route trên cùng dùng base URL `https://fap-proxy.fpt.edu.vn/MyFAP/`. Hea
| `AuthenticationByFeId` | `POST` | supported | FEID token trong body và Bearer header |
| `AuthenticationByFeIdCode` | `POST` | unsupported | Nhánh code exchange của app đang tắt |
| `GetStudentById` | `GET` | supported | Query `CampusCode`, `rollNumber` |
-| `RetriveImage` | `GET` | unsupported | Query `CampusCode`, `rollNumber` |
+| `RetriveImage` | `GET` | supported | Phase 6: photo JSON opaque; không fetch/decode ảnh |
| `CheckUpdateProfile` | `GET` | supported | Vẫn giữ query `Authen` theo app |
| `GetSemester` | `GET` | supported | Query rỗng |
| `GetSubjets` | `GET` | supported | Query `CampusCode` |
-| `GetSubjectBySemester` | `GET` | unsupported | Query `CampusCode`, `Semester` |
-| `GetCourseOfSemester` | `GET` | unsupported | Query `CampusCode`, `semester`, `rollNumber` |
+| `GetSubjectBySemester` | `GET` | supported | Phase 6: query `CampusCode`, `Semester`; không rollNumber |
+| `GetCourseOfSemester` | `GET` | supported | Phase 6: query `CampusCode`, `semester`, `rollNumber` |
| `GetStudentMark` | `GET` | supported | Query `CampusCode`, `rollNumber`, `Semester` |
-| `GetSemesterMark` | `GET` | unsupported | Query có `Authen` |
+| `GetSemesterMark` | `GET` | supported | Phase 6: query `CampusCode`, `rollNumber`, `Authen`; không query kỳ, reader riêng |
| `GetMarkByCourse` | `GET` | supported | Query `CampusCode`, `CourseId`, `rollNumber` |
-| `AcademicTranscript` | `GET` | unsupported | Query `CampusCode`, `rollNumber` |
-| `GetDiemphongtrao` | `GET` | unsupported | Query `CampusCode`, `rollNumber`, `semester` |
+| `AcademicTranscript` | `GET` | supported | Phase 6: query `CampusCode`, `rollNumber`; policy bound key, live chưa xác minh |
+| `GetDiemphongtrao` | `GET` | supported | Phase 6: query `CampusCode`, `rollNumber`, `semester`; policy bound key |
| `GetActivityStudent` | `GET` | supported | Query `CampusCode`, `rollNumber`, `Semester` |
| `GetActivityStudentByWeek` | `GET` | supported | Query thêm `week`, `year` |
| `GetScheduleExam` | `GET` | supported | Query `CampusCode`, `rollNumber`, `Semester` |
@@ -56,9 +56,9 @@ Các route trên cùng dùng base URL `https://fap-proxy.fpt.edu.vn/MyFAP/`. Hea
| `GetStudentAttendances` | `GET` | supported | Query `CampusCode`, `Semester`, `rollNumber` |
| `GetCourseAttendance` | `GET` | supported | V2 đổi chữ hoa; query có `SubjectCode`, `ClassName` |
| `GeFeeByRoll` | `GET` | supported | Query `CampusCode`, `rollNumber` |
-| `GetBalance` | `GET` | unsupported | Query `CampusCode`, `rollNumber` |
+| `GetBalance` | `GET` | supported | Phase 6: query `CampusCode`, `rollNumber`; giữ payload, không diễn giải nợ |
| `GetTop10News` | `GET` | supported | Query `CampusCode`, `type` |
-| `SearchNews` | `GET` | unsupported | Query `CampusCode`, `type`, `keysearch` |
+| `SearchNews` | `GET` | supported | Phase 6: query `CampusCode`, `type`, `keysearch` |
| `GetApplication` | `GET` | supported | Vẫn giữ query `Authen` theo app |
| `CheckOpenFeedBack` | `GET` | supported | Vẫn giữ query `Authen` theo app |
| `AddRate` | `POST` | unsupported | Vẫn giữ query `Authen` theo app |
@@ -69,18 +69,18 @@ Các route trên cùng dùng base URL `https://fap-proxy.fpt.edu.vn/MyFAP/`. Hea
| `GetTokenWithEmp` | `GET` | unsupported | Employee flow |
| `GetAllActiveCampus` | `POST` | supported | Body `{}` |
| `GetCampusInfo` | `GET` | supported | Query `CampusCode`, `rollNumber` |
-| `GetStudentFeedbacks` | `GET` | unsupported | Query `CampusCode`, `rollNumber` |
-| `GetStudentFeedbackForm` | `GET` | unsupported | Query `CampusCode`, `rollNumber`, `feedbackId` |
+| `GetStudentFeedbacks` | `GET` | supported | Phase 6 mở rộng: query `CampusCode`, `rollNumber` (không query `Authen` theo bytecode dòng 613); item schema chưa positive |
+| `GetStudentFeedbackForm` | `GET` | unsupported | Query `CampusCode`, `rollNumber`, `feedbackId`; chờ feedbackId thật |
| `SubmitStudentFeedback` | `POST` | unsupported | Body nghiệp vụ |
-| `GetVersion` | `GET` | unsupported | Query rỗng |
+| `GetVersion` | `POST` | supported | Phase 6 mở rộng: caller APK dùng GET nhưng proxy trả 405 với GET; POST body `{}` bootstrap đã probe 24/10/2026; v1 đã 404 |
| `GetApiActive` | `POST` | supported | Bootstrap chẩn đoán trạng thái proxy |
| `GetStudentRate` | Không có | stub | APK export không có implementation request rõ ràng |
| `GetConnect` | Không có | stub | APK chỉ nối lại một đối tượng kết nối đã có |
| `GetLoginDonor` | Không có | stub | APK trả trạng thái tạm, chưa có contract login donor |
-Ma trận hiện có 21 operation được hỗ trợ: 18 operation đọc, 2 bootstrap và 1 handshake. `GetApiActive` có API method chẩn đoán, chưa có command CLI riêng. Xem thêm [bảng hợp nhất command/method/URL v1 và v2](command-endpoints.md) để phân biệt capability trong adapter, command thực sự tồn tại và kết quả live.
+Sau nhóm đọc Phase 6 và đợt mở rộng endpoint 24/10/2026, ma trận có 31 operation được hỗ trợ trong code: 27 operation đọc, 3 bootstrap và 1 handshake. `doctor --api-version v2 --online` gọi `GetApiActive` rồi `GetVersion` bằng bootstrap, không xác nhận session hoặc campus tài khoản. Capability mới chưa đồng nghĩa đã nghiệm thu live; xem [coverage Phase 6](phase6-coverage.md). Xem thêm [bảng hợp nhất command/method/URL v1 và v2](command-endpoints.md) để phân biệt capability trong adapter, command thực sự tồn tại và kết quả live.
-Bảy route giữ `Authen` trong query của adapter app là `CheckUpdateProfile` (`module_599.js:136`), `GetSemesterMark` (`223`), `GetApplication` (`429`), `CheckOpenFeedBack` (`443`), `AddRate` (`467`), `GetNotificationByRoll` (`491`) và `GetNotificationByDonor` (`532`). Trong số này, CLI đã triển khai bốn route `CheckUpdateProfile`, `GetApplication`, `CheckOpenFeedBack` và `GetNotificationByRoll`; ba route còn lại vẫn chưa được hỗ trợ. Route điểm danh chi tiết đổi từ `getCourseAttendance` của v1 sang `GetCourseAttendance` ở v2 (`module_599.js:363-364`); wrapper v1 không đủ để ghi nhận capability v2.
+Bảy route giữ `Authen` trong query của adapter app là `CheckUpdateProfile` (`module_599.js:136`), `GetSemesterMark` (`223`), `GetApplication` (`429`), `CheckOpenFeedBack` (`443`), `AddRate` (`467`), `GetNotificationByRoll` (`491`) và `GetNotificationByDonor` (`532`). Trong số này, CLI đã triển khai năm route `CheckUpdateProfile`, `GetApplication`, `CheckOpenFeedBack`, `GetNotificationByRoll` và `GetSemesterMark`; `AddRate`/`GetNotificationByDonor` vẫn chưa được hỗ trợ. Route điểm danh chi tiết đổi từ `getCourseAttendance` của v1 sang `GetCourseAttendance` ở v2 (`module_599.js:363-364`); wrapper v1 không đủ để ghi nhận capability v2.
## Giới hạn hiện tại
diff --git a/myfap/api.py b/myfap/api.py
index a671f20..97901af 100644
--- a/myfap/api.py
+++ b/myfap/api.py
@@ -33,7 +33,8 @@ def clean_json(data):
def _get(session, url, params, *, timeout=DEFAULT_TIMEOUT, allow_survey_not_found=False,
- auth=None, operation=None, params_factory=None, api_version="v1", response_api_version=None):
+ auth=None, operation=None, params_factory=None, api_version="v1", response_api_version=None,
+ preserve_data=False, response_reader=None):
current_params = params
retried = False
while True:
@@ -44,7 +45,9 @@ def _get(session, url, params, *, timeout=DEFAULT_TIMEOUT, allow_survey_not_foun
except requests.RequestException:
raise ApiError("Không kết nối được API. Hãy thử lại sau.") from None
try:
- return clean_json(read_response(response, allow_survey_not_found=allow_survey_not_found, api_version=response_api_version or api_version, operation=operation))
+ payload = response_reader(response) if response_reader else read_response(
+ response, allow_survey_not_found=allow_survey_not_found, api_version=response_api_version or api_version, operation=operation)
+ return payload if preserve_data else clean_json(payload)
except ApiSessionExpiredError:
if retried or operation not in READ_OPERATIONS or auth is None or "Authen" not in params or params_factory is None:
raise
@@ -55,7 +58,7 @@ def _get(session, url, params, *, timeout=DEFAULT_TIMEOUT, allow_survey_not_foun
current_params = params_factory()
-def _v2_request(session, auth, operation, *, timeout, campus=None, params=None):
+def _v2_request(session, auth, operation, *, timeout, campus=None, params=None, preserve_data=False, response_reader=None):
from . import v2
retried = False
@@ -66,7 +69,8 @@ def _v2_request(session, auth, operation, *, timeout, campus=None, params=None):
campus=campus or getattr(auth, "campus", None),
params=params, timeout=timeout)
try:
- return clean_json(read_response(response, api_version="v2", operation=operation))
+ payload = response_reader(response) if response_reader else read_response(response, api_version="v2", operation=operation)
+ return payload if preserve_data else clean_json(payload)
except ApiSessionExpiredError:
if retried or operation not in v2.READ_OPERATIONS or auth is None:
raise
@@ -103,20 +107,25 @@ def _ensure_bound(auth, *, campus=None, api_version=None):
hook(campus=campus or auth.campus, api_version=version, account_type=getattr(auth, "account_type", None))
-def _authenticated_get(session, auth, operation, identifier, *, timeout, campus=None, student=False, params=None, api_version=None):
+def _authenticated_get(session, auth, operation, identifier, *, timeout, campus=None, student=False, params=None, api_version=None, preserve_data=False):
version = _resolve_api_version(auth, api_version)
if version == "v2":
from .v2 import OPERATION_ALIASES
operation = OPERATION_ALIASES.get(operation, operation)
query = {"rollNumber": auth.mssv, **(params or {})} if student else params
- return _v2_request(session, auth, operation, timeout=timeout, campus=campus, params=query)
+ return _v2_request(session, auth, operation, timeout=timeout, campus=campus, params=query, preserve_data=preserve_data)
def build_params():
return {**_auth_params(auth, identifier, campus=campus, student=student), **(params or {})}
return _get(session, f"{FAP_HOST}/{operation}", build_params(), timeout=timeout,
- auth=auth, operation=operation, params_factory=build_params)
+ auth=auth, operation=operation, params_factory=build_params, preserve_data=preserve_data)
+
+
+def _validate_semester(semester):
+ if not isinstance(semester, str) or not semester.strip() or any(ord(character) < 32 for character in semester):
+ raise ApiError("Kỳ học phải là chuỗi không rỗng, không chứa ký tự điều khiển.")
def _semester_start(semester):
@@ -162,6 +171,12 @@ def get_api_active(self):
raise ApiError("GetApiActive chưa được hỗ trợ trên API v1. Hãy chọn --api-version v2.")
return _v2_request(self.session, self.auth, "GetApiActive", timeout=self.timeout)
+ def get_version(self):
+ """Đọc version backend qua bootstrap GetVersion; route v1 đã trả 404."""
+ if self.api_version != "v2":
+ raise ApiError("GetVersion chỉ hỗ trợ bootstrap API v2; route v1 đã ngừng phản hồi. Hãy chọn --api-version v2.")
+ return _v2_request(self.session, self.auth, "GetVersion", timeout=self.timeout)
+
def get_semesters(self, campus: str = None):
"""Lấy kỳ học theo startDate mới nhất; giữ thứ tự server khi trùng ngày."""
if not self.auth:
@@ -187,12 +202,17 @@ def get_week(self, date_str: str):
except ValueError:
raise ApiPayloadError("Số tuần trong response API không hợp lệ.") from None
- def get_news(self, news_type: int = 1):
- """Lấy 10 thông báo gần nhất."""
+ def get_news(self, news_type: int = 1, search=None):
+ """Lấy tin gần nhất hoặc tìm kiếm, ký v1 bằng type."""
if not self.auth:
raise ApiError("Không tìm thấy session xác thực.")
- return _authenticated_get(self.session, self.auth, "GetTop10News", str(news_type),
- params={"type": news_type}, timeout=self.timeout, api_version=self.api_version)
+ if search is not None and (not isinstance(search, str) or not search.strip()):
+ raise ApiError("Nội dung tìm kiếm không được rỗng.")
+ params = {"type": news_type}
+ if search is not None:
+ params["keysearch"] = search
+ return _authenticated_get(self.session, self.auth, "GetTop10News" if search is None else "SearchNews", str(news_type),
+ params=params, timeout=self.timeout, api_version=self.api_version)
class MyFapOther:
@@ -233,9 +253,32 @@ def get_fee(self):
return _authenticated_get(self.session, self.auth, "GeFeeByRoll", self.auth.mssv,
student=True, timeout=self.timeout, api_version=self.api_version)
- def get_subjects(self):
- """Lấy danh sách môn học."""
- return _authenticated_get(self.session, self.auth, "GetSubjets", MAGIC_ID,
+ def get_ratings(self):
+ """Đọc danh sách rating v1; không suy implementation cho stub v2."""
+ if self.api_version != "v1":
+ raise ApiError("GetStudentRate chưa được hỗ trợ trong adapter API v2.")
+ return _authenticated_get(self.session, self.auth, "GetStudentRate", self.auth.mssv,
+ student=True, timeout=self.timeout, api_version=self.api_version)
+
+ def get_feedbacks(self):
+ """Đọc danh sách feedback student; chỉ có trên proxy v2, item schema chưa kiểm chứng positive."""
+ if self.api_version != "v2":
+ raise ApiError("GetStudentFeedbacks chỉ có trên proxy API v2; v1 không có route tương ứng.")
+ return _authenticated_get(self.session, self.auth, "GetStudentFeedbacks", self.auth.mssv,
+ student=True, timeout=self.timeout, api_version=self.api_version)
+
+ def get_balance(self):
+ """Lấy số dư, bảo toàn payload thay vì tự suy diễn thông tin tài chính."""
+ return _authenticated_get(self.session, self.auth, "GetBalance", self.auth.mssv,
+ student=True, timeout=self.timeout, api_version=self.api_version)
+
+ def get_subjects(self, semester=None):
+ """Giữ GetSubjets mặc định; môn theo kỳ ký v1 bằng semester."""
+ if semester is not None:
+ _validate_semester(semester)
+ operation = "GetSubjets" if semester is None else "GetSubjectBySemester"
+ return _authenticated_get(self.session, self.auth, operation, MAGIC_ID if semester is None else semester,
+ params=None if semester is None else {"Semester": semester},
timeout=max(self.timeout, 30.0), api_version=self.api_version)
@@ -252,11 +295,36 @@ def get_schedule(self, semester: str):
return _authenticated_get(self.session, self.auth, "GetActivityStudent", self.auth.mssv,
student=True, params={"Semester": semester}, timeout=self.timeout, api_version=self.api_version)
+ def get_courses(self, semester: str):
+ """Lấy khóa học theo kỳ, giữ đúng query semester chữ thường."""
+ _validate_semester(semester)
+ return _authenticated_get(self.session, self.auth, "GetCourseOfSemester", self.auth.mssv,
+ student=True, params={"semester": semester}, timeout=self.timeout, api_version=self.api_version)
+
def get_marks(self, semester: str):
"""Lấy bảng điểm theo kỳ."""
return _authenticated_get(self.session, self.auth, "GetStudentMark", self.auth.mssv,
student=True, params={"Semester": semester}, timeout=self.timeout, api_version=self.api_version)
+ def get_mark_summary(self):
+ """GetSemesterMark không có query kỳ; v1 cũng không có checksum."""
+ from .summary import read_semester_marks_response
+
+ def reader(response):
+ return read_semester_marks_response(response, api_version=self.api_version)
+
+ if self.api_version == "v2":
+ return _v2_request(self.session, self.auth, "GetSemesterMark", timeout=self.timeout,
+ params={"rollNumber": self.auth.mssv}, preserve_data=True, response_reader=reader)
+
+ def build_params():
+ _ensure_bound(self.auth, api_version="v1")
+ return {"CampusCode": self.auth.campus, "rollNumber": self.auth.mssv, "Authen": self.auth.authen_key}
+
+ return _get(self.session, f"{FAP_HOST}/GetSemesterMark", build_params(), timeout=self.timeout,
+ auth=self.auth, operation="GetSemesterMark", params_factory=build_params,
+ preserve_data=True, response_reader=reader)
+
def get_mark_by_course(self, course_id: str):
"""Lấy điểm chi tiết của môn học, gồm dữ liệu HTML."""
return _authenticated_get(self.session, self.auth, "GetMarkByCourse", self.auth.mssv,
@@ -287,6 +355,22 @@ def get_applications(self):
return _authenticated_get(self.session, self.auth, "GetApplication", self.auth.mssv,
student=True, timeout=self.timeout, api_version=self.api_version)
+ def get_training(self, semester: str):
+ """Lấy điểm phong trào theo kỳ, không tự tính tổng hoặc đổi schema."""
+ _validate_semester(semester)
+ return _authenticated_get(self.session, self.auth, "GetDiemphongtrao", self.auth.mssv,
+ student=True, params={"semester": semester}, timeout=self.timeout, api_version=self.api_version)
+
+ def get_photo(self):
+ """Giữ nguyên representation ảnh; không fetch URL hoặc decode Base64."""
+ return _authenticated_get(self.session, self.auth, "RetriveImage", self.auth.mssv,
+ student=True, timeout=self.timeout, api_version=self.api_version, preserve_data=True)
+
+ def get_transcript(self):
+ """Lấy transcript bằng credential đã bind; không suy schema nghiệp vụ."""
+ return _authenticated_get(self.session, self.auth, "AcademicTranscript", self.auth.mssv,
+ student=True, timeout=self.timeout, api_version=self.api_version)
+
def get_student_info(self):
"""Lấy thông tin sinh viên."""
return _authenticated_get(self.session, self.auth, "GetStudentById", self.auth.mssv,
diff --git a/myfap/cli.py b/myfap/cli.py
index 37814fc..1d0299d 100644
--- a/myfap/cli.py
+++ b/myfap/cli.py
@@ -15,7 +15,7 @@
from .auth import MyFapAuth, SessionBindingError
from .api import MyFapClient, MyFapEssential, MyFapOther
-from .parsers import parse_marks_html, convert_schedule_to_ics
+from .parsers import parse_marks_html, parse_transcript_html, convert_schedule_to_ics, convert_exams_to_ics
from .config import resolve_timeout
from importlib import metadata
@@ -90,6 +90,9 @@ def inherit(command):
other_app = typer.Typer(help="Các chức năng phụ trợ khác (survey, feedback, fee...)")
app.add_typer(other_app, name="other")
+rating_app = typer.Typer(help="Đánh giá dịch vụ; list hiện chỉ hỗ trợ API v1")
+other_app.add_typer(rating_app, name="rating")
+
state = {
"campus": None,
"config": None,
@@ -161,7 +164,9 @@ def save_output(data, default_filename: str, output_dir: Optional[str], stdout:
out_path = Path(output_dir) if output_dir else Path.cwd()
out_path.mkdir(parents=True, exist_ok=True)
- file_path = out_path / default_filename
+ # Tên file có thể nhúng dữ liệu server (tên kỳ); thay ký tự đường dẫn để không thoát thư mục xuất.
+ safe_filename = default_filename.replace("\\", "_").replace("/", "_").replace("\x00", "_")
+ file_path = out_path / safe_filename
try:
with open(file_path, "w", encoding="utf-8", newline="" if is_text else None) as f:
@@ -204,6 +209,23 @@ def version():
ver = "unknown (not installed via pip)"
console.print(f"MyFap API CLI version: [bold cyan]{ver}[/bold cyan]")
+@app.command()
+def doctor(
+ online: bool = typer.Option(False, "--online", help="Gọi bootstrap GetApiActive/GetVersion v2; không xác thực session"),
+ output: Optional[str] = typer.Option(None, "--output", "-o", help="Thư mục xuất file"),
+ stdout: bool = typer.Option(False, "--stdout", help="In JSON chẩn đoán ra stdout")
+):
+ """Chẩn đoán cấu hình explicit/default; không đọc hoặc làm mới session."""
+ from .diagnostics import get_diagnostics
+ try:
+ report = get_diagnostics(api_version=state["api_version"], campus=state["campus"],
+ timeout=state["timeout"], online=online)
+ save_output(report, "Doctor.json", output, stdout)
+ except Exception as error:
+ err_console.print(f"[red]Lỗi chẩn đoán: {error}[/red]")
+ raise typer.Exit(code=1)
+
+
@app.command()
def login(
campus: Optional[str] = typer.Option(None, "--campus", "-c", help="Mã cơ sở theo API version; ví dụ APHL (v1), HN (v2)"),
@@ -327,15 +349,87 @@ def schedule(
err_console.print(f"[red]Lỗi lấy lịch học: {e}[/red]")
raise typer.Exit(code=1)
+@app.command()
+def transcript(
+ pretty: bool = typer.Option(False, "--pretty", "-p", help="Phân tích HTML bảng điểm toàn khóa thành JSON cấu trúc"),
+ output: Optional[str] = typer.Option(None, "--output", "-o", help="Thư mục xuất file"),
+ stdout: bool = typer.Option(False, "--stdout", help="In kết quả ra màn hình thay vì lưu file")
+):
+ """Lấy bảng điểm toàn khóa theo contract API đã chọn."""
+ auth = require_auth("AcademicTranscript")
+ try:
+ data = MyFapClient(auth).get_transcript()
+ filename = "Transcript.json"
+ if pretty and isinstance(data, dict) and isinstance(data.get('data'), str) and '= 3 and tds[0].has_attr('rowspan'):
current_category = td_texts[0]
- category_rows_remaining = max(0, int(tds[0]['rowspan']) - 1)
+ category_rows_remaining = _rowspan_rows(tds[0]['rowspan']) - 1
data_tds = td_texts[1:]
elif len(tds) >= 2 and tds[0].has_attr('colspan') and current_category:
# Giữ cấu trúc output của dòng tổng kết hiện có.
@@ -73,7 +82,116 @@ def parse_marks_html(html_str: str):
return result
-from datetime import datetime, timezone
+def parse_transcript_html(html_str: str):
+ """Phân tích chuỗi HTML bảng điểm toàn khóa: mỗi bảng giữ header riêng và hàng dữ liệu keyed theo header."""
+ def cell_text(node):
+ # giải mã thành \xa0; chuẩn hoá thành space thường để JSON sạch.
+ return node.get_text().replace('\xa0', ' ').strip()
+
+ soup = BeautifulSoup(html_str, 'html.parser')
+ tables = []
+ for table in soup.find_all('table'):
+ headers = []
+ rows = []
+ for tr in table.find_all('tr'):
+ if tr.find('th'):
+ headers = [cell_text(th) for th in tr.find_all('th')]
+ continue
+ tds = tr.find_all('td')
+ if not tds or not headers:
+ continue
+ row = {}
+ for index, td in enumerate(tds):
+ key = headers[index] if index < len(headers) else f"Column{index + 1}"
+ row[key] = cell_text(td)
+ rows.append(row)
+ if headers or rows:
+ tables.append({"headers": headers, "rows": rows})
+ return tables
+
+
+def convert_exams_to_ics(data: dict, full: bool = False) -> str:
+ """Chuyển dữ liệu lịch thi JSON thành chuỗi ICS.
+
+ Mặc định (full=False) chỉ đưa thông tin quan trọng (Môn, Ngày công bố);
+ ẩn mã slot UUID, phòng thi, ghi chú và các trường phụ.
+ Khi full=True đưa toàn bộ thông tin phụ vào sự kiện lịch.
+ """
+ if not isinstance(data, dict) or not isinstance(data.get("data"), list):
+ raise ValueError("Invalid JSON format")
+
+ c = Calendar()
+ tz = pytz.timezone("Asia/Ho_Chi_Minh")
+
+ for exam in data["data"]:
+ if (not isinstance(exam, dict)
+ or any(not isinstance(exam.get(field), str) or not exam[field].strip()
+ for field in ("date", "time", "subjectCode"))):
+ raise ValueError("Invalid exam: date, time and subjectCode are required")
+ try:
+ day = datetime.strptime(exam["date"].split("T")[0].strip(), "%Y-%m-%d")
+ normalized = exam["time"].strip().strip("()").replace(" ", "")
+ match = re.fullmatch(r"(\d{1,2})h(\d{2})-(\d{1,2})h(\d{2})", normalized)
+ if match is None:
+ raise ValueError
+ start_dt = tz.localize(datetime.strptime(
+ f"{day:%Y-%m-%d} {match.group(1)}:{match.group(2)}", "%Y-%m-%d %H:%M"))
+ end_dt = tz.localize(datetime.strptime(
+ f"{day:%Y-%m-%d} {match.group(3)}:{match.group(4)}", "%Y-%m-%d %H:%M"))
+ except ValueError:
+ raise ValueError(
+ "Invalid exam: date hoặc time không hợp lệ (date dạng YYYY-MM-DD, time dạng 7h30-9h50).") from None
+ # Kỳ thi kết thúc trước giờ bắt đầu nghĩa là vượt nửa đêm: kết thúc sang ngày hôm sau.
+ if end_dt <= start_dt:
+ end_dt += timedelta(days=1)
+
+ e = Event(created=datetime.now(timezone.utc))
+ title = exam["subjectCode"]
+ kythi = exam.get("kythi")
+ if isinstance(kythi, str) and kythi.strip():
+ title += f" ({kythi.strip()})"
+ e.name = title
+ e.begin = start_dt
+ e.end = end_dt
+
+ e.location = exam.get("roomNo") or ""
+
+ if full:
+ fields_to_add = (
+ ("Môn", "subjectName"),
+ ("Phòng", "roomNo"),
+ ("Ngày công bố", "dateofPublication"),
+ ("Mã slot", "slot"),
+ ("Ghi chú", "note"),
+ ("Ghi chú điểm danh", "note_Attendance"),
+ ("Đã tốt nghiệp", "isGraduated"),
+ )
+ else:
+ fields_to_add = (
+ ("Môn", "subjectName"),
+ ("Phòng", "roomNo"),
+ ("Ngày công bố", "dateofPublication"),
+ )
+
+ desc = []
+ for label, field in fields_to_add:
+ value = exam.get(field)
+ if value is None:
+ continue
+ if isinstance(value, bool):
+ desc.append(f"{label}: {'Có' if value else 'Không'}")
+ elif isinstance(value, str) and value.strip():
+ clean_val = value.strip().replace("T00:00:00", "")
+ desc.append(f"{label}: {clean_val}")
+ e.description = "\n".join(desc)
+
+ c.events.add(e)
+
+ # Trả về chuỗi ICS
+ return "".join(c.serialize_iter())
+
+
+from datetime import datetime, timedelta, timezone
import pytz
from ics import Calendar, Event
@@ -96,18 +214,25 @@ def convert_schedule_to_ics(data: dict) -> str:
# Parse time: "(7:30-9:50)" -> "7:30", "9:50"
time_str = session["slotTime"].strip().strip("()").strip()
- start_time_str, end_time_str = (part.strip() for part in time_str.split("-", 1))
-
+ try:
+ start_time_str, end_time_str = (part.strip() for part in time_str.split("-", 1))
+ except ValueError:
+ raise ValueError("slotTime phải có dạng (giờ bắt đầu-giờ kết thúc), ví dụ (7:30-9:50).") from None
+
# Parse full datetime
start_dt = tz.localize(datetime.strptime(f"{date_str} {start_time_str}", "%m/%d/%Y %H:%M"))
end_dt = tz.localize(datetime.strptime(f"{date_str} {end_time_str}", "%m/%d/%Y %H:%M"))
+ # Slot kết thúc trước giờ bắt đầu nghĩa là vượt nửa đêm: kết thúc sang ngày hôm sau.
+ if end_dt <= start_dt:
+ end_dt += timedelta(days=1)
# Create event
e = Event(created=datetime.now(timezone.utc))
# Title
title = session['subjectCode']
- if session.get("isOnline") == "True":
+ is_online = session.get("isOnline")
+ if is_online is True or is_online == "True":
title += " (Online)"
e.name = title
diff --git a/myfap/summary.py b/myfap/summary.py
new file mode 100644
index 0000000..be11357
--- /dev/null
+++ b/myfap/summary.py
@@ -0,0 +1,34 @@
+"""Strict response reader scoped to GetSemesterMark, not a generic text fallback."""
+
+import json
+
+from .errors import ApiPayloadError, read_response
+
+
+MAX_SUMMARY_BYTES = 1024 * 1024
+
+
+def read_semester_marks_response(response, *, api_version):
+ if response.status_code != 200:
+ read_response(response, api_version=api_version, operation="GetSemesterMark")
+ content = getattr(response, "content", b"")
+ if isinstance(content, bytes) and len(content) > MAX_SUMMARY_BYTES:
+ raise ApiPayloadError("Response tổng kết vượt giới hạn xử lý cục bộ.")
+ try:
+ payload = response.json()
+ except (ValueError, AttributeError):
+ payload = None
+ # Preserve the common HTTP, App Check and explicit expiry classifications.
+ if response.status_code != 200 or isinstance(payload, dict):
+ envelope = read_response(response, api_version=api_version, operation="GetSemesterMark")
+ if not isinstance(envelope["data"], list):
+ raise ApiPayloadError("Dữ liệu tổng kết phải là một danh sách.")
+ return envelope
+ if isinstance(payload, str):
+ try:
+ payload = json.loads(payload)
+ except ValueError:
+ raise ApiPayloadError("Định dạng tổng kết chưa được hỗ trợ.") from None
+ if not isinstance(payload, list):
+ raise ApiPayloadError("Response tổng kết không có danh sách hợp lệ.")
+ return {"code": 200, "data": payload}
diff --git a/myfap/v2.py b/myfap/v2.py
index 7c923a0..a51ce0e 100644
--- a/myfap/v2.py
+++ b/myfap/v2.py
@@ -13,18 +13,26 @@
from .errors import ApiError
-BOOTSTRAP_OPERATIONS = frozenset({"GetAllActiveCampus", "GetApiActive"})
+# GetVersion: caller APK dùng GET (module_599.js:662) nhưng proxy hiện trả 405 với GET;
+# POST body rỗng được chấp nhận (thí nghiệm 24/10/2026), nên đi theo nhánh bootstrap.
+BOOTSTRAP_OPERATIONS = frozenset({"GetAllActiveCampus", "GetApiActive", "GetVersion"})
OPERATION_ALIASES = {"getCourseAttendance": "GetCourseAttendance"}
_READ_QUERY_FIELDS = {
"GetSemester": (),
"GetTop10News": ("type",),
+ "SearchNews": ("type", "keysearch"),
"CheckOpenFeedBack": ("rollNumber",),
"CheckUpdateProfile": ("rollNumber",),
"GetNotificationByRoll": ("rollNumber",),
"GeFeeByRoll": ("rollNumber",),
+ "GetBalance": ("rollNumber",),
"GetSubjets": (),
+ "GetSubjectBySemester": ("Semester",),
"GetActivityStudent": ("rollNumber", "Semester"),
"GetStudentMark": ("rollNumber", "Semester"),
+ "GetSemesterMark": ("rollNumber",),
+ "GetCourseOfSemester": ("rollNumber", "semester"),
+ "GetDiemphongtrao": ("rollNumber", "semester"),
"GetMarkByCourse": ("rollNumber", "CourseId"),
"GetScheduleExam": ("rollNumber", "Semester"),
"GetStudentAttendances": ("rollNumber", "Semester"),
@@ -32,10 +40,13 @@
"GetCourseAttendance": ("rollNumber", "Semester", "SubjectCode", "ClassName"),
"GetApplication": ("rollNumber",),
"GetStudentById": ("rollNumber",),
+ "GetStudentFeedbacks": ("rollNumber",),
+ "AcademicTranscript": ("rollNumber",),
+ "RetriveImage": ("rollNumber",),
"GetCampusInfo": ("rollNumber",),
"GetWeekByDate": ("date",),
}
-_AUTHEN_QUERY_OPERATIONS = frozenset({"CheckOpenFeedBack", "CheckUpdateProfile", "GetApplication", "GetNotificationByRoll"})
+_AUTHEN_QUERY_OPERATIONS = frozenset({"CheckOpenFeedBack", "CheckUpdateProfile", "GetApplication", "GetNotificationByRoll", "GetSemesterMark"})
READ_OPERATIONS = frozenset(_READ_QUERY_FIELDS)
SUPPORTED_OPERATIONS = BOOTSTRAP_OPERATIONS | READ_OPERATIONS | {"AuthenticationByFeId"}
diff --git a/tasks/phase5.md b/tasks/phase5.md
index 9c7d953..6a1740b 100644
--- a/tasks/phase5.md
+++ b/tasks/phase5.md
@@ -2,7 +2,9 @@
Nhánh `feat/phase5-release-automation` bắt đầu từ `origin/main` tại `06d98e115bb63a244d793236f81d7b62f63a5dc7`, sau khi PR #8 đã merge. Package giữ `0.2.0`, Python >=3.9, v1 mặc định và v2 opt-in.
-Phạm vi phase là chuẩn bị release notes, gate tag/version/artifact, Trusted Publishing, post-publish smoke và GitHub Release; thêm endpoint mới thuộc Phase 6 theo kế hoạch workspace. Người dùng đã xác nhận commit và push **nhánh tính năng** sau kiểm tra. Nhánh đang được theo dõi trong [Draft PR #9](https://github.com/WindowScary321/myfap-api-cli/pull/9). Tạo/push tag, upload và thay đổi cấu hình dịch vụ cần maintainer cho phép riêng; chưa tạo tag, publish hoặc GitHub Release.
+Phạm vi phase là chuẩn bị release notes, gate tag/version/artifact, Trusted Publishing, post-publish smoke và GitHub Release; thêm endpoint mới thuộc Phase 6. [PR #9](https://github.com/WindowScary321/myfap-api-cli/pull/9) đã merge vào `main` tại `75fc7b4aa33a13b9b39eab898f61e2e693f4baf9`.
+
+**Quyết định ngày 23/10/2026:** hoãn tag/publish đến sau khi hoàn thiện và nghiệm thu phạm vi [Phase 6](phase6.md). Phase 5 hiện là pipeline đã chuẩn bị, không phải bản đã phát hành. Giữ `0.2.0`, v1 mặc định/v2 opt-in; chưa tạo tag, publish PyPI/TestPyPI hoặc GitHub Release. Nghiệm thu dịch vụ, tạo/push tag, upload và thay đổi cấu hình vẫn cần maintainer cho phép riêng.
Mapping command → method → endpoint → URL → capability được hợp nhất tại [command-endpoints.md](../docs/command-endpoints.md), kèm danh sách route còn chưa tích hợp. Không dùng trạng thái triển khai pipeline hoặc live command cốt lõi để tuyên bố đã thêm toàn bộ endpoint.
@@ -15,7 +17,7 @@ Hai commit mã nguồn đã kiểm: `671ca5f06b63ce4ae826732fb4f1a3a64c252f62` (
- [ ] Giữ positive fee/survey là TODO hoãn chờ dữ liệu phù hợp; schema live có dữ liệu chưa kiểm chứng. Quyết định hoãn ngày 19/10/2026 cho phép chuyển Phase 5, không chứng minh backend đạt.
- [ ] Giữ giới hạn ICS: reader độc lập đã kiểm; import vào ứng dụng lịch thật chưa kiểm chứng.
-Các finding v1 và positive case nằm trong [TODO](todo.md) và [coverage Phase 4](../docs/phase4-coverage.md). Phase 6 không chặn `0.2.0`.
+Các finding v1 và positive case nằm trong [TODO](todo.md) và [coverage Phase 4](../docs/phase4-coverage.md). Theo quyết định ngày 23/10/2026, nghiệm thu phạm vi Phase 6 diễn ra trước khi phát hành bằng pipeline này; việc hoãn positive fee/survey trước đó vẫn được giữ, không chuyển thành bằng chứng schema đã đạt.
## Gate kỹ thuật
diff --git a/tasks/phase6.md b/tasks/phase6.md
new file mode 100644
index 0000000..118be59
--- /dev/null
+++ b/tasks/phase6.md
@@ -0,0 +1,115 @@
+# Phase 6: mở rộng command và endpoint trước phát hành
+
+Nhánh triển khai `feat/phase6-command-expansion` bắt đầu từ `main` tại `75fc7b4aa33a13b9b39eab898f61e2e693f4baf9`, sau khi [PR #9](https://github.com/WindowScary321/myfap-api-cli/pull/9) được merge. Theo quyết định ngày **23/10/2026**, Phase 5 chỉ chuẩn bị pipeline; **hoãn tag/publish đến sau khi hoàn thiện và nghiệm thu phạm vi Phase 6**. Giữ baseline `0.2.0`, Python >=3.9, v1 mặc định và v2 opt-in.
+
+Nhóm command đọc đã có implementation và fixture CLI/HTTP; xem [coverage Phase 6](../docs/phase6-coverage.md). Dấu đã kiểm bên dưới chỉ áp dụng cho code/fixture được nêu, không thay thế live hoặc nghiệm thu backend. Phần thiếu contract/schema vẫn giữ gate rõ; không đánh dấu toàn Phase 6 hoàn tất khi các yêu cầu bắt buộc còn mở.
+
+## Quy tắc xuyên suốt
+
+- Tái sử dụng wrapper, common options, resolver kỳ và output JSON hiện có; không refactor auth/CI ngoài phạm vi. Không thay `tasks/plan.md` vì đó là lịch sử migration.
+- Kiểm capability và option/input trước HTTP; giữ binding campus/API version/student và bảo toàn token đã rotate. Không fallback version, không trả dữ liệu rỗng giả cho stub/lỗi.
+- Retry đọc tối đa một lần chỉ khi expiry rõ. Thao tác ghi không replay dù endpoint dùng GET; timeout hoặc kết quả không rõ không được báo thành công hoặc tự gửi lại.
+- JSON/ICS stdout giữ UTF-8; log/lỗi stderr. `save_output` không phải binary writer.
+- Test dùng dữ liệu tổng hợp, credential giả và session tạm. Live đọc dùng browser/context mới, payload chỉ xử lý cục bộ; chỉ operation/method/HTTP/body code/kiểu dữ liệu/exit code/kiểm định dạng được ghi vào báo cáo.
+- Không đưa raw response, ảnh, token, query có giá trị, identity hoặc dữ liệu tài khoản lên GitHub. Live ghi cần người dùng xác nhận riêng thao tác cụ thể.
+- Mỗi commit push lên PR phải có comment ngay sau commit, ghi SHA, kiểm tra/exit code và giới hạn; không tự merge, tạo tag, publish hoặc đổi default v2.
+
+## 1. Các lát cắt đọc rõ contract
+
+Mỗi mục cần đi trọn CLI → wrapper → transport v1/v2 → fixture/test → coverage, không chỉ thêm tên vào allowlist.
+
+- [x] **`courses --semester` → `GetCourseOfSemester`:** dùng resolver kỳ nếu thiếu option; query `semester` chữ thường, đúng credential/signing identity từng version.
+- [x] **`other subjects --semester` → `GetSubjectBySemester`:** query `Semester` chữ hoa; v1 ký bằng semester. Khi không có option mới vẫn dùng `GetSubjets`, không lookup kỳ và giữ timeout subjects hiện có.
+- [x] **`other balance` → `GetBalance`:** không lookup kỳ; bảo toàn payload, không suy ra currency/nợ/invoice. Cập nhật retry/error allowlist có chủ đích và giữ regression cho operation chưa hỗ trợ.
+- [x] **`news --search` → `SearchNews`:** không có search vẫn dùng `GetTop10News`; từ chối search rỗng trước auth, truyền `type`/`keysearch` qua params và v1 ký bằng type. Kiểm Unicode và ký tự reserved, không nối query thủ công.
+
+**Nghiệm thu nhóm:**
+- [x] Test tại public seam CLI và biên HTTP chứng minh method/path/query/header/body đúng, stdout sạch, binding và common-option precedence được giữ.
+- [x] Có success/empty/not-found phù hợp, malformed, expiry, App Check, timeout/5xx và không fallback; focused tests rồi regression hiện có đạt.
+
+## 2. Transcript, training và marks summary
+
+- [x] **`transcript` → `AcademicTranscript`:** hỗ trợ theo contract cả v1/v2, không lookup kỳ; chưa thêm formatter nghiệp vụ khi schema data chưa được xác minh.
+- [x] **`other training --semester` → `GetDiemphongtrao`:** query `semester` chữ thường, dùng resolver khi thiếu kỳ; giữ bound credential phù hợp.
+- [x] **`marks --summary` → `GetSemesterMark`:** không lookup kỳ hoặc thêm query semester. V1 dùng đúng `CampusCode`, `rollNumber`, `Authen`, **không checksum**; v2 giữ query `Authen` mới sau refresh.
+- [x] Từ chối tổ hợp summary với `--courseid`/`--pretty`; nếu `--semester` không áp dụng thì báo lỗi, không âm thầm bỏ qua.
+- [x] Reader riêng cho summary kiểm HTTP/App Check/expiry trước khi đọc raw array/envelope/text. Chỉ parse dạng đã có bằng chứng, có giới hạn; malformed/unknown phải báo payload error, không cắt tùy tiện giữa dấu ngoặc rồi trả success.
+- [x] Chốt khác biệt credential v2 ở các caller decompile của transcript/training/summary bằng bytecode/contract và kiểm đọc. Không mặc định sao chép credential rỗng, thử unauth rồi fallback hoặc nới reader chung cho mọi endpoint.
+
+**Nghiệm thu nhóm:**
+- [x] Test exact casing, no-semester/no-checksum, signing identity và dựng Authen mới sau refresh; giữ nguyên command marks cũ.
+- [x] Fixture được ghi rõ synthetic; các schema hoặc credential chưa live xác nhận tiếp tục có nhãn unverified.
+
+## 3. Photo và doctor
+
+- [x] **`info photo` → `RetriveImage`:** output JSON theo representation đã chứng minh, giữ chuỗi opaque; không tự fetch URL, decode Base64, in binary hoặc mở ảnh. Xuất ảnh file riêng chỉ mở sau khi đủ bằng chứng định dạng/size/type và fixture.
+- [x] **`doctor` local:** chỉ xuất allowlist chẩn đoán package/API version, campus được chọn, capability và loại lỗi; không dump auth/session, email/MSSV, header, token hoặc config path đầy đủ. Không gọi `require_auth`/`load_session` gây refresh/persist.
+- [x] Probe online là option explicit và tái sử dụng `GetApiActive` v2; không auto-login/refresh/switch version. `GetVersion` giữ gate riêng khi public/text contract còn chưa rõ; `myfap version` tiếp tục offline.
+- [x] Test doctor/help local không gọi mạng; lỗi không lộ payload; photo không tạo file/fetch ngoài ý muốn.
+
+## Checkpoint: nhóm đọc
+
+- [x] Focused/full regression, build/Twine/artifact validator và pip smoke đạt; không có docs/tasks/tests/session/capture trong distribution.
+- [x] Cập nhật [mapping command/endpoint/URL](../docs/command-endpoints.md), [contract v2](../docs/v2-contracts.md) và coverage Phase 6 với capability theo version/account rõ ràng.
+- [x] Live đọc bằng session/browser mới; ghi riêng success, empty, not-found, failure, skip và unverified. Không dùng 200 hoặc nonempty để đóng positive fee/survey; không dùng v2 để đóng finding v1.
+
+## 4. Rating và push — chỉ mở sau gate contract
+
+Bằng chứng đã biết, phần còn thiếu và cách thu thập không lộ PII được liệt kê tại [phase6-write-gates.md](../docs/phase6-write-gates.md). Không dùng body/query tùy ý để thay cho schema; caller code 200 của AddRate đã biết nhưng ack nghiệp vụ/positive item chưa được xác minh.
+
+*Ghi chú phạm vi (24/10/2026):* Năm (5) hộp việc bên dưới liên quan đến thao tác ghi (`AddRate`, `UpdateTokedevices`, tách luồng retry, test invalid/cancel không replay, và xác nhận live ghi) tiếp tục **giữ trạng thái gate/unsupported có chủ đích** do tài khoản kiểm chứng hiện tại trả danh sách rating rỗng, không thể xác minh schema/ack thực tế. Tuyệt đối không đánh dấu tick khi chưa có bằng chứng và không diễn giải thành "mọi hộp việc đã hoàn tất".
+
+- [x] **Rating list:** `other rating list` student/v1 có code và fixture envelope/query; lượt live trước đổi namespace trả list rỗng, chưa suy kiểu ID/schema item hoặc positive schema. V2 là stub nên unsupported trước load session/HTTP, không gọi v1 ngầm hoặc trả `[]` giả.
+- [ ] **`other rating submit --input` (dự kiến, chưa mở):** chốt input/ack bằng bằng chứng đủ tin cậy trước khi mở. `AddRate` là POST; v1 checksum dùng **rateid**, v2 giữ query `Authen` và body `{}`. Dải rating 1–5 có nguồn caller; không tự đặt type ID/comment bounds của backend.
+- [ ] **`push register --token-file`:** chốt contract student; `UpdateTokedevices` là **GET ghi**, v1 ký bằng **email**. Token chỉ đọc từ regular file có giới hạn, kiểm encoding/newline và symlink/reparse/path swap; không token trên argv/preview/log/error. Campus/identity lấy từ session đã bind.
+- [ ] Đường ghi tách khỏi read retry, không thêm AddRate/push vào read allowlist để cấp credential. Trình tự: validate → capability → preview không bí mật → confirmation/`--yes` → auth → một lần gửi. `--yes` không bỏ validation.
+- [ ] Test invalid input/cancel/noninteractive thiếu xác nhận gây zero auth/network; 401/App Check/timeout/5xx hoặc unknown outcome không replay.
+- [ ] Live ghi chỉ thực hiện sau xác nhận riêng của người dùng; nếu chưa đủ schema/ack thì capability vẫn đóng và ghi TODO, không mở generic submit.
+
+## 5. Feedback và flow còn thiếu bằng chứng
+
+*Ghi chú phạm vi (24/10/2026):* Ba (3) hộp việc bên dưới (`CheckOpenFeedBack`, `SubmitStudentFeedback`/donor/employee/FEID-server-code, và rà soát blocker trước chốt) tiếp tục **giữ trạng thái gate/unsupported có chủ đích**. `GetStudentFeedbacks` đã mở đọc list, nhưng do danh sách trả về rỗng nên `GetStudentFeedbackForm` và `SubmitStudentFeedback` không có `feedbackId` và form schema thực tế; giữ nguyên gate, không đoán ID hoặc tick khi chưa có schema live.
+
+- [ ] Giữ `other feedback` là `CheckOpenFeedBack`; không đổi nghĩa thành list/form/submit.
+- [x] `GetStudentFeedbacks` mở `other feedbacks` (24/10/2026) sau khi có envelope live 200/list rỗng và bytecode xác nhận query `{CampusCode, rollNumber}` không `Authen`; item schema giữ nhãn chưa positive. `GetStudentFeedbackForm` vẫn gate chờ feedbackId thật; không suy kiểu item/ID/câu hỏi từ tên route.
+- [ ] `SubmitStudentFeedback`, donor/employee, donor push và FEID server-code exchange thiếu schema/capability tiếp tục gate/TODO; không nhận JSON tùy ý để vượt gate.
+- [ ] Trước khi chốt phạm vi, liệt kê từng blocker và bằng chứng cần thêm; không đánh dấu Phase 6 hoàn tất bằng cách lặng lẽ bỏ các mục chưa đạt.
+
+## 6. Kiểm chứng và bàn giao PR
+
+- [x] Dùng red → green từng feature qua CLI thật và HTTP giả; mutation check cho casing, signing identity và no-retry. Không dùng dữ liệu account làm fixture.
+- [x] Chạy từ checkout: `uv sync --locked --group ci`, focused tests, rồi `uv run --locked --group ci python -m unittest discover -s tests -v` trên Python 3.9/3.11; `git diff --check`.
+- [x] Build, Twine, artifact validator và pip smoke theo [development.md](../docs/development.md); CI xác nhận Ubuntu/Windows × Python 3.9/3.11.
+- [x] Review độc lập phần query/credential/parser/write safety và cập nhật README/CHANGELOG/coverage theo đúng kết quả.
+- [x] Draft PR Phase 6 được tạo từ nhánh mới; mỗi commit push có comment ngay sau commit, gồm SHA, thay đổi, lệnh/exit code và giới hạn.
+- [x] Maintainer nghiệm thu phạm vi Phase 6 trước khi tiếp tục [gate phát hành Phase 5](phase5.md). Không tự merge/tag/publish.
+
+## Kết quả checkpoint hiện tại
+
+Nhóm command đọc và doctor đã có fixture; focused tests ghi RED trước implementation rồi GREEN. Full suite ngày 24/10/2026 trên Windows: **389 test mỗi Python 3.11 và 3.9, 385 đạt/4 skip, exit 0**. Bốn skip là các phép symlink/POSIX mode không áp dụng hoặc thiếu quyền trên Windows, không phải test bị bỏ mới.
+
+Review độc lập đã tái hiện hai finding bằng HTTP giả: public API v1 chưa validate kỳ trước HTTP, và body summary lỗi quá lớn che HTTP 401/503. Đã sửa và test lại. Lượt full đầu chạy hai interpreter đồng thời bị timeout tiến trình help 20 giây; Python 3.9 còn lộ cách CliRunner tách stderr khác version. Đã sửa cấu hình capture trong test theo mẫu hiện có, giữ nguyên kiểm tra nội dung/timeout; focused help đạt, sau đó hai full suite chạy tuần tự đều đạt. Không hạ tiêu chí hoặc bỏ test.
+
+Build, Twine và artifact validator đã đạt với bộ `dist-phase6-reads`, manifest SHA-256 `f88e6fe7b5795fbb01acfda00df434e74d02965aaab21c2c83328e4bfaff2fea`. Pip smoke wheel/sdist trong hai venv sạch Windows/Python 3.11 đạt, exit 0; không dùng lockfile để resolve dependency. Mutation đổi signer subjects từ semester sang identity khác bị test bắt; chạy trên bản sao tạm, không sửa checkout. Fixture mới dùng identity tổng hợp kể cả nhánh legacy. Doctor local đã chạy qua CLI thật, không đọc session/HTTP. Sau khi thêm rating list v1: full Windows có 391 test mỗi Python 3.11/3.9, 387 đạt/4 skip, exit 0. CI tại `d6d0ee6` đạt [11/11 job](https://github.com/WindowScary321/myfap-api-cli/actions/runs/40064482334). Đã sửa assertion ANSI gây fail run trước, không đổi runtime; lỗi tzdata UTC của venv test 3.9 được tái hiện bằng probe riêng rồi cài lại đúng package đã khóa, không đổi dependency.
+
+Lượt thử live đầu chưa hoàn tất login (exit 1, chưa có response FAP); doctor local đạt, các command xác thực sau login chưa chạy; đã dọn session/thư mục tạm. Lượt sau ngày 24/10/2026, người dùng xác nhận login mới v2/HN: **14 lần command đều exit 0**, JSON hợp lệ; courses, subjects theo kỳ, balance, search, transcript, training, summary, photo JSON và doctor bootstrap đều HTTP/body 200. Training list rỗng hợp lệ; balance/transcript/photo là string, chưa suy schema nghiệp vụ hoặc định dạng ảnh. Refresh và đọc sau refresh đạt, session/lock/thư mục tạm đã dọn.
+
+CI của code `0e0c01c` đạt [11/11 job](https://github.com/WindowScary321/myfap-api-cli/actions/runs/40064917612). Xem [metadata và giới hạn live](../docs/phase6-coverage.md#live-đọc-v2hn-ngày-24102026). Sau đó đã login mới và chạy v1/APHL trên `ca09b11`: 14 lần command, 10 exit 0/4 exit 1, harness exit 1. Subjects/balance/transcript/photo/rating list đọc được, nhưng transcript rỗng, photo null và rating list rỗng chưa xác minh positive schema. Courses/summary HTTP 404; search/training HTTP 200/body 201, chưa rõ nguyên nhân. Không fallback hoặc che lỗi bằng empty; đã dọn session/lock. Xem [kết quả v1](../docs/phase6-coverage.md#live-đọc-v1aphl-ngày-24102026). Rating submit/push/feedback vẫn gate, không tuyên bố Phase 6 hoàn tất. Các finding v1 và positive fee/survey giữ tại [todo.md](todo.md).
+
+Sau khi thêm `V1ObservedFailureTests` bằng status/shape tổng hợp: focused nhóm đọc với FORCE_COLOR=1 đạt 15/15 trên cả Python 3.11/3.9, exit 0. Full chuẩn của repo chạy tuần tự có **392 test mỗi version, 388 đạt/4 skip, exit 0**. Không sửa runtime để che bốn lỗi server v1. Lượt thử ép FORCE_COLOR=1 lên toàn suite (không phải môi trường gate chuẩn) có 5 failure ở assertion màu/spinner cũ trong test_auth_contract/test_cli/test_cli_output; chưa ghi nhận hỗ trợ full suite ở mode đó. Chỉ focused màu và full chuẩn được ghi đạt; không xóa/nới các assertion cũ.
+
+Nghiệm thu nhóm mục 1 hoàn tất ngày 24/10/2026 bằng lớp `ReadSliceAcceptanceTests` trong tests/test_phase6_reads.py: 5 test chạy tại seam CLI cho cả bốn lát cắt đọc (balance, courses, subjects theo kỳ, news search) trên hai version. Phần header contract v2 kiểm `ClientCode`, `CampusCode`, `Authorization` Bearer, `Checksum` dạng chữ ký base64 + dấu hai chấm + timestamp giây decimal, GET không có `json` body hoặc `Content-Type`. Ma trận lỗi gồm expiry retry đúng một lần với credential mới (v1 body 201 `Token invalid`; v2 body 401 và HTTP 401, Checksum đổi theo key mới, phần query còn lại giữ nguyên), dừng sau lần expiry thứ hai, và App Check/timeout/HTTP 503/malformed giữ đúng một request, không refresh/fallback, stdout rỗng khi lỗi, không lộ sentinel hay credential. Test đạt GREEN ngay vì xác nhận hành vi đã triển khai từ các commit trước, không có behavior mới cần bước RED. Focused `tests.test_phase6_reads` đạt 22/22; full suite 399 test, 395 đạt/4 skip, exit 0 trên Windows Python 3.11.
+
+Nghiệm thu nhóm mục 2 hoàn tất ngày 24/10/2026. (1) Từ chối tổ hợp `--summary` với `--semester`/`--courseid`/`--pretty` đã có code chặn trước auth và test `test_conflicting_summary_options_fail_before_auth`. (2) Reader `read_semester_marks_response` kiểm HTTP/App Check/expiry trước khi đọc, giới hạn 1 MiB và từ chối wrapper chưa xác minh bằng payload error — phủ bởi 5 test reader trong tests/test_phase6_summary.py, gồm phân loại 401/503 cho body lỗi quá lớn. (3) Credential v2 chốt bằng bytecode caller: trong module_599.js của APK, wrapper GET (closure_21, dòng 898–906) mặc định credential là chuỗi rỗng khi caller không truyền tham số thứ tư; `_buildHeaders` (dòng 747–781) với credential rỗng tạo header **không Authorization** và `_makeChecksum` (dòng 726–746) ký bằng bootstrap token. Cả ba `_getSemesterMark` (dòng 218–224), `_getAcademicTranscript` (dòng 266–272) và `_getDiemphongtrao` (dòng 280–286) đều gọi wrapper không truyền credential header; chỉ GetSemesterMark đặt FAP key trong query `Authen`. CLI giữ chủ đích policy authenticated-read (Bearer FAP key + Checksum theo key) cho cả ba, không sao chép credential rỗng, không thử unauth rồi fallback, không nới reader chung; khác biệt với app được ghi tại coverage. Kiểm đọc live v2/HN bằng chính CLI đạt HTTP/body 200 cả ba operation ở lượt 24/10 và lượt nghiệm thu hôm nay. Lượt nghiệm thu chạy trên máy cá nhân với session thật; output raw chỉ xử lý cục bộ trên máy đó, đã xóa sau khi trích metadata và không đưa lên Git. Metadata được ghi: info student đối chứng 200 (list 1); transcript 200 data chuỗi ~10,5 KB là mảnh HTML bảng (53 `` bao); training 200 list rỗng kỳ mới nhất; marks --summary 200 envelope data list 32 phần tử, mỗi phần tử đúng 5 khóa `SubjectCode`/`ClassName`/`AverageMark`/`Status`/`GradeStatus` — positive schema thật đầu tiên cho summary. Formatter nghiệp vụ transcript/training vẫn giữ nhãn chưa kiểm chứng; fixture trong test luôn synthetic. Theo yêu cầu của maintainer, biến thể credential rỗng được kiểm chứng thêm bằng thí nghiệm transport có kiểm soát trước khi đổi CLI: proxy từ chối HTTP 400 mọi biến thể không Authorization hoặc checksum lệch credential (và 500 khi dùng bootstrap token làm credential dữ liệu); duy nhất Bearer FAP key + checksum theo cùng key đạt 200 — policy CLI được xác nhận hai chiều và giữ nguyên; chi tiết tại coverage Phase 6.
+
+Nghiệm thu mục 3 và mở rộng endpoint hoàn tất ngày 24/10/2026 sau khi đối chiếu toàn bộ 82 route của APK với adapter (xem [phân tích khoảng trống](../docs/endpoint-gap-analysis.md)). `GetVersion` chốt contract bằng probe: GET bị 405, POST body `{}` bootstrap đạt 200 với data chuỗi ngắn, route v1 404 — mở cho `doctor --online` với `backend_version` trong report, `myfap version` vẫn offline; test doctor hiện có cập nhật cho hai probe và test mới chặn version không phải chuỗi, trong đó test bắt một lỗi thứ tự thật (probe version trước khi validate active) đã sửa. `GetStudentFeedbacks` mở `other feedbacks` theo envelope live 200/list rỗng và bytecode query `{CampusCode, rollNumber}`; RED 3 test → GREEN. Nhóm C/D của phân tích (donor/employee, login thay thế, OTA, Linking features) được ghi rõ là out of scope/QoL trong docs. Full suite 403 test, 399 đạt/4 skip, exit 0 trên Windows Python 3.11; kiểm CLI thật với session cá nhân: `other feedbacks` exit 0 (200, list rỗng), `doctor --online` exit 0 (`backend_version` chuỗi ngắn). Các finding v1 và mục 4–6 còn lại giữ nguyên trạng thái mở.
+
+Checkpoint nhóm đọc khép ngày 24/10/2026. (1) Build/Twine/validator/pip smoke chạy lại trên code mới: `uv build` wheel+sdist 0.2.0, Twine strict PASSED cả hai, artifact validator exit 0 với manifest SHA-256 `abcaef1b70e20a1e200b6458c58677d3d6d876c2b50819e6f5e8df73b900dae7` (không docs/tasks/tests/session/capture trong distribution), pip smoke hai venv sạch exit 0; full regression 403 test như trên. (2) Mapping/contract/coverage đã cập nhật kèm phân tích khoảng trống endpoint. (3) Quét toàn bộ lệnh đọc bằng **login/browser mới** với session tạm (hai lượt, đều đã logout): 29 lệnh chạy trong lượt chính — success có dữ liệu gồm cả **attendance detail positive đầu tiên** (param trích cục bộ từ courses) và **news search v2 list(50)**; data rỗng hợp lệ (marks, applications, training, feedbacks, marks --courseid str rỗng); survey giữ not-found theo contract; fee v2 list không rỗng nhưng **không đóng positive fee**; rating list exit 1 đúng thiết kế v1-only trên session v2; lệnh bảng semesters đạt ở lượt phụ (lượt chính sai cú pháp `--stdout` do harness, exit 2 không phải lỗi CLI). Chi tiết metadata tại coverage Phase 6; không dùng 200/nonempty để đóng positive fee/survey và không dùng v2 để đóng finding v1.
+
+Theo yêu cầu mở rộng của maintainer (24/10/2026), `transcript --pretty` phân tích HTML bảng điểm toàn khóa thành JSON cấu trúc: mỗi bảng giữ header riêng và hàng keyed theo header (bảng chính 10 cột `No`…`Status`, bảng phụ 7 cột), chuẩn hoá ` `. Schema chốt bằng phân tích cấu trúc dữ liệu thật trên máy cá nhân (chỉ in skeleton/tên cột, không in giá trị); fixture test tổng hợp theo schema đó. RED→GREEN 5 test (4 parser + 1 CLI seam, gồm nhánh không `--pretty` giữ nguyên chuỗi); full suite 408 test, 404 đạt/4 skip, exit 0; live `--pretty` cho 2 bảng 49+2 dòng đúng header thật, mặc định vẫn giữ chuỗi HTML theo contract cũ.
+
+Nghiệm thu mục 6 hoàn tất ngày 24/10/2026, trừ hộp cuối chờ maintainer. (1) RED→GREEN ghi cho từng feature mới (feedbacks 3 test, doctor GetVersion, transcript --pretty 5 test) qua CLI thật + HTTP giả, fixture tổng hợp; mutation check trên worktree tạm 3/3 bị test bắt: đổi casing query `semester`→`Semester` ở `get_courses`, đổi signer SearchNews từ type sang `MAGIC_ID`, bỏ guard no-retry trong `_get` — đều làm focused test fail rồi khôi phục. (2) `uv sync --locked --group ci` sạch; full suite **408 test, 404 đạt/4 skip, exit 0 trên cả Python 3.11 lẫn 3.9** (venv 3.9 tạm riêng); `git diff --check` sạch. (3) Build/Twine/validator/pip smoke chạy lại trên commit cuối: manifest SHA-256 `b15ff78b0a7fcca70b249258dbcd4479253bc702eace8bc7b079879caa848131`; CI GitHub Actions đạt trên commit code `8529176` (matrix Ubuntu/Windows × Python 3.9/3.11). (4) Lượt review thứ hai có cấu trúc trên toàn bộ diff PR (14 file code/test, +1355/−30) theo 4 trục: query contract, credential và write safety sạch (khớp mutation và test); parser ghi 4 finding robustness (rowspan rác, `isOnline` boolean, slot vượt nửa đêm, sanitize tên file xuất) — đã ghi vào CHANGELOG known issues và TODO, không phải lỗ hổng bảo mật, chờ maintainer quyết sửa trước `0.2.0` hay nhận known issue. Giới hạn trung thực: kênh agent review độc lập bị giới hạn concurrency của tài khoản sau 4 lần thử, lượt review này do session reviewer thực hiện. README/CHANGELOG/coverage cập nhật theo đúng kết quả. (5) PR #10 Draft từ nhánh riêng; mọi commit push đều có comment SHA/lệnh/exit code/giới hạn.
+
+Maintainer nghiệm thu phạm vi Phase 6 ngày 24/10/2026 qua hai quyết định ghi rõ: (a) **chấp nhận phạm vi** — toàn bộ read student v1+v2, doctor, transcript --pretty; mục 4–5 giữ gate vì không thể xác minh với tài khoản hiện tại; 7 lỗi v1 là known issues; positive fee/survey hoãn; (b) **chọn sửa 4 finding robustness trước phát hành** thay vì ghi known issues — đã sửa kèm 5 test regression (rowspan rác coi như 1; ICS nhận `isOnline` boolean, slot vượt nửa đêm kết thúc sang hôm sau, `slotTime` thiếu dấu gạch báo lỗi rõ; `save_output` thay ký tự đường dẫn trong tên file), full suite 413 test, 409 đạt/4 skip, exit 0.
+
+Bổ sung `exams --ics` và cờ `--full` (24/10/2026) theo yêu cầu mở rộng cuối của maintainer: `convert_exams_to_ics` tạo iCalendar RFC 5545 chuẩn CRLF, UID/DTSTAMP UTC, giờ Việt Nam, tiêu đề `mã_môn (kỳ_thi)`, vượt nửa đêm kết thúc hôm sau; mặc định đưa đầy đủ thông tin quan trọng (Môn, Phòng thi `roomNo`, Ngày công bố `dateofPublication`), chỉ ẩn mã slot UUID, ghi chú phụ và điểm danh; cờ `--full` kèm toàn bộ thông tin phụ vào sự kiện lịch; JSON mặc định giữ nguyên 100% dữ liệu gốc; RED→GREEN qua converter và CLI seam; full suite 420 test, 416 đạt/4 skip, exit 0; live đạt 7 sự kiện thật trên tài khoản kiểm chứng. Theo yêu cầu của maintainer, PR #10 **giữ nguyên Draft và không tự ready/merge/tag/publish**; các bước đó do maintainer thực hiện khi sẵn sàng.
diff --git a/tasks/todo.md b/tasks/todo.md
index 12316d7..18957ec 100644
--- a/tasks/todo.md
+++ b/tasks/todo.md
@@ -30,3 +30,59 @@ Khi có điều kiện kiểm chứng, dùng session tạm, ghi rõ API version/
Theo dõi triển khai, kết quả kiểm tra và gate dịch vụ còn mở tại [phase5.md](phase5.md). [Runbook phát hành](../docs/releasing.md) mô tả kiểm tag/version/artifact, Trusted Publishing, retry và TestPyPI; [CHANGELOG.md](../CHANGELOG.md) giữ release notes cùng known issues.
Chuyển Phase 5 không tự đóng ba lỗi live v1, không xác nhận positive fee/survey và không cho phép tạo/push tag hoặc publish. Maintainer phải duyệt phạm vi hỗ trợ và các gate phát hành trước khi thực hiện.
+
+## Mở rộng command và endpoint Phase 6
+
+Theo quyết định ngày 23/10/2026, **chưa tag/publish cho đến sau khi hoàn thiện và nghiệm thu phạm vi Phase 6**. PR #9 đã merge tại `75fc7b4aa33a13b9b39eab898f61e2e693f4baf9`; đó là pipeline chuẩn bị, không phải release. Giữ baseline `0.2.0`, v1 mặc định/v2 opt-in.
+
+Checklist, tiêu chí và gate bằng chứng nằm tại [phase6.md](phase6.md). Các mục sau chỉ được đánh dấu khi có kết quả tương ứng:
+
+- [x] Hoàn thiện các lát cắt đọc: courses, subjects theo kỳ, balance và news search, giữ hành vi command cũ (nghiệm thu 24/10/2026).
+- [x] Hoàn thiện transcript/training và marks summary sau khi chốt các ngoại lệ credential/response; không đoán query hoặc schema (nghiệm thu 24/10/2026, bổ sung `transcript --pretty`).
+- [x] Bổ sung photo JSON và doctor an toàn; không tự fetch/decode ảnh hoặc refresh session khi chẩn đoán local (nghiệm thu 24/10/2026, mở `doctor --online` với `GetVersion`).
+- [ ] Chốt rating/push/feedback theo gate schema/capability; không mở write hoặc ghi live khi chưa đủ bằng chứng/xác nhận. (Tám (8) hộp việc ở mục 4–5 của `phase6.md` tiếp tục **giữ gate/unsupported có chủ đích** do tài khoản kiểm chứng trả danh sách rỗng, không thể xác minh positive schema/ack).
+- [x] Bổ sung xuất lịch thi `exams --ics` (RFC 5545, CRLF, UTC UID/DTSTAMP) và cờ `--full` (hoàn tất 26/10/2026).
+- [x] Kiểm regression, artifact, CI và live đọc riêng; giữ nguyên mọi skip/failure/unverified và TODO v1/positive fee/survey ở trên (420 test đạt trên Python 3.9/3.11).
+- [x] Đồng bộ tài liệu và đóng các điểm lệch phạm vi trước merge (Pre-merge Docs Sync):
+ - [x] Khớp lại ghi chú mục 4–5 trong `tasks/phase6.md` (khẳng định 8 hộp việc giữ gate/unsupported có chủ đích, không tick khi chưa có schema live).
+ - [x] Chuẩn hóa tuyên bố trong `docs/endpoint-gap-analysis.md` (ghi nhận CLI phủ toàn bộ thao tác đọc sinh viên ngoại trừ `GetStudentFeedbackForm`).
+ - [x] Đồng bộ thứ tự phát hành trong `docs/releasing.md` (khớp quyết định phát hành sau khi nghiệm thu phạm vi Phase 6).
+- [x] Cập nhật Draft PR Phase 6; mỗi commit push có comment ngay sau commit, không tự merge/tag/publish.
+- [ ] Maintainer duyệt phạm vi Phase 6 và các gate dịch vụ Phase 5 trước khi phát hành thật.
+
+### Lỗi live v1 mới ngày 24/10/2026
+
+Các command đã chạy thật trên v1/APHL sau login mới; chi tiết tại [coverage Phase 6](../docs/phase6-coverage.md#live-đọc-v1aphl-ngày-24102026). Không dùng kết quả v2 hoặc fixture để đóng các mục này:
+
+- [ ] Xác định nguyên nhân GetCourseOfSemester HTTP 404; request hiện giữ casing/signing theo caller v1.
+- [ ] Xác định nguyên nhân GetSemesterMark HTTP 404; không tự thêm checksum/kỳ hoặc đổi route để thử.
+- [ ] Xác định nguyên nhân SearchNews HTTP 200/body 201, data null; không coi là hết phiên hoặc empty hợp lệ.
+- [ ] Xác định nguyên nhân GetDiemphongtrao HTTP 200/body 201, data null; không bỏ lỗi hoặc fallback v2.
+
+Cùng lượt, subjects/balance/rating list đọc được và student sau refresh đạt 200/200. Transcript rỗng, photo null và rating list rỗng không xác nhận positive schema hoặc ID hợp lệ cho submit. Session/lock/thư mục tạm đã dọn; chỉ metadata được ghi, không raw response/identity/credential.
+
+## Mục 4–5 Phase 6 khó thực hiện với tài khoản hiện tại
+
+Theo đánh giá của maintainer ngày 24/10/2026, **các mục 4 (rating/push) và 5 (feedback đầy đủ) của [phase6.md](phase6.md) không thể thực hiện hoặc xác minh bằng tài khoản hiện tại**:
+
+- **Rating submit (`AddRate`)**: rating list v1 trả danh sách rỗng — không có rateid/positive item để đối chiếu input schema và ack.
+- **Push register (`UpdateTokedevices`)**: thao tác ghi thiết bị; cần contract student đã chốt và xác nhận riêng trước khi live ghi.
+- **`GetStudentFeedbackForm`**: `other feedbacks` trả list rỗng — không có feedbackId thật; không đoán ID theo quy tắc plan.
+- **`SubmitStudentFeedback`**: cần feedback đang mở để có form/ack hợp lệ.
+- **Donor/employee và login thay thế** (`GetNotificationByDonor`, `GetTokenWithEmp`, `UpdateTokenDonor`, Google/username/FeIdCode): đã ghi out of scope tại [phân tích khoảng trống endpoint](../docs/endpoint-gap-analysis.md), không dự định triển khai trong Phase 6.
+
+Hệ quả khi chốt phạm vi Phase 6 và phát hành `0.2.0`: Tám (8) hộp việc ở mục 4–5 trong `tasks/phase6.md` tiếp tục giữ trạng thái **gate/unsupported có chủ đích** (không tick trong `phase6.md`), không đánh dấu hoàn tất và không mở generic submit; `docs/endpoint-gap-analysis.md` đã chuẩn hóa tuyên bố phủ toàn bộ đọc sinh viên ngoại trừ `GetStudentFeedbackForm`; maintainer duyệt phát hành với known issues này. Khi có tài khoản hoặc dữ liệu phù hợp:
+
+- [ ] Thu thập input schema và ack của `AddRate` (v1 checksum `rateid`, v2 query `Authen`, body `{}`) và các form feedback theo [phase6-write-gates.md](../docs/phase6-write-gates.md) trước khi mở command.
+- [ ] `push register --token-file` cần contract student đã chốt và xác nhận riêng của người dùng trước khi live ghi; token thiết bị chỉ đọc từ regular file, không đưa vào argv/preview/log/error.
+
+Các gate và trình tự validate → capability → preview → confirmation → auth vẫn áp dụng; không cố tình thử ghi để tạo dữ liệu, không coi list rỗng là route lỗi, và việc chưa xác minh được không tự đóng cũng không nới gate.
+
+## Finding robustness từ review Phase 6 (24/10/2026)
+
+Lượt review lượt hai trên toàn bộ diff PR #10 theo 4 trục (query/credential/parser/write safety): query contract, credential và write safety sạch; parser có bốn finding, đều không phải lỗ hổng bảo mật (CLI chạy bởi chính người dùng trên máy họ). Maintainer quyết định sửa trước khi tag `0.2.0` hay phát hành với known issues:
+
+- [x] `parse_marks_html` crash khi `rowspan` không phải số nguyên (`myfap/parsers.py`) — **đã sửa 24/10/2026**: giá trị rác coi như 1, kèm test regression.
+- [x] ICS: `isOnline` boolean mất nhãn "(Online)"; slot vượt nửa đêm và `slotTime` không dấu gạch — **đã sửa 24/10/2026**: nhận boolean, slot kết thúc sang ngày hôm sau, lỗi `slotTime` có thông báo rõ; kèm test.
+- [x] `save_output` sanitize tên file xuất — **đã sửa 24/10/2026**: thay `/`, `\` và NUL bằng `_`, file luôn nằm trong thư mục `--output`; kèm test.
+- [x] (low) Test nhánh `transcript --pretty` khi data không phải HTML — **đã có**: test CLI seam phủ cả nhánh giữ nguyên chuỗi gốc.
diff --git a/tests/test_api_session.py b/tests/test_api_session.py
index ae33b0a..37ef131 100644
--- a/tests/test_api_session.py
+++ b/tests/test_api_session.py
@@ -11,25 +11,41 @@
AUTHENTICATED_READ_CASES = (
(api.MyFapEssential, "get_semesters", (), "GetSemester"),
(api.MyFapEssential, "get_news", (), "GetTop10News"),
+ (api.MyFapEssential, "get_news", (1, "synthetic"), "SearchNews"),
(api.MyFapOther, "check_open_feedback", (), "CheckOpenFeedBack"),
(api.MyFapOther, "check_update_profile", (), "CheckUpdateProfile"),
(api.MyFapOther, "get_notification", (), "GetNotificationByRoll"),
(api.MyFapOther, "get_fee", (), "GeFeeByRoll"),
+ (api.MyFapOther, "get_balance", (), "GetBalance"),
+ (api.MyFapOther, "get_ratings", (), "GetStudentRate"),
(api.MyFapOther, "get_subjects", (), "GetSubjets"),
+ (api.MyFapOther, "get_subjects", ("Fall2026",), "GetSubjectBySemester"),
(api.MyFapClient, "get_schedule", ("Fall2026",), "GetActivityStudent"),
(api.MyFapClient, "get_marks", ("Fall2026",), "GetStudentMark"),
+ (api.MyFapClient, "get_courses", ("Fall2026",), "GetCourseOfSemester"),
(api.MyFapClient, "get_mark_by_course", ("123",), "GetMarkByCourse"),
(api.MyFapClient, "get_exams", ("Fall2026",), "GetScheduleExam"),
(api.MyFapClient, "get_schedule_by_week", (42, "Fall2026", 2026), "GetActivityStudentByWeek"),
(api.MyFapClient, "get_attendances", ("Fall2026",), "GetStudentAttendances"),
(api.MyFapClient, "get_course_attendance", ("Fall2026", "TEST101", "DEMO01"), "getCourseAttendance"),
(api.MyFapClient, "get_applications", (), "GetApplication"),
+ (api.MyFapClient, "get_transcript", (), "AcademicTranscript"),
+ (api.MyFapClient, "get_photo", (), "RetriveImage"),
+ (api.MyFapClient, "get_training", ("Fall2026",), "GetDiemphongtrao"),
(api.MyFapClient, "get_student_info", (), "GetStudentById"),
(api.MyFapClient, "get_campus_info", (), "GetCampusInfo"),
)
class ApiErrorPolicyTests(unittest.TestCase):
+ def test_balance_v1_expiry_is_recognized_only_for_exact_token_invalid(self):
+ with self.assertRaises(api.ApiSessionExpiredError):
+ api.read_response(response({"code": 201, "message": "Token invalid", "data": None}),
+ api_version="v1", operation="GetBalance")
+ with self.assertRaises(api.ApiOperationError):
+ api.read_response(response({"code": 201, "data": None}),
+ api_version="v1", operation="GetBalance")
+
def test_authenticated_v1_reads_recognize_201_token_invalid_with_actual_http_status(self):
for _, _, _, operation in AUTHENTICATED_READ_CASES:
for code in (201, "201"):
@@ -39,7 +55,7 @@ def test_authenticated_v1_reads_recognize_201_token_invalid_with_actual_http_sta
self.assertEqual(caught.exception.status_code, 200)
def test_other_v1_body_201_and_401_are_operation_errors_even_with_expiry_message(self):
- for operation in ("GetAllActiveCampus", "GetWeekByDate", "AuthenticationByFeId", "GetRequiredSurvey", "AddRate", "GetBalance", "UnknownOperation"):
+ for operation in ("GetAllActiveCampus", "GetWeekByDate", "AuthenticationByFeId", "GetRequiredSurvey", "AddRate", "UnknownOperation"):
for code in (201, "201", 401, "401"):
with self.subTest(operation=operation, code=code):
with self.assertRaises(api.ApiOperationError) as caught:
diff --git a/tests/test_cli_output.py b/tests/test_cli_output.py
index e89e2b5..7f214fd 100644
--- a/tests/test_cli_output.py
+++ b/tests/test_cli_output.py
@@ -106,7 +106,8 @@ def test_root_group_and_command_help_preserve_unicode_with_legacy_stdout(self):
with patch("myfap.cli.get_auth", side_effect=AssertionError("help must not load auth")), patch("requests.Session.request", side_effect=AssertionError("help must not call HTTP")):
app()
"""
- for command in ([], ["info"], ["info", "student"], ["other", "survey"], ["schedule"]):
+ for command in ([], ["info"], ["info", "student"], ["other", "survey"], ["schedule"],
+ ["other", "training"], ["other", "rating"], ["other", "rating", "list"]):
for encoding, utf8 in (("cp1252:strict", "0"), ("utf-8", "1")):
with self.subTest(command=command, encoding=encoding):
result = subprocess.run(
diff --git a/tests/test_parsers.py b/tests/test_parsers.py
index 929259f..bad246f 100644
--- a/tests/test_parsers.py
+++ b/tests/test_parsers.py
@@ -71,6 +71,70 @@ def test_legacy_three_columns_with_category_are_preserved(self):
self.assertEqual(parse_marks_html(html), [{"category": "Final", "item": "FE", "value": "7.3"}])
+ def test_garbage_rowspan_does_not_crash_and_keeps_own_row(self):
+ for rowspan in ("2.0", "abc", ""):
+ with self.subTest(rowspan=rowspan):
+ html = ("| Item | Weight | Value | "
+ f"| Quiz | Q1 | 10% | 8 | "
+ "| Q2 | 20% | 7 | ")
+ rows = parse_marks_html(html)
+ self.assertEqual(rows[0], {"category": "Quiz", "item": "Q1", "weight": "10%", "value": "8"})
+
+
+class TranscriptHtmlTests(unittest.TestCase):
+ MAIN_HEADERS = ["No", "Term", "Semester", "Subject Code", "prerequisite",
+ "Replaced Subject", "Subject Name", "Credit", "Grade", "Status"]
+ EXTRA_HEADERS = ["No", "Semester", "SubjectCode", "SubjectName", "Credit", "Grade", "Status"]
+
+ @staticmethod
+ def fixture():
+ main = (
+ " " + "".join(f"| {v} | " for v in
+ ("1", "202", "Fall2026", "PRO192", "", "", "Object Oriented Programming", "3", "8.5", "Passed")) + " "
+ "" + "".join(f"| {v} | " for v in
+ ("2", "202", "Fall2026", "MAL202", "PRO192", "", "Linear Algebra", "3", "", "Not Passed")) + " "
+ )
+ extra = (
+ "" + "".join(f"| {v} | " for v in
+ ("1", "Spring2027", "SSG103", "Soft Skill", "2", "7.0", "Passed")) + " "
+ )
+ def header(names):
+ return "" + "".join(f"| {n} | " for n in names) + " "
+ return (
+ "" + header(TranscriptHtmlTests.MAIN_HEADERS) + main + " "
+ "" + header(TranscriptHtmlTests.EXTRA_HEADERS) + extra + " "
+ )
+
+ def setUp(self):
+ from myfap.parsers import parse_transcript_html
+ self.parse = parse_transcript_html
+
+ def test_each_table_keeps_own_headers_and_keyed_rows(self):
+ tables = self.parse(self.fixture())
+ self.assertEqual([table["headers"] for table in tables], [self.MAIN_HEADERS, self.EXTRA_HEADERS])
+ self.assertEqual(tables[0]["rows"][0], {
+ "No": "1", "Term": "202", "Semester": "Fall2026", "Subject Code": "PRO192",
+ "prerequisite": "", "Replaced Subject": "", "Subject Name": "Object Oriented Programming",
+ "Credit": "3", "Grade": "8.5", "Status": "Passed",
+ })
+ self.assertEqual(len(tables[0]["rows"]), 2)
+ self.assertEqual(tables[1]["rows"][0]["SubjectName"], "Soft Skill")
+ self.assertEqual(len(tables[1]["rows"]), 1)
+
+ def test_html_entities_are_decoded_and_extra_cells_get_stable_keys(self):
+ tables = self.parse("")
+ self.assertEqual(tables[0]["rows"][0], {"A": "Số 1", "B": "x", "Column3": "thừa"})
+
+ def test_input_without_table_returns_empty_list(self):
+ self.assertEqual(self.parse("PRIVATE [not a table] "), [])
+ self.assertEqual(self.parse(""), [])
+
+ def test_data_rows_before_header_are_ignored(self):
+ tables = self.parse("")
+ self.assertEqual(tables[0]["headers"], ["Only"])
+ self.assertEqual(tables[0]["rows"], [{"Only": "ok"}])
+
class ScheduleParserTests(unittest.TestCase):
def test_saved_ics_keeps_line_endings_for_independent_reader(self):
@@ -150,6 +214,136 @@ def test_ics_preserves_vietnam_time_and_session_details(self):
"Room: Demo room", "Meet URL: https://example.invalid/meet",
]))
+ def test_boolean_is_online_still_marks_online_title(self):
+ data = json.loads((FIXTURES / "schedule_valid.json").read_text(encoding="utf-8"))
+ data["data"][0]["isOnline"] = True
+
+ event = next(iter(Calendar(convert_schedule_to_ics(data)).events))
+
+ self.assertEqual(event.name, "TEST101 (Online)")
+
+ def test_overnight_slot_wraps_end_to_next_day(self):
+ data = json.loads((FIXTURES / "schedule_valid.json").read_text(encoding="utf-8"))
+ data["data"][0]["slotTime"] = "(23:30-0:50)"
+
+ event = next(iter(Calendar(convert_schedule_to_ics(data)).events))
+
+ # 23:30 và 0:50 (hôm sau) giờ Việt Nam = 16:30 và 17:50 UTC cùng ngày 15/10.
+ self.assertEqual(event.begin.datetime, datetime(2026, 10, 15, 16, 30, tzinfo=timezone.utc))
+ self.assertEqual(event.end.datetime, datetime(2026, 10, 15, 17, 50, tzinfo=timezone.utc))
+ self.assertEqual((event.end.datetime - event.begin.datetime).total_seconds(), 80 * 60)
+
+ def test_slot_without_separator_raises_clear_message(self):
+ data = json.loads((FIXTURES / "schedule_valid.json").read_text(encoding="utf-8"))
+ data["data"][0]["slotTime"] = "7:30"
+
+ with self.assertRaises(ValueError) as caught:
+ convert_schedule_to_ics(data)
+ self.assertIn("slotTime", str(caught.exception))
+ self.assertIn("7:30-9:50", str(caught.exception))
+
+
+class ExamsParserTests(unittest.TestCase):
+ @staticmethod
+ def fixture_data(**overrides):
+ row = {
+ "subjectCode": "TEST101", "realSubject": "TEST101", "subjectName": "Môn thử nghiệm",
+ "date": "2026-10-20T00:00:00", "slot": "Synthetic slot text (7h30-9h50)", "time": "7h30-9h50",
+ "note": "", "roomNo": "SY-101", "dateofPublication": "2026-10-01T00:00:00",
+ "kythi": "FE", "note_Attendance": "", "isGraduated": False,
+ }
+ row.update(overrides)
+ return {"code": "200", "data": [row]}
+
+ def setUp(self):
+ from myfap.parsers import convert_exams_to_ics
+ self.convert = convert_exams_to_ics
+
+ def test_valid_exams_build_calendar_with_uid_dtstamp_and_vietnam_time(self):
+ content = self.convert(self.fixture_data()).encode("utf-8")
+ calendar = IndependentCalendar.from_ical(content)
+ events = calendar.walk("VEVENT")
+ self.assertEqual(len(events), 1)
+ event = events[0]
+ self.assertEqual(str(event["SUMMARY"]), "TEST101 (FE)")
+ self.assertEqual(event.decoded("DTSTART"), datetime(2026, 10, 20, 0, 30, tzinfo=timezone.utc))
+ self.assertEqual(event.decoded("DTEND"), datetime(2026, 10, 20, 2, 50, tzinfo=timezone.utc))
+ properties = [name for name, _ in event.property_items()]
+ self.assertEqual(properties.count("UID"), 1)
+ self.assertEqual(properties.count("DTSTAMP"), 1)
+ self.assertRegex(event["DTSTAMP"].to_ical().decode("ascii"), r"^\d{8}T\d{6}Z$")
+ self.assertIn("Môn thử nghiệm".encode("utf-8"), content)
+ self.assertIn(b"\r\n", content)
+ self.assertNotIn(b"\r\r\n", content)
+
+ def test_default_ics_includes_room_and_publication_and_hides_slot_uuid(self):
+ content = self.convert(self.fixture_data(slot="42409f01-4993-4a0b-9302-2ccf5", roomNo="BE-201")).encode("utf-8")
+ event = IndependentCalendar.from_ical(content).walk("VEVENT")[0]
+ desc = str(event.get("DESCRIPTION"))
+ self.assertIn("Môn: Môn thử nghiệm", desc)
+ self.assertIn("Phòng: BE-201", desc)
+ self.assertIn("Ngày công bố: 2026-10-01", desc)
+ self.assertNotIn("42409f01", desc)
+ self.assertNotIn("Mã slot", desc)
+ self.assertEqual(str(event.get("LOCATION")), "BE-201")
+
+ def test_full_ics_includes_all_secondary_fields(self):
+ content = self.convert(self.fixture_data(
+ slot="42409f01-4993-4a0b-9302-2ccf5", roomNo="BE-201",
+ note="Mang thẻ SV", note_Attendance="Có mặt", isGraduated=True
+ ), full=True).encode("utf-8")
+ event = IndependentCalendar.from_ical(content).walk("VEVENT")[0]
+ desc = str(event.get("DESCRIPTION"))
+ self.assertIn("Môn: Môn thử nghiệm", desc)
+ self.assertIn("Ngày công bố: 2026-10-01", desc)
+ self.assertIn("Phòng: BE-201", desc)
+ self.assertIn("Mã slot: 42409f01-4993-4a0b-9302-2ccf5", desc)
+ self.assertIn("Ghi chú: Mang thẻ SV", desc)
+ self.assertIn("Ghi chú điểm danh: Có mặt", desc)
+ self.assertIn("Đã tốt nghiệp: Có", desc)
+ self.assertEqual(str(event.get("LOCATION")), "BE-201")
+
+ def test_time_with_spaces_and_parentheses_is_accepted(self):
+ for time in ("7h30 - 9h50", "(7h30-9h50)", " ( 7h30-9h50 ) "):
+ with self.subTest(time=time):
+ content = self.convert(self.fixture_data(time=time))
+ event = IndependentCalendar.from_ical(content).walk("VEVENT")[0]
+ self.assertEqual(event.decoded("DTSTART"), datetime(2026, 10, 20, 0, 30, tzinfo=timezone.utc))
+
+ def test_overnight_exam_wraps_end_to_next_day(self):
+ content = self.convert(self.fixture_data(time="23h30-0h50"))
+ event = IndependentCalendar.from_ical(content).walk("VEVENT")[0]
+ self.assertEqual((event.decoded("DTEND") - event.decoded("DTSTART")).total_seconds(), 80 * 60)
+
+ def test_invalid_root_or_rows_are_rejected_with_clear_errors(self):
+ cases = (
+ (None, "Invalid JSON format"),
+ ({}, "Invalid JSON format"),
+ ({"data": None}, "Invalid JSON format"),
+ ({"data": [None]}, "date, time"),
+ ({"data": [{}]}, "date, time"),
+ (self.fixture_data(subjectCode=" "), "date, time"),
+ (self.fixture_data(date="20/10/2026T00:00:00"), "date"),
+ (self.fixture_data(time="7:30-9:50"), "time"),
+ (self.fixture_data(time="7h30"), "time"),
+ (self.fixture_data(time="7h99-9h50"), "time"),
+ )
+ for data, message in cases:
+ with self.subTest(data=data, message=message):
+ with self.assertRaises(ValueError) as caught:
+ self.convert(data)
+ self.assertIn(message, str(caught.exception))
+
+
+class SaveOutputSanitizationTests(unittest.TestCase):
+ def test_server_influenced_filename_stays_inside_output_dir(self):
+ with TemporaryDirectory() as temporary, redirect_stderr(io.StringIO()):
+ save_output({"code": 200, "data": []}, "BangDiem_x/../../evil.json", temporary, False)
+ files = sorted(path.name for path in Path(temporary).iterdir())
+ self.assertEqual(files, ["BangDiem_x_.._.._evil.json"])
+ content = json.loads((Path(temporary) / files[0]).read_text(encoding="utf-8"))
+ self.assertEqual(content, {"code": 200, "data": []})
+
def test_empty_schedule_returns_valid_empty_calendar(self):
data = json.loads((FIXTURES / "schedule_empty.json").read_text(encoding="utf-8"))
diff --git a/tests/test_phase4_transport.py b/tests/test_phase4_transport.py
index 35e1b4a..dd318c4 100644
--- a/tests/test_phase4_transport.py
+++ b/tests/test_phase4_transport.py
@@ -98,7 +98,11 @@ def test_alias_is_explicit_and_only_supported_canonical_reads_are_exposed(self):
self.assertIn("GetWeekByDate", v2.READ_OPERATIONS)
self.assertIn("GetCourseAttendance", v2.READ_OPERATIONS)
self.assertNotIn("getCourseAttendance", v2.READ_OPERATIONS)
- for operation in ("GetVersion", "GetStudentFeedbackForm", "AddRate", "UpdateTokedevices"):
+ # GetVersion mở theo contract POST bootstrap đã probe 24/10/2026;
+ # GetStudentFeedbacks mở theo envelope live cùng ngày, item schema chưa positive.
+ self.assertIn("GetVersion", v2.BOOTSTRAP_OPERATIONS)
+ self.assertIn("GetStudentFeedbacks", v2.READ_OPERATIONS)
+ for operation in ("GetStudentFeedbackForm", "AddRate", "UpdateTokedevices"):
self.assertNotIn(operation, v2.SUPPORTED_OPERATIONS)
def test_invalid_read_queries_are_rejected_before_http_without_echo(self):
diff --git a/tests/test_phase6_doctor.py b/tests/test_phase6_doctor.py
new file mode 100644
index 0000000..63b635f
--- /dev/null
+++ b/tests/test_phase6_doctor.py
@@ -0,0 +1,127 @@
+"""Doctor public API: local-only by default, explicit bootstrap probe only."""
+import json
+import unittest
+from unittest.mock import Mock, patch
+
+import requests
+
+from myfap import diagnostics, v2
+from myfap.api import READ_OPERATIONS
+from myfap.errors import ApiError, ApiPayloadError
+
+
+class DoctorTests(unittest.TestCase):
+ def test_local_defaults_do_not_construct_auth_or_touch_session_or_http(self):
+ with patch("myfap.auth.MyFapAuth", side_effect=AssertionError("auth must stay offline")), \
+ patch("myfap.storage.SessionStore.read", side_effect=AssertionError("no session read")), \
+ patch("myfap.storage.SessionStore.lock", side_effect=AssertionError("no session lock")), \
+ patch("requests.Session.request", side_effect=AssertionError("no network")):
+ report = diagnostics.get_diagnostics()
+ self.assertEqual(report["api_version"], "v1")
+ self.assertEqual(report["api_version_source"], "default")
+ self.assertIsNone(report["campus"])
+ self.assertEqual(report["session_validation"], "not_checked")
+ self.assertEqual(report["available_operations"], sorted(READ_OPERATIONS))
+ self.assertEqual(report["online_probe"], {"requested": False})
+ self.assertIsInstance(report["package_version"], str)
+ self.assertEqual(set(report), {"package_version", "api_version", "api_version_source", "campus", "available_operations", "session_validation", "online_probe"})
+ json.dumps(report)
+
+ def test_local_explicit_version_and_campus_use_only_supplied_values(self):
+ with patch("requests.Session.request", side_effect=AssertionError("no network")):
+ report = diagnostics.get_diagnostics(api_version="v2", campus="TEST", timeout=3)
+ self.assertEqual(report["api_version"], "v2")
+ self.assertEqual(report["api_version_source"], "explicit")
+ self.assertEqual(report["campus"], "TEST")
+ self.assertEqual(report["available_operations"], sorted(v2.SUPPORTED_OPERATIONS | {"GetRequiredSurvey"}))
+ self.assertEqual(report["session_validation"], "not_checked")
+
+ def test_invalid_inputs_and_online_v1_fail_before_client_or_http(self):
+ for kwargs in ({"api_version": "v3"}, {"api_version": ""}, {"api_version": False},
+ {"campus": ""}, {"campus": " "}, {"campus": "TEST\nPRIVATE"},
+ {"campus": 3}, {"online": True}, {"api_version": "v1", "online": True}):
+ with self.subTest(kwargs=kwargs), \
+ patch("myfap.api.MyFapEssential", side_effect=AssertionError("no client")), \
+ patch("requests.Session.request", side_effect=AssertionError("no network")):
+ with self.assertRaises(ApiError):
+ diagnostics.get_diagnostics(**kwargs)
+
+ def test_online_probe_is_v2_bootstrap_not_user_session_or_selected_campus_validation(self):
+ for active in (True, False):
+ active_response = Mock(status_code=200, json=Mock(return_value={"code": 200, "data": active, "private": "MUST_NOT_APPEAR"}))
+ version_response = Mock(status_code=200, json=Mock(return_value={"code": 200, "data": "SYNTHETIC_BACKEND_VERSION", "private": "MUST_NOT_APPEAR"}))
+ with self.subTest(active=active), patch("requests.Session.request", side_effect=[active_response, version_response]) as request, \
+ patch("myfap.auth.MyFapAuth", side_effect=AssertionError("no auth")):
+ report = diagnostics.get_diagnostics(api_version="v2", campus="TEST", timeout=3, online=True)
+ self.assertEqual(report["campus"], "TEST")
+ self.assertEqual(report["session_validation"], "not_checked")
+ self.assertEqual(report["online_probe"], {"requested": True, "operation": "GetApiActive", "bootstrap_campus": "HN", "api_active": active, "backend_version": "SYNTHETIC_BACKEND_VERSION", "scope": "proxy_bootstrap_only"})
+ self.assertNotIn("MUST_NOT_APPEAR", json.dumps(report))
+ self.assertEqual(request.call_count, 2)
+ first, second = request.call_args_list
+ self.assertEqual(first.args, ("POST", "https://fap-proxy.fpt.edu.vn/MyFAP/GetApiActive"))
+ self.assertEqual(second.args, ("POST", "https://fap-proxy.fpt.edu.vn/MyFAP/GetVersion"))
+ for call in (first, second):
+ self.assertEqual(call.kwargs["headers"]["CampusCode"], "HN")
+ self.assertEqual(call.kwargs["params"], {})
+ self.assertEqual(call.kwargs["json"], {})
+ self.assertEqual(call.kwargs["timeout"], 3)
+ self.assertFalse(call.kwargs["allow_redirects"])
+
+ def test_online_probe_rejects_non_boolean_payload_without_echoing_it(self):
+ for value in (None, [], {}, 1, "true", "PRIVATE_PAYLOAD"):
+ response = Mock(status_code=200, json=Mock(return_value={"code": 200, "data": value}))
+ with self.subTest(value=value), patch("requests.Session.request", return_value=response) as request:
+ with self.assertRaises(ApiPayloadError) as caught:
+ diagnostics.get_diagnostics(api_version="v2", online=True)
+ self.assertNotIn("PRIVATE_PAYLOAD", str(caught.exception))
+ request.assert_called_once()
+
+ def test_online_probe_rejects_non_string_version_without_echoing_it(self):
+ active_response = Mock(status_code=200, json=Mock(return_value={"code": 200, "data": True}))
+ for value in (None, [], {}, 3, "", " "):
+ version_response = Mock(status_code=200, json=Mock(return_value={"code": 200, "data": value, "private": "PRIVATE_PAYLOAD"}))
+ with self.subTest(value=value), patch("requests.Session.request", side_effect=[active_response, version_response]) as request:
+ with self.assertRaises(ApiPayloadError) as caught:
+ diagnostics.get_diagnostics(api_version="v2", online=True)
+ self.assertNotIn("PRIVATE_PAYLOAD", str(caught.exception))
+ self.assertEqual(request.call_count, 2)
+
+ def test_probe_network_failure_is_safe_and_not_retried(self):
+ with patch("requests.Session.request", side_effect=requests.Timeout("PRIVATE_TOKEN")) as request:
+ with self.assertRaises(ApiError) as caught:
+ diagnostics.get_diagnostics(api_version="v2", online=True)
+ request.assert_called_once()
+ self.assertNotIn("PRIVATE_TOKEN", str(caught.exception))
+
+
+class DoctorCommandTests(unittest.TestCase):
+ def test_cli_local_does_not_load_auth_and_keeps_json_stdout(self):
+ from typer.testing import CliRunner
+ from myfap.cli import app
+ with patch("myfap.cli.get_auth", side_effect=AssertionError("no auth")), \
+ patch("requests.Session.request", side_effect=AssertionError("no network")):
+ result = CliRunner().invoke(app, ["--config", "PRIVATE_PATH", "doctor", "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ report = json.loads(result.stdout)
+ self.assertEqual(report["session_validation"], "not_checked")
+ self.assertEqual(report["online_probe"], {"requested": False})
+ self.assertNotIn("PRIVATE_PATH", result.output)
+
+ def test_cli_online_is_explicit_and_does_not_use_session(self):
+ from typer.testing import CliRunner
+ from myfap.cli import app
+ replies = [Mock(status_code=200, json=Mock(return_value={"code": 200, "data": True})),
+ Mock(status_code=200, json=Mock(return_value={"code": 200, "data": "SYNTHETIC_BACKEND_VERSION"}))]
+ with patch("myfap.cli.get_auth", side_effect=AssertionError("no auth")), \
+ patch("requests.Session.request", side_effect=replies) as request:
+ result = CliRunner().invoke(app, ["doctor", "--api-version", "v2", "--online", "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ report = json.loads(result.stdout)["online_probe"]
+ self.assertTrue(report["api_active"])
+ self.assertEqual(report["backend_version"], "SYNTHETIC_BACKEND_VERSION")
+ self.assertEqual(request.call_count, 2)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_phase6_reads.py b/tests/test_phase6_reads.py
new file mode 100644
index 0000000..4d43569
--- /dev/null
+++ b/tests/test_phase6_reads.py
@@ -0,0 +1,670 @@
+"""Phase 6 command contracts using real auth/client code and synthetic HTTP."""
+
+import inspect
+import json
+from pathlib import Path
+from tempfile import TemporaryDirectory
+import unittest
+from unittest.mock import patch
+from urllib.parse import urlsplit
+
+from typer.testing import CliRunner
+from rich.text import Text
+
+from myfap.cli import app
+from tests.test_api import response
+
+
+RUNNER_OPTIONS = {"mix_stderr": False} if "mix_stderr" in inspect.signature(CliRunner).parameters else {}
+
+
+class BalanceCommandTests(unittest.TestCase):
+ def setUp(self):
+ temporary = TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.path = Path(temporary.name) / "session.json"
+ self.runner = CliRunner(**RUNNER_OPTIONS)
+
+ def save_session(self, version):
+ session = {
+ "campus": "TEST", "account_type": "student", "authen_key": "FAKE_FAP_KEY",
+ "mssv": "TEST000", "email": "synthetic@example.invalid",
+ }
+ if version == "v2":
+ session["api_version"] = version
+ self.path.write_text(json.dumps(session), encoding="utf-8")
+
+ def test_balance_preserves_envelope_and_uses_exact_version_contract_without_term_lookup(self):
+ payload = {"code": 200, "data": {"synthetic": {"label": "Dữ liệu thử", "value": 7.5}}, "message": None}
+ for version in ("v1", "v2"):
+ with self.subTest(version=version):
+ self.save_session(version)
+ original = self.path.read_bytes()
+ with patch("requests.Session.request", return_value=response(payload)) as request, patch(
+ "myfap.api.create_checksum", return_value="FAKE_ROLL_CHECKSUM"
+ ) as checksum:
+ result = self.runner.invoke(app, ["--config", str(self.path), "other", "balance", "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(json.loads(result.stdout), payload)
+ request.assert_called_once()
+ self.assertEqual(request.call_args.args[0], "GET")
+ parsed = urlsplit(request.call_args.args[1])
+ self.assertEqual(parsed.path.rsplit("/", 1)[-1], "GetBalance")
+ self.assertEqual(parsed.query, "")
+ self.assertFalse(request.call_args.kwargs["allow_redirects"])
+ if version == "v1":
+ self.assertEqual(parsed.netloc, "api.fpt.edu.vn")
+ self.assertEqual(request.call_args.kwargs["params"], {
+ "campusCode": "TEST", "rollNumber": "TEST000", "Authen": "FAKE_FAP_KEY",
+ "checksum": "FAKE_ROLL_CHECKSUM",
+ })
+ checksum.assert_called_once_with("TEST000", "TEST")
+ else:
+ self.assertEqual(parsed.netloc, "fap-proxy.fpt.edu.vn")
+ self.assertEqual(request.call_args.kwargs["params"], {"CampusCode": "TEST", "rollNumber": "TEST000"})
+ self.assertEqual(request.call_args.kwargs["headers"]["Authorization"], "Bearer FAKE_FAP_KEY")
+ checksum.assert_not_called()
+ self.assertEqual(self.path.read_bytes(), original)
+ self.assertNotIn("FAKE_FAP_KEY", result.stdout + result.stderr)
+
+ def test_balance_accepts_nested_common_options_and_preserves_empty_data(self):
+ payload = {"code": "200", "data": []}
+ for version in ("v1", "v2"):
+ with self.subTest(version=version):
+ self.save_session(version)
+ with patch("requests.Session.request", return_value=response(payload)) as request:
+ result = self.runner.invoke(app, [
+ "other", "balance", "--config", str(self.path), "--api-version", version,
+ "--campus", "TEST", "--timeout", "31", "--stdout",
+ ])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(json.loads(result.stdout), payload)
+ request.assert_called_once()
+ self.assertEqual(request.call_args.args[0], "GET")
+ self.assertTrue(request.call_args.args[1].endswith("/GetBalance"))
+ self.assertEqual(request.call_args.kwargs["timeout"], 31.0)
+
+
+class CoursesCommandTests(unittest.TestCase):
+ def setUp(self):
+ temporary = TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.path = Path(temporary.name) / "session.json"
+ self.runner = CliRunner(**RUNNER_OPTIONS)
+
+ def save_session(self, version):
+ session = {
+ "campus": "TEST", "account_type": "student", "authen_key": "FAKE_FAP_KEY",
+ "mssv": "TEST000", "email": "synthetic@example.invalid",
+ }
+ if version == "v2":
+ session["api_version"] = version
+ self.path.write_text(json.dumps(session), encoding="utf-8")
+
+ def test_courses_preserves_data_and_uses_explicit_or_latest_semester(self):
+ payload = {"code": 200, "data": [{"synthetic": True}], "message": None}
+ semesters = [
+ {"semesterName": "Fall2025", "startDate": "2025-09-01", "termID": "zzzz-opaque-old"},
+ {"semesterName": "Fall2026", "startDate": "2026-09-01", "termID": "aaaa-opaque-new"},
+ ]
+
+ def reply(method, url, **kwargs):
+ operation = urlsplit(url).path.rsplit("/", 1)[-1]
+ return response({"code": 200, "data": semesters}) if operation == "GetSemester" else response(payload)
+
+ for version in ("v1", "v2"):
+ for explicit in (False, True):
+ with self.subTest(version=version, explicit=explicit):
+ self.save_session(version)
+ original = self.path.read_bytes()
+ options = ["--semester", "Summer&2026"] if explicit else []
+ with patch("requests.Session.request", side_effect=reply) as request, patch(
+ "myfap.api.create_checksum", return_value="FAKE_ROLL_CHECKSUM"
+ ) as checksum:
+ result = self.runner.invoke(app, ["--config", str(self.path), "courses", *options, "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(json.loads(result.stdout), payload)
+ operations = [urlsplit(call.args[1]).path.rsplit("/", 1)[-1] for call in request.call_args_list]
+ self.assertEqual(operations, ["GetCourseOfSemester"] if explicit else ["GetSemester", "GetCourseOfSemester"])
+ self.assertEqual(request.call_args.args[0], "GET")
+ parsed = urlsplit(request.call_args.args[1])
+ self.assertEqual(parsed.query, "")
+ self.assertFalse(request.call_args.kwargs["allow_redirects"])
+ semester = "Summer&2026" if explicit else "Fall2026"
+ if version == "v1":
+ self.assertEqual(parsed.netloc, "api.fpt.edu.vn")
+ self.assertEqual(request.call_args.kwargs["params"], {
+ "campusCode": "TEST", "rollNumber": "TEST000", "Authen": "FAKE_FAP_KEY",
+ "checksum": "FAKE_ROLL_CHECKSUM", "semester": semester,
+ })
+ self.assertEqual(checksum.call_args.args, ("TEST000", "TEST"))
+ else:
+ self.assertEqual(parsed.netloc, "fap-proxy.fpt.edu.vn")
+ self.assertEqual(request.call_args.kwargs["params"], {
+ "CampusCode": "TEST", "rollNumber": "TEST000", "semester": semester,
+ })
+ self.assertEqual(request.call_args.kwargs["headers"]["Authorization"], "Bearer FAKE_FAP_KEY")
+ checksum.assert_not_called()
+ self.assertEqual(self.path.read_bytes(), original)
+ self.assertNotIn("FAKE_FAP_KEY", result.stdout + result.stderr)
+
+ def test_courses_rejects_blank_explicit_semester_before_http(self):
+ for version in ("v1", "v2"):
+ with self.subTest(version=version):
+ self.save_session(version)
+ with patch("requests.Session.request") as request:
+ result = self.runner.invoke(app, [
+ "--config", str(self.path), "courses", "--semester", " ", "--stdout",
+ ])
+ self.assertIn(result.exit_code, (1, 2))
+ self.assertEqual(result.stdout, "")
+ self.assertIn("--semester", Text.from_ansi(result.stderr).plain)
+ request.assert_not_called()
+
+
+class SubjectsBySemesterTests(unittest.TestCase):
+ setUp = BalanceCommandTests.setUp
+ save_session = BalanceCommandTests.save_session
+
+ def test_subjects_option_preserves_legacy_and_signs_by_semester(self):
+ for version in ("v1", "v2"):
+ for semester in (None, "Fall&2026"):
+ with self.subTest(version=version, semester=semester):
+ self.save_session(version)
+ options = ["--semester", semester] if semester is not None else []
+ with patch("requests.Session.request", return_value=response({"code": 200, "data": []})) as request, \
+ patch("myfap.api.MAGIC_ID", "SYNTHETIC_MAGIC_ID"), \
+ patch("myfap.api.create_checksum", return_value="SYNTHETIC_CHECKSUM") as checksum:
+ result = self.runner.invoke(app, ["--config", str(self.path), "other", "subjects", *options, "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(json.loads(result.stdout), {"code": 200, "data": []})
+ request.assert_called_once()
+ operation = "GetSubjectBySemester" if semester is not None else "GetSubjets"
+ self.assertTrue(request.call_args.args[1].endswith('/' + operation))
+ query = request.call_args.kwargs["params"]
+ self.assertNotIn("rollNumber", query)
+ self.assertNotIn("semester", query)
+ self.assertEqual(query.get("Semester"), semester)
+ self.assertGreaterEqual(request.call_args.kwargs["timeout"], 30)
+ if version == "v1" and semester is not None:
+ checksum.assert_called_once_with(semester, "TEST")
+ if version == "v2":
+ self.assertEqual(query, {"CampusCode": "TEST", **({"Semester": semester} if semester else {})})
+
+ def test_blank_semester_is_rejected_before_http(self):
+ with patch("requests.Session.request") as request:
+ result = self.runner.invoke(app, ["other", "subjects", "--semester", " ", "--stdout"])
+ self.assertNotEqual(result.exit_code, 0)
+ self.assertIn("--semester", Text.from_ansi(result.stderr).plain)
+ request.assert_not_called()
+
+
+class SearchNewsTests(unittest.TestCase):
+ setUp = BalanceCommandTests.setUp
+ save_session = BalanceCommandTests.save_session
+
+ def test_search_uses_type_signing_and_preserves_unicode_query(self):
+ text = "Học phí & A+B%"
+ for version in ("v1", "v2"):
+ with self.subTest(version=version):
+ self.save_session(version)
+ payload = {"code": 200, "data": [{"synthetic": text}]}
+ with patch("requests.Session.request", return_value=response(payload)) as request, \
+ patch("myfap.api.create_checksum", return_value="SYNTHETIC_SEARCH_SIGNATURE") as checksum:
+ result = self.runner.invoke(app, ["--config", str(self.path), "news", "--search", text, "--type", "2", "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(json.loads(result.stdout), payload)
+ request.assert_called_once()
+ self.assertTrue(request.call_args.args[1].endswith("/SearchNews"))
+ query = request.call_args.kwargs["params"]
+ self.assertEqual(query["keysearch"], text)
+ self.assertEqual(query["type"], 2)
+ self.assertNotIn("rollNumber", query)
+ if version == "v1":
+ checksum.assert_called_once_with("2", "TEST")
+ else:
+ self.assertEqual(query, {"CampusCode": "TEST", "type": 2, "keysearch": text})
+
+ def test_empty_search_is_rejected_before_auth_and_http(self):
+ for value in ("", " "):
+ with self.subTest(value=value), patch("myfap.cli.get_auth") as auth, patch("requests.Session.request") as request:
+ result = self.runner.invoke(app, ["news", "--search", value, "--stdout"])
+ self.assertNotEqual(result.exit_code, 0)
+ self.assertIn("--search", Text.from_ansi(result.stderr).plain)
+ auth.assert_not_called()
+ request.assert_not_called()
+
+
+class TranscriptCommandTests(unittest.TestCase):
+ setUp = BalanceCommandTests.setUp
+ save_session = BalanceCommandTests.save_session
+
+ def test_transcript_uses_bound_key_without_semester_lookup(self):
+ for version in ("v1", "v2"):
+ with self.subTest(version=version):
+ self.save_session(version)
+ payload = {"code": 200, "data": [{"synthetic": "Toàn khóa"}]}
+ with patch("requests.Session.request", return_value=response(payload)) as request:
+ result = self.runner.invoke(app, ["--config", str(self.path), "transcript", "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(json.loads(result.stdout), payload)
+ request.assert_called_once()
+ self.assertTrue(request.call_args.args[1].endswith("/AcademicTranscript"))
+ query = request.call_args.kwargs["params"]
+ self.assertEqual(query["rollNumber"], "TEST000")
+ self.assertNotIn("Semester", query)
+ if version == "v2":
+ self.assertEqual(query, {"CampusCode": "TEST", "rollNumber": "TEST000"})
+ self.assertEqual(request.call_args.kwargs["headers"]["Authorization"], "Bearer FAKE_FAP_KEY")
+
+
+ def test_transcript_pretty_parses_html_and_default_keeps_raw_string(self):
+ from tests.test_parsers import TranscriptHtmlTests
+
+ html = TranscriptHtmlTests.fixture()
+ for options, expect_parsed in (([], False), (["--pretty"], True)):
+ with self.subTest(options=options):
+ self.save_session("v2")
+ payload = {"code": 200, "data": html}
+ with patch("requests.Session.request", return_value=response(payload)) as request:
+ result = self.runner.invoke(app, ["--config", str(self.path), "transcript", *options, "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ data = json.loads(result.stdout)["data"]
+ if expect_parsed:
+ self.assertEqual([table["headers"] for table in data],
+ [TranscriptHtmlTests.MAIN_HEADERS, TranscriptHtmlTests.EXTRA_HEADERS])
+ self.assertEqual(data[0]["rows"][0]["Subject Code"], "PRO192")
+ else:
+ self.assertEqual(data, html)
+ request.assert_called_once()
+ self.assertTrue(request.call_args.args[1].endswith("/AcademicTranscript"))
+
+
+class TrainingCommandTests(unittest.TestCase):
+ setUp = BalanceCommandTests.setUp
+ save_session = BalanceCommandTests.save_session
+
+ def test_training_uses_lowercase_semester_and_latest_resolver(self):
+ for version in ("v1", "v2"):
+ with self.subTest(version=version):
+ self.save_session(version)
+ payload = {"code": 200, "data": [{"synthetic": "Phong trào"}]}
+ def reply(method, url, **kwargs):
+ if url.endswith("/GetSemester"):
+ return response({"code": 200, "data": [{"semesterName": "Fall2026", "startDate": "2026-09-01"}]})
+ return response(payload)
+ with patch("requests.Session.request", side_effect=reply) as request:
+ result = self.runner.invoke(app, ["--config", str(self.path), "other", "training", "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(json.loads(result.stdout), payload)
+ self.assertEqual([call.args[1].rsplit('/', 1)[-1] for call in request.call_args_list],
+ ["GetSemester", "GetDiemphongtrao"])
+ query = request.call_args.kwargs["params"]
+ self.assertEqual(query["semester"], "Fall2026")
+ self.assertNotIn("Semester", query)
+ if version == "v2":
+ self.assertEqual(request.call_args.kwargs["headers"]["Authorization"], "Bearer FAKE_FAP_KEY")
+
+
+class PhotoCommandTests(unittest.TestCase):
+ setUp = BalanceCommandTests.setUp
+ save_session = BalanceCommandTests.save_session
+
+ def test_photo_preserves_opaque_json_without_fetching_or_decoding(self):
+ payload = {"code": 200, "data": "opaque&literal-not-a-url"}
+ for version in ("v1", "v2"):
+ with self.subTest(version=version):
+ self.save_session(version)
+ with patch("requests.Session.request", return_value=response(payload)) as request:
+ result = self.runner.invoke(app, ["--config", str(self.path), "info", "photo", "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(json.loads(result.stdout), payload)
+ request.assert_called_once()
+ self.assertTrue(request.call_args.args[1].endswith("/RetriveImage"))
+ self.assertEqual(request.call_args.kwargs["params"]["rollNumber"], "TEST000")
+
+
+class PublicReadValidationTests(unittest.TestCase):
+ def test_invalid_semester_is_rejected_by_public_api_before_http(self):
+ from types import SimpleNamespace
+ from unittest.mock import Mock
+ from myfap.api import MyFapClient, MyFapOther
+ from myfap.errors import ApiError
+ for version in ("v1", "v2"):
+ for value in (None, "", " ", False, 3, "TERM\nPRIVATE"):
+ for owner, method in ((MyFapClient, "get_courses"), (MyFapClient, "get_training"), (MyFapOther, "get_subjects")):
+ if method == "get_subjects" and value is None:
+ continue
+ with self.subTest(version=version, method=method, value=value):
+ session = Mock()
+ auth = SimpleNamespace(session=session, api_version=version, campus="TEST", account_type="student",
+ authen_key="FAKE_KEY", mssv="TEST000", ensure_bound=Mock())
+ with self.assertRaises(ApiError):
+ getattr(owner(auth), method)(value)
+ session.request.assert_not_called()
+ session.get.assert_not_called()
+
+
+class RatingListTests(unittest.TestCase):
+ setUp = BalanceCommandTests.setUp
+ save_session = BalanceCommandTests.save_session
+
+ def test_rating_list_v1_uses_read_contract_without_semester(self):
+ self.save_session("v1")
+ payload = {"code": 200, "data": [{"synthetic": "rating item"}]}
+ with patch("requests.Session.request", return_value=response(payload)) as request, \
+ patch("myfap.api.create_checksum", return_value="SYNTHETIC_RATE_LIST") as checksum:
+ result = self.runner.invoke(app, ["other", "rating", "list", "--config", str(self.path), "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(json.loads(result.stdout), payload)
+ request.assert_called_once()
+ self.assertEqual(request.call_args.args[0], "GET")
+ self.assertTrue(request.call_args.args[1].endswith("/GetStudentRate"))
+ self.assertEqual(request.call_args.kwargs["params"], {
+ "campusCode": "TEST", "rollNumber": "TEST000", "Authen": "FAKE_FAP_KEY", "checksum": "SYNTHETIC_RATE_LIST"})
+ checksum.assert_called_once_with("TEST000", "TEST")
+
+ def test_rating_list_v2_stub_is_rejected_before_session_load_or_http(self):
+ self.save_session("v2")
+ with patch("myfap.auth.MyFapAuth.load_session") as load, patch("requests.Session.request") as request:
+ result = self.runner.invoke(app, ["--config", str(self.path), "other", "rating", "list", "--stdout"])
+ self.assertEqual(result.exit_code, 1)
+ self.assertEqual(result.stdout, "")
+ self.assertIn("GetStudentRate", result.stderr)
+ load.assert_not_called()
+ request.assert_not_called()
+
+
+class V1ObservedFailureTests(unittest.TestCase):
+ setUp = BalanceCommandTests.setUp
+ save_session = BalanceCommandTests.save_session
+
+ def test_http_404_and_unexplained_201_remain_failures_without_refresh_or_fallback(self):
+ # Only status/shape from live; every input and session here is synthetic.
+ for command, operation, status, payload, message in (
+ (["courses", "--semester", "FAKE_TERM"], "GetCourseOfSemester", 404, None, "HTTP 404"),
+ (["marks", "--summary"], "GetSemesterMark", 404, None, "HTTP 404"),
+ (["news", "--search", "synthetic"], "SearchNews", 200, {"code": 201, "data": None}, "201"),
+ (["other", "training", "--semester", "FAKE_TERM"], "GetDiemphongtrao", 200, {"code": 201, "data": None}, "201"),
+ ):
+ with self.subTest(operation=operation):
+ self.save_session("v1")
+ before = self.path.read_bytes()
+ with patch("requests.Session.request", return_value=response(payload, status)) as request, \
+ patch("myfap.auth.MyFapAuth.refresh_session") as refresh:
+ result = self.runner.invoke(app, ["--config", str(self.path), *command, "--stdout"])
+ self.assertEqual(result.exit_code, 1)
+ self.assertEqual(result.stdout, "")
+ self.assertIn(message, Text.from_ansi(result.stderr).plain)
+ request.assert_called_once()
+ self.assertEqual(urlsplit(request.call_args.args[1]).netloc, "api.fpt.edu.vn")
+ self.assertTrue(request.call_args.args[1].endswith('/' + operation))
+ refresh.assert_not_called()
+ self.assertEqual(self.path.read_bytes(), before)
+
+
+class FeedbackListTests(unittest.TestCase):
+ setUp = BalanceCommandTests.setUp
+ save_session = BalanceCommandTests.save_session
+
+ def test_feedbacks_v2_reads_exact_contract_and_preserves_envelope(self):
+ self.save_session("v2")
+ payload = {"code": 200, "data": [{"synthetic": "feedback item"}]}
+ with patch("requests.Session.request", return_value=response(payload)) as request:
+ result = self.runner.invoke(app, ["--config", str(self.path), "other", "feedbacks", "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(json.loads(result.stdout), payload)
+ request.assert_called_once()
+ self.assertEqual(request.call_args.args[0], "GET")
+ self.assertTrue(request.call_args.args[1].endswith("/GetStudentFeedbacks"))
+ self.assertEqual(request.call_args.kwargs["params"], {"CampusCode": "TEST", "rollNumber": "TEST000"})
+ self.assertNotIn("Authen", request.call_args.kwargs["params"])
+ self.assertEqual(request.call_args.kwargs["headers"]["Authorization"], "Bearer FAKE_FAP_KEY")
+ self.assertNotIn("json", request.call_args.kwargs)
+
+ def test_feedbacks_preserves_empty_list(self):
+ self.save_session("v2")
+ payload = {"code": 200, "data": []}
+ with patch("requests.Session.request", return_value=response(payload)) as request:
+ result = self.runner.invoke(app, ["--config", str(self.path), "other", "feedbacks", "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(json.loads(result.stdout), payload)
+ request.assert_called_once()
+
+ def test_feedbacks_v1_is_rejected_before_http(self):
+ self.save_session("v1")
+ with patch("requests.Session.request") as request:
+ result = self.runner.invoke(app, ["--config", str(self.path), "other", "feedbacks", "--stdout"])
+ self.assertEqual(result.exit_code, 1)
+ self.assertEqual(result.stdout, "")
+ self.assertIn("GetStudentFeedbacks", Text.from_ansi(result.stderr).plain)
+ request.assert_not_called()
+
+
+class ExamsIcsCommandTests(unittest.TestCase):
+ setUp = BalanceCommandTests.setUp
+ save_session = BalanceCommandTests.save_session
+
+ ROW = {"subjectCode": "TEST101", "realSubject": "TEST101", "subjectName": "Môn thử nghiệm",
+ "date": "2026-10-20T00:00:00", "slot": "Synthetic slot (7h30-9h50)", "time": "7h30-9h50",
+ "note": "", "roomNo": "SY-101", "dateofPublication": "2026-10-01T00:00:00",
+ "kythi": "FE", "note_Attendance": "", "isGraduated": False}
+
+ def test_exams_ics_outputs_calendar_and_plain_keeps_json(self):
+ payload = {"code": 200, "data": [dict(self.ROW)]}
+ for options, expect_ics, expect_full in (
+ ([], False, False),
+ (["--ics"], True, False),
+ (["--ics", "--full"], True, True),
+ (["--full"], False, False),
+ ):
+ with self.subTest(options=options):
+ self.save_session("v2")
+ with patch("requests.Session.request", return_value=response(payload)) as request:
+ result = self.runner.invoke(app, ["--config", str(self.path), "exams", "--semester", "FAKE_TERM", *options, "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ if expect_ics:
+ self.assertTrue(result.stdout.startswith("BEGIN:VCALENDAR"))
+ self.assertIn("BEGIN:VEVENT", result.stdout)
+ self.assertIn("TEST101 (FE)", result.stdout)
+ self.assertIn("Môn: Môn thử nghiệm", result.stdout)
+ self.assertIn("Phòng: SY-101", result.stdout)
+ self.assertIn("Ngày công bố: 2026-10-01", result.stdout)
+ if expect_full:
+ self.assertIn("Mã slot: Synthetic slot", result.stdout)
+ else:
+ self.assertNotIn("Mã slot", result.stdout)
+ else:
+ self.assertEqual(json.loads(result.stdout), payload)
+ # Mặc định JSON luôn bảo toàn toàn bộ thông tin gốc kể cả slot/UUID
+ self.assertEqual(json.loads(result.stdout)["data"][0]["slot"], "Synthetic slot (7h30-9h50)")
+ request.assert_called_once()
+ self.assertTrue(request.call_args.args[1].endswith("/GetScheduleExam"))
+ query = request.call_args.kwargs["params"]
+ self.assertEqual(query.get("Semester"), "FAKE_TERM")
+
+
+class ReadSliceAcceptanceTests(unittest.TestCase):
+ """Nghiệm thu nhóm mục 1: header contract và ma trận lỗi tại seam CLI."""
+
+ COMMANDS = (
+ (["other", "balance"], "GetBalance"),
+ (["courses", "--semester", "FAKE_TERM"], "GetCourseOfSemester"),
+ (["other", "subjects", "--semester", "FAKE_TERM"], "GetSubjectBySemester"),
+ (["news", "--search", "synthetic"], "SearchNews"),
+ )
+
+ setUp = BalanceCommandTests.setUp
+ save_session = BalanceCommandTests.save_session
+
+ def test_v2_headers_carry_client_contract_and_get_has_no_body(self):
+ self.save_session("v2")
+ for command, operation in self.COMMANDS:
+ with self.subTest(operation=operation):
+ with patch("requests.Session.request", return_value=response({"code": 200, "data": []})) as request:
+ result = self.runner.invoke(app, ["--config", str(self.path), *command, "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(json.loads(result.stdout), {"code": 200, "data": []})
+ self.assertEqual(request.call_args.args[0], "GET")
+ self.assertTrue(request.call_args.args[1].endswith("/" + operation))
+ headers = request.call_args.kwargs["headers"]
+ self.assertEqual(headers["ClientCode"], "MyFAP")
+ self.assertEqual(headers["CampusCode"], "TEST")
+ self.assertEqual(headers["Authorization"], "Bearer FAKE_FAP_KEY")
+ signature, separator, timestamp = headers["Checksum"].partition(":")
+ self.assertEqual(separator, ":")
+ self.assertTrue(signature and signature.isascii())
+ self.assertTrue(timestamp and timestamp.isascii() and timestamp.isdecimal())
+ self.assertNotIn("json", request.call_args.kwargs)
+ self.assertNotIn("Content-Type", headers)
+
+ def test_expiry_retries_once_with_fresh_credential_at_cli_seam(self):
+ signals = (
+ ("v1", {"code": 201, "message": "Token invalid", "data": None}, 200),
+ ("v2", {"code": 401, "data": None}, 200),
+ ("v2", {"code": 200, "data": []}, 401),
+ )
+ for command, operation in self.COMMANDS:
+ for version, expired, status in signals:
+ with self.subTest(operation=operation, version=version, status=status):
+ self.save_session(version)
+ original = self.path.read_bytes()
+
+ def refresh(auth):
+ auth.authen_key = "FAKE_NEW_KEY"
+ return True
+
+ with patch("requests.Session.request",
+ side_effect=[response(expired, status), response({"code": 200, "data": []})]) as request, \
+ patch("myfap.auth.MyFapAuth.refresh_session", autospec=True, side_effect=refresh) as rotation:
+ result = self.runner.invoke(app, ["--config", str(self.path), *command, "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(json.loads(result.stdout), {"code": 200, "data": []})
+ self.assertEqual(request.call_count, 2)
+ rotation.assert_called_once()
+ first, second = request.call_args_list
+ self.assertTrue(first.args[1].endswith("/" + operation))
+ self.assertTrue(second.args[1].endswith("/" + operation))
+ if version == "v1":
+ self.assertEqual(first.kwargs["params"]["Authen"], "FAKE_FAP_KEY")
+ self.assertEqual(second.kwargs["params"]["Authen"], "FAKE_NEW_KEY")
+ else:
+ self.assertEqual(first.kwargs["headers"]["Authorization"], "Bearer FAKE_FAP_KEY")
+ self.assertEqual(second.kwargs["headers"]["Authorization"], "Bearer FAKE_NEW_KEY")
+ self.assertNotEqual(first.kwargs["headers"]["Checksum"], second.kwargs["headers"]["Checksum"])
+ self.assertEqual(
+ {key: value for key, value in first.kwargs["params"].items() if key != "Authen"},
+ {key: value for key, value in second.kwargs["params"].items() if key != "Authen"},
+ )
+ self.assertEqual(self.path.read_bytes(), original)
+ self.assertNotIn("FAKE_FAP_KEY", result.stdout + result.stderr)
+
+ def test_second_expiry_stops_after_single_retry(self):
+ signals = (
+ ("v1", {"code": 201, "message": "Token invalid", "data": None}, 200),
+ ("v2", {"code": 401, "data": None}, 200),
+ )
+ for version, expired, status in signals:
+ with self.subTest(version=version):
+ self.save_session(version)
+
+ def refresh(auth):
+ auth.authen_key = "FAKE_NEW_KEY"
+ return True
+
+ with patch("requests.Session.request",
+ side_effect=[response(expired, status), response(expired, status)]) as request, \
+ patch("myfap.auth.MyFapAuth.refresh_session", autospec=True, side_effect=refresh) as rotation:
+ result = self.runner.invoke(app, ["--config", str(self.path), "other", "balance", "--stdout"])
+ self.assertEqual(result.exit_code, 1)
+ self.assertEqual(result.stdout, "")
+ self.assertEqual(request.call_count, 2)
+ rotation.assert_called_once()
+
+ def test_app_check_timeout_and_5xx_fail_once_without_refresh_or_fallback(self):
+ import requests as requests_module
+
+ failures = (
+ (response({"code": "APP_CHECK_FAILED"}), "APP_CHECK_FAILED"),
+ (requests_module.Timeout("PRIVATE_SENTINEL_URL"), "thử lại sau"),
+ (response(None, 503), "HTTP 503"),
+ )
+ for version in ("v1", "v2"):
+ for command, operation in self.COMMANDS:
+ for failure, message in failures:
+ with self.subTest(version=version, operation=operation, message=message):
+ self.save_session(version)
+ before = self.path.read_bytes()
+ with patch("requests.Session.request", side_effect=[failure]) as request, \
+ patch("myfap.auth.MyFapAuth.refresh_session") as refresh:
+ result = self.runner.invoke(app, ["--config", str(self.path), *command, "--stdout"])
+ self.assertEqual(result.exit_code, 1)
+ self.assertEqual(result.stdout, "")
+ self.assertIn(message, Text.from_ansi(result.stderr).plain)
+ self.assertNotIn("PRIVATE_SENTINEL_URL", Text.from_ansi(result.stderr).plain)
+ self.assertEqual(request.call_count, 1)
+ self.assertTrue(request.call_args.args[1].endswith("/" + operation))
+ refresh.assert_not_called()
+ self.assertEqual(self.path.read_bytes(), before)
+
+ def test_malformed_payload_is_reported_without_retry_or_refresh(self):
+ cases = (
+ (response("invalid-envelope"), "phải có code và data"),
+ (response({"code": "ok", "data": []}), "không hợp lệ"),
+ )
+ for version in ("v1", "v2"):
+ for command, operation in self.COMMANDS:
+ for failure, message in cases:
+ with self.subTest(version=version, operation=operation, message=message):
+ self.save_session(version)
+ with patch("requests.Session.request", side_effect=[failure]) as request, \
+ patch("myfap.auth.MyFapAuth.refresh_session") as refresh:
+ result = self.runner.invoke(app, ["--config", str(self.path), *command, "--stdout"])
+ self.assertEqual(result.exit_code, 1)
+ self.assertEqual(result.stdout, "")
+ self.assertIn(message, Text.from_ansi(result.stderr).plain)
+ self.assertEqual(request.call_count, 1)
+ self.assertTrue(request.call_args.args[1].endswith("/" + operation))
+ refresh.assert_not_called()
+
+
+class OtherCommandLayoutTests(unittest.TestCase):
+ setUp = BalanceCommandTests.setUp
+ save_session = BalanceCommandTests.save_session
+
+ def test_training_and_rating_inherit_options_at_nested_leaf(self):
+ self.save_session("v1")
+ for command, operation in (
+ (["other", "--api-version", "v2", "training", "--semester", "FAKE_TERM"], "GetDiemphongtrao"),
+ (["other", "--api-version", "v2", "rating", "--api-version", "v2", "list"], "GetStudentRate"),
+ ):
+ with self.subTest(operation=operation), patch("requests.Session.request", return_value=response({"code": 200, "data": []})) as request:
+ result = self.runner.invoke(app, ["--api-version", "v2", *command,
+ "--config", str(self.path), "--api-version", "v1", "--timeout", "31", "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(json.loads(result.stdout), {"code": 200, "data": []})
+ request.assert_called_once()
+ self.assertTrue(request.call_args.args[1].endswith('/' + operation))
+ self.assertEqual(urlsplit(request.call_args.args[1]).netloc, "api.fpt.edu.vn")
+ self.assertEqual(request.call_args.kwargs["timeout"], 31)
+
+ def test_new_help_paths_work_and_old_root_commands_are_absent_without_auth(self):
+ with patch("myfap.cli.get_auth") as auth, patch("requests.Session.request") as request:
+ for command in (["other"], ["other", "training"], ["other", "rating"], ["other", "rating", "list"]):
+ with self.subTest(command=command):
+ result = self.runner.invoke(app, [*command, "--help"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ result = self.runner.invoke(app, ["other", "--help"])
+ text = Text.from_ansi(result.stdout).plain
+ self.assertIn("training", text)
+ self.assertIn("rating", text)
+ for command in (["training"], ["rating", "list"]):
+ with self.subTest(old_command=command):
+ result = self.runner.invoke(app, [*command, "--help"])
+ self.assertEqual(result.exit_code, 2)
+ auth.assert_not_called()
+ request.assert_not_called()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_phase6_summary.py b/tests/test_phase6_summary.py
new file mode 100644
index 0000000..1c8dc89
--- /dev/null
+++ b/tests/test_phase6_summary.py
@@ -0,0 +1,126 @@
+"""Operation-specific semester summary reader; all responses are synthetic."""
+import inspect
+import json
+import unittest
+
+import requests
+from rich.text import Text
+
+from myfap.summary import read_semester_marks_response
+
+
+def response(payload, status=200):
+ result = requests.Response()
+ result.status_code = status
+ result.encoding = "utf-8"
+ result._content = json.dumps(payload, ensure_ascii=False).encode("utf-8")
+ return result
+
+
+class SemesterSummaryReaderTests(unittest.TestCase):
+ def test_raw_array_is_normalized_without_changing_data(self):
+ data = [{"synthetic": "Tiếng Việt", "nested": [1, None]}]
+ for version in ("v1", "v2"):
+ with self.subTest(api_version=version):
+ self.assertEqual(read_semester_marks_response(response(data), api_version=version),
+ {"code": 200, "data": data})
+
+ def test_envelope_is_preserved_and_json_string_array_is_normalized(self):
+ payload = {"code": "200", "data": [{"synthetic": 1}], "message": None}
+ self.assertEqual(read_semester_marks_response(response(payload), api_version="v2"), payload)
+ self.assertEqual(read_semester_marks_response(response('[{"synthetic": 1}]'), api_version="v1"),
+ {"code": 200, "data": [{"synthetic": 1}]})
+
+ def test_errors_are_not_converted_to_empty_arrays(self):
+ from myfap.errors import ApiAppCheckError, ApiHTTPError, ApiOperationError, ApiSessionExpiredError
+ cases = (
+ (response([], 401), "v1", ApiSessionExpiredError),
+ (response([], 403), "v2", ApiHTTPError),
+ (response({"code": "APP_CHECK_FAILED"}, 401), "v2", ApiAppCheckError),
+ (response({"code": 401, "data": None}), "v2", ApiSessionExpiredError),
+ (response({"code": 201, "data": None}), "v1", ApiOperationError),
+ )
+ for value, version, expected in cases:
+ with self.subTest(version=version, status=value.status_code):
+ with self.assertRaises(expected):
+ read_semester_marks_response(value, api_version=version)
+
+ def test_oversize_error_body_preserves_http_status_classification(self):
+ from myfap.errors import ApiHTTPError, ApiSessionExpiredError
+ for status, expected in ((401, ApiSessionExpiredError), (503, ApiHTTPError)):
+ with self.subTest(status=status):
+ with self.assertRaises(expected) as caught:
+ read_semester_marks_response(response("x" * (1024 * 1024 + 1), status), api_version="v2")
+ self.assertEqual(caught.exception.status_code, status)
+
+ def test_unknown_wrapper_malformed_or_oversize_payload_is_safe(self):
+ from myfap.errors import ApiPayloadError
+ for value in (None, True, {}, {"code": 200, "data": {}}, "PRIVATE [not json]", "[]"):
+ with self.subTest(value=value), self.assertRaises(ApiPayloadError) as caught:
+ read_semester_marks_response(response(value), api_version="v2")
+ self.assertNotIn("PRIVATE", str(caught.exception))
+ with self.assertRaises(ApiPayloadError):
+ read_semester_marks_response(response("x" * (1024 * 1024 + 1)), api_version="v2")
+
+
+class SemesterSummaryCommandTests(unittest.TestCase):
+ def test_summary_has_exact_query_and_never_looks_up_semester(self):
+ from pathlib import Path
+ from tempfile import TemporaryDirectory
+ from unittest.mock import patch
+ from typer.testing import CliRunner
+ from myfap.cli import app
+ for version in ("v1", "v2"):
+ with self.subTest(version=version), TemporaryDirectory() as directory:
+ path = Path(directory) / "session.json"
+ path.write_text(json.dumps({"campus": "TEST", "api_version": version,
+ "authen_key": "FAKE_KEY", "mssv": "TEST000", "email": "sample@example.invalid"}), encoding="utf-8")
+ with patch("requests.Session.request", return_value=response([{"synthetic": True}])) as request:
+ result = CliRunner(**({"mix_stderr": False} if "mix_stderr" in inspect.signature(CliRunner).parameters else {})).invoke(app, ["--config", str(path), "marks", "--summary", "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(json.loads(result.stdout), {"code": 200, "data": [{"synthetic": True}]})
+ request.assert_called_once()
+ self.assertTrue(request.call_args.args[1].endswith("/GetSemesterMark"))
+ self.assertEqual(request.call_args.kwargs["params"], {
+ "CampusCode": "TEST", "rollNumber": "TEST000", "Authen": "FAKE_KEY"})
+ if version == "v2":
+ self.assertEqual(request.call_args.kwargs["headers"]["Authorization"], "Bearer FAKE_KEY")
+
+ def test_conflicting_summary_options_fail_before_auth(self):
+ from unittest.mock import patch
+ from typer.testing import CliRunner
+ from myfap.cli import app
+ for options in (["--semester", "Fall2026"], ["--courseid", "DEMO"], ["--pretty"]):
+ with self.subTest(options=options), patch("myfap.cli.get_auth") as auth:
+ result = CliRunner(**({"mix_stderr": False} if "mix_stderr" in inspect.signature(CliRunner).parameters else {})).invoke(app, ["marks", "--summary", *options, "--stdout"])
+ self.assertNotEqual(result.exit_code, 0)
+ self.assertIn("--summary", Text.from_ansi(result.stderr).plain)
+ auth.assert_not_called()
+
+ def test_summary_rebuilds_authen_after_single_refresh(self):
+ from pathlib import Path
+ from tempfile import TemporaryDirectory
+ from unittest.mock import patch
+ from typer.testing import CliRunner
+ from myfap.cli import app
+ for version in ("v1", "v2"):
+ with self.subTest(version=version), TemporaryDirectory() as directory:
+ path = Path(directory) / "session.json"
+ path.write_text(json.dumps({"campus": "TEST", "api_version": version,
+ "authen_key": "FAKE_OLD", "mssv": "TEST000", "email": "sample@example.invalid"}), encoding="utf-8")
+ def refresh(auth):
+ auth.authen_key = "FAKE_NEW"
+ return True
+ expired = {"code": 201, "message": "Token invalid", "data": None} if version == "v1" else {"code": 401, "data": None}
+ with patch("requests.Session.request", side_effect=[response(expired), response([])]) as request, \
+ patch("myfap.auth.MyFapAuth.refresh_session", autospec=True, side_effect=refresh) as rotation:
+ result = CliRunner(**({"mix_stderr": False} if "mix_stderr" in inspect.signature(CliRunner).parameters else {})).invoke(app, ["--config", str(path), "marks", "--summary", "--stdout"])
+ self.assertEqual(result.exit_code, 0, result.output)
+ self.assertEqual(request.call_count, 2)
+ rotation.assert_called_once()
+ self.assertEqual(request.call_args.kwargs["params"]["Authen"], "FAKE_NEW")
+ self.assertNotIn("checksum", request.call_args.kwargs["params"])
+
+
+if __name__ == "__main__":
+ unittest.main()
|