From 028722f706d1173390e144109087f260ac66286d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E4=BD=B3=E6=81=A9?= Date: Wed, 18 Nov 2026 07:32:31 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=B8=89=E8=A7=92=E8=AA=BF=E8=AA=B2(?= =?UTF-8?q?=E5=90=8C=E4=B8=80=E7=8F=AD=E4=B8=89=E4=BD=8D=E8=80=81=E5=B8=AB?= =?UTF-8?q?=E8=BC=AA=E6=B5=81=E6=8F=9B=E8=AA=B2);=E5=88=97=E5=87=BA?= =?UTF-8?q?=E5=8F=AF=E8=A1=8C=E7=9A=84=E4=B8=89=E4=BA=BA=E7=B5=84=E5=90=88?= =?UTF-8?q?,=E4=B8=89=E4=BD=8D=E8=80=81=E5=B8=AB=E8=88=87=E7=8F=AD?= =?UTF-8?q?=E7=B4=9A=E5=90=84=E6=9C=89=E8=AA=BF=E8=AA=B2=E5=96=AE,?= =?UTF-8?q?=E6=92=A4=E5=9B=9E=E4=B8=80=E8=B5=B7=E6=92=A4;=E7=99=BC?= =?UTF-8?q?=E5=B8=83=20v1.4.20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 遷移 0022:substitutions 新增 tri_teacher_id 與 tri_*(乙原本那一節,改由丙上),可為空 - services/swap_legs.py:一筆調課換人上的每一格(互調兩格、三角三格),巡堂表、週課表、 教師週總表、調課單、調代課紀錄、停課衝突共用 - swap_options.triangle_search 與 substitutions._validate_triangle 共用 SwapChecker; 只限同一班、一位老師上的一般課;三角調的節次不能再調 - 通知三位老師;撤回、銷假一起撤並通知丙;重新發布課表兩節一起接到新課表 - 修正:對方那一節已在他自己的調課(未請假)裡時,不再列為可對調 - 前端調課面板「兩人互調/三角調課」切換;手冊 8.3、FAQ、CHANGELOG、升級與退回說明 Co-Authored-By: Claude Opus 5.5 --- .env.example | 2 +- CHANGELOG.md | 22 +- README.md | 6 +- .../alembic/versions/0022_triangle_swaps.py | 46 +++ backend/app/api/leaves.py | 4 + backend/app/api/substitutions.py | 25 +- backend/app/models/substitution.py | 27 +- backend/app/schemas/leave.py | 4 + backend/app/schemas/substitution.py | 44 +++ backend/app/schemas/substitution_log.py | 5 + backend/app/services/availability.py | 15 + backend/app/services/leaves.py | 14 + backend/app/services/patrol_sheets.py | 52 ++-- backend/app/services/substitution_log.py | 103 ++++--- backend/app/services/substitutions.py | 197 +++++++++++- backend/app/services/suspensions.py | 30 +- backend/app/services/swap_legs.py | 154 ++++++++++ backend/app/services/swap_options.py | 234 ++++++++++++++- backend/app/services/swap_relink.py | 42 ++- backend/app/services/swap_slips.py | 52 ++-- backend/app/services/teacher_week_sheets.py | 32 +- backend/app/services/timetable_week.py | 4 +- backend/tests/test_triangle_swap_v1420.py | 283 ++++++++++++++++++ docs/architecture.html | 2 +- docs/architecture.md | 2 +- docs/deploy/upgrade.html | 17 +- docs/deploy/upgrade.md | 21 ++ docs/features.html | 12 +- docs/index.html | 20 +- docs/roadmap.html | 5 + docs/roadmap.md | 1 + frontend/e2e/triangle-swap.spec.ts | 122 ++++++++ frontend/src/api/leaves.ts | 4 + frontend/src/api/substitutionLog.ts | 6 + frontend/src/api/substitutions.ts | 54 ++++ .../src/views/substitution/DailyBoard.vue | 2 + .../views/substitution/DailyBoardPrint.vue | 10 + .../substitution/SubstitutionLog.test.ts | 1 + .../views/substitution/Substitutions.test.ts | 1 + .../src/views/substitution/Substitutions.vue | 159 ++++++++-- .../src/views/substitution/logText.test.ts | 12 + frontend/src/views/substitution/logText.ts | 10 + .../views/substitution/triangleText.test.ts | 30 ++ .../src/views/substitution/triangleText.ts | 35 +++ 44 files changed, 1743 insertions(+), 180 deletions(-) create mode 100644 backend/alembic/versions/0022_triangle_swaps.py create mode 100644 backend/app/services/swap_legs.py create mode 100644 backend/tests/test_triangle_swap_v1420.py create mode 100644 frontend/e2e/triangle-swap.spec.ts create mode 100644 frontend/src/views/substitution/triangleText.test.ts create mode 100644 frontend/src/views/substitution/triangleText.ts diff --git a/.env.example b/.env.example index 28979a89..a492df34 100644 --- a/.env.example +++ b/.env.example @@ -32,7 +32,7 @@ HTTP_PORT=80 # ── 預建映像版本(僅「拉取映像」部署方式需要)────────── # 用 docker compose pull 拉官方映像時,決定要拉哪一版。 # 預設 latest(最新);正式部署建議釘選版本號以利可控升級,例如: -# IMAGE_TAG=v1.4.19 +# IMAGE_TAG=v1.4.20 # 若你是從原始碼 docker compose up -d 自行建置,此項可忽略。 IMAGE_TAG=latest diff --git a/CHANGELOG.md b/CHANGELOG.md index 1946b4e2..447b93ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,10 +4,30 @@ 破壞性變更(需人工介入才能升級)以 ⚠️ 標註。 -> **新使用者請直接安裝 v1.4.19**(見 [README](README.md) 快速開始)。v1.0.0 ~ v1.4.18 是先前版本;以下條目保留作為變更紀錄。 +> **新使用者請直接安裝 v1.4.20**(見 [README](README.md) 快速開始)。v1.0.0 ~ v1.4.19 是先前版本;以下條目保留作為變更紀錄。 ## [Unreleased] +## [1.4.20] — 2026-11-18 + +**新功能:三角調課**(組長拿別家系統的畫面來問:「會出三角調課嗎?」)。 + +**調代課處置的資料表新增幾個欄位**(三角調課的第三位老師與中間那一節,可為空;既有的調課都是兩人互調,資料不變)。升級時系統會先自動備份再升級,照一般方式即可(`.env` 改 `IMAGE_TAG=v1.4.20` → `docker compose pull && docker compose up -d`)。 + +官方映像(amd64 + arm64 雙架構)已發布於 GHCR: +`ghcr.io/begin0808/course_scheduling_system-{api,worker,web}:v1.4.20` + +### 新增 +- **三角調課**(「調代課處理」的調課面板切到「三角調課」):兩人互調湊不出來時,同一班三位老師輪流換課——乙來上請假的這一節、丙來上乙原本的一節、請假的老師回來上丙原本的一節。 + - 系統列出**可行的三人組合**(乙在請假那節有空、丙在乙那節有空、請假的老師在丙那節有空),兩節都越早的排越前面,點一下就成立。範圍與互調相同(預設本週與下週,可放寬到四週、可改從較早的週開始找)。「新增調課(未請假)」也可以用。 + - 只限**同一個班、一位老師上的一般課**;跑班、單雙週組、協同教學的課不列(那一節不只一門課或一位老師)。 + - 鐘點都不計(和互調一樣)。三位老師各收到通知;**撤回或銷假時三節一起撤**,三位都收到取消通知。 + - 調課單:**三位老師各一張**(只列自己要去上的那一格)、**班級一張**(三格);記號指向那位老師自己空出來的那一節。 + - 週課表、巡堂表、全校教師週總表、今日看板、調代課紀錄都列出三格,標「三角調課」。查丙老師的調代課紀錄也查得到。 + - **三角調的節次不能再調**:清單上寫「這節已經和別的老師調課了」。重新發布課表時,兩節一起接到新課表;設停課日時也會列出來。 + +### 修正 +- 調課清單:對方那一節已經在他自己的「調課(未請假)」裡交給別人時,原本仍列為可以對調;現在列在「換不了」並寫原因。 ## [1.4.19] — 2026-11-17 **新功能:停課日**(LINE 社群組長:「停課日在哪邊可以設定?」)。 diff --git a/README.md b/README.md index 51e9f797..5fad7e80 100644 --- a/README.md +++ b/README.md @@ -132,11 +132,11 @@ docker compose up -d # 首次會建置映像,需數分鐘 ## 專案狀態 -**v1.4.19 已發行(2026-11-17)。** 六大里程碑 M0–M5 全部完成,功能齊備並經完整驗收(後端 792 項單元/整合測試、62 項 Playwright 端對端測試涵蓋全部 21 個頁面,每次提交皆對真實 Docker 全棧跑過)。官方映像(amd64 + arm64)已發布於 GHCR。 +**v1.4.20 已發行(2026-11-18)。** 六大里程碑 M0–M5 全部完成,功能齊備並經完整驗收(後端 804 項單元/整合測試、63 項 Playwright 端對端測試涵蓋全部 21 個頁面,每次提交皆對真實 Docker 全棧跑過)。官方映像(amd64 + arm64)已發布於 GHCR。 -v1.4.19 新增**停課日**(全校、年級或班級,整天或第幾節到第幾節;請假不必代課、不能拿來調課補課,巡堂表與週課表標停課);v1.4.18 修正調課後**重新發布課表**時補課那一節消失的問題;v1.4.17 調代課紀錄與某一週的班級課表,調課**寫出對調的另一節在哪一天**;v1.4.16 跑班 5 組以內在班級課表**列出每位老師**,先調課再請假時已調走的節次**不再重複列出**;v1.4.15 課表查詢可以**看某一週實際的課表**(含調代課,異動標色),並新增身心調適假等常用假別;v1.4.14 新增**全校教師週總表**(老師為欄、標出這週的調代課,可列印或匯出 Excel);v1.4.13 修正跑班群組在班級課表只顯示一位老師(同一格改列出每一組);v1.4.12 調課可以**從較早的週開始找**(老師提早請假、想先補課),換不了的節次會**寫出原因**,代導半天改以「次」計;v1.4.11「代課鐘點統計」可以**自訂統計區間**(每月 15 日結算的學校可選 10/16~11/15);v1.4.10 已經上過的調課可以**事後補登**(「新增調課(未請假)」勾已經上過的節次;不通知老師),調代課紀錄也能篩出「調課(未請假)」,查老師多常換課;v1.4.9 同一天好幾節要一起換(例如學校活動讓兩班的第七、八節同時對調)也**調得成**了;v1.4.8 新學期第一次進「自動排課」會**自動建立草稿**,配完課就能直接排;v1.4.7 **資安修正**:登入失敗鎖定不會再被「同時送出」繞過(建議升級);v1.4.6 全校總表與批次 zip 都可以**匯出 PDF**;v1.4.5 老師**沒請假也能調課**(調代課處理的「新增調課」);v1.4.4 登記後可以**修改假別與計費方式**(已經上過的代課也可以改計費方式),請假的假別改成一定要選;v1.4.3 修正安排代導時操作紀錄沒寫出老師名字;v1.4.2 可以**補登**事後才登記的請假(已經過去的節次補登代課,不通知老師、列入鐘點統計);v1.4.1 起改採 **AGPL-3.0 授權**(見下方「授權」;功能與資料都沒有變動);v1.4.0 新增**代導**(導師請假當天由誰代他帶班,當天沒課也算、半天也算;可印代導通知單,月結分開記全天與半天天數;⚠️ 資料表結構變更,升級前會自動備份);v1.3.5 修正**併班**選不到老師(改列出這一節正在上課的老師),調課單加上記號說明;v1.3.4 讓跑班群組、導師、任教科目等下拉選單都能**打字搜尋**;v1.3.3 的儀表板新增**即時概況**(現在這一節各班在上什麼課、誰在上,已套用當天的調代課);v1.3.2 新增**重設管理員密碼**的指令(忘了密碼或第一次就登不進去時,不必刪資料或還原備份);v1.3.1 新增**帳號管理**(系統管理員可設定教學組長、教務主任的帳號);v1.3.0 支援**單雙週課程**(同一節單週、雙週輪流上不同的課,排課、請假代課、調課、巡堂表、鐘點都分單雙週;⚠️ 首次改動資料表結構,升級前請先備份);v1.2.19 支援**日薪代課**(國小常見:月結統計把鐘點與日薪分開列)並可**整批指派代課**(整張假單或整天一次派給同一位老師);v1.2.18 可**檢查課表**(發布前列出衝堂、教師不可排時段等衝突;事後修改不可排時段時當場提示已排的課);v1.2.17 修正登入按一次送出兩筆請求(輸錯密碼約第 3 次就被鎖定);v1.2.15、v1.2.16 修正跑班群組的兩個問題(同一位老師在群組裡重複配課時自動排課會排出撞課的課表;同一格有多筆同科目配課時,手動排課把每日節數重複計算);v1.2.12~v1.2.14 可列印**巡堂表**並匯出 Excel(依當天的調代課結果產生,社團另出分組巡堂單);v1.2.10、v1.2.11 讓**國中小、完全中學**跨部上課的老師,課表與通知單都標出實際上課時間,兩部節數不同(國中七節、高中八節)也不會漏課;v1.2.9 可一次匯出**全校教師課表**(總表與批次打包);v1.2.8 可用 Excel **批次更新既有教師**(新學年職務異動),並能**停用/啟用教師登入帳號**(離職教師保留歷史紀錄又進不來);v1.2.7 補上**學期起訖日期**的填寫與修改(先前畫面上無處可填,導致請假被擋);v1.2.6 修掉第一批外部使用者回報的三個問題(教師帳號首次登入卡死、無法事後補開教師帳號、未排課務清單過長時拖不動),並可在畫面上自行修改與重設密碼;v1.2.5 可列印**教師代課通知單與班級代課通知單**(照學校紙本格式,代課時可選計費方式);v1.2.4 的調代課處理會寫出處置方式(代課或調課、哪天補課);v1.2.3 起系統會顯示目前版本,並在有新版時提醒系統管理員(只提醒、不自動升級);v1.2.2 可列印**教師調課通知單與班級調課通知單**(照學校紙本格式);v1.2.1 補上**調課**的操作畫面——請假(含研習)的節次可直接列出雙方都有空的對調節次,支援跨週(最多四週)與連堂,補課日也會出現在今日看板。v1.2.0 起另有**一鍵示範資料**,裝好後兩分鐘內就能看到一張排好的全校課表。 +v1.4.20 新增**三角調課**(同一班三位老師輪流換課,列出可行的三人組合;三位老師與班級各有調課單,撤回一起撤);v1.4.19 新增**停課日**(全校、年級或班級,整天或第幾節到第幾節;請假不必代課、不能拿來調課補課,巡堂表與週課表標停課);v1.4.18 修正調課後**重新發布課表**時補課那一節消失的問題;v1.4.17 調代課紀錄與某一週的班級課表,調課**寫出對調的另一節在哪一天**;v1.4.16 跑班 5 組以內在班級課表**列出每位老師**,先調課再請假時已調走的節次**不再重複列出**;v1.4.15 課表查詢可以**看某一週實際的課表**(含調代課,異動標色),並新增身心調適假等常用假別;v1.4.14 新增**全校教師週總表**(老師為欄、標出這週的調代課,可列印或匯出 Excel);v1.4.13 修正跑班群組在班級課表只顯示一位老師(同一格改列出每一組);v1.4.12 調課可以**從較早的週開始找**(老師提早請假、想先補課),換不了的節次會**寫出原因**,代導半天改以「次」計;v1.4.11「代課鐘點統計」可以**自訂統計區間**(每月 15 日結算的學校可選 10/16~11/15);v1.4.10 已經上過的調課可以**事後補登**(「新增調課(未請假)」勾已經上過的節次;不通知老師),調代課紀錄也能篩出「調課(未請假)」,查老師多常換課;v1.4.9 同一天好幾節要一起換(例如學校活動讓兩班的第七、八節同時對調)也**調得成**了;v1.4.8 新學期第一次進「自動排課」會**自動建立草稿**,配完課就能直接排;v1.4.7 **資安修正**:登入失敗鎖定不會再被「同時送出」繞過(建議升級);v1.4.6 全校總表與批次 zip 都可以**匯出 PDF**;v1.4.5 老師**沒請假也能調課**(調代課處理的「新增調課」);v1.4.4 登記後可以**修改假別與計費方式**(已經上過的代課也可以改計費方式),請假的假別改成一定要選;v1.4.3 修正安排代導時操作紀錄沒寫出老師名字;v1.4.2 可以**補登**事後才登記的請假(已經過去的節次補登代課,不通知老師、列入鐘點統計);v1.4.1 起改採 **AGPL-3.0 授權**(見下方「授權」;功能與資料都沒有變動);v1.4.0 新增**代導**(導師請假當天由誰代他帶班,當天沒課也算、半天也算;可印代導通知單,月結分開記全天與半天天數;⚠️ 資料表結構變更,升級前會自動備份);v1.3.5 修正**併班**選不到老師(改列出這一節正在上課的老師),調課單加上記號說明;v1.3.4 讓跑班群組、導師、任教科目等下拉選單都能**打字搜尋**;v1.3.3 的儀表板新增**即時概況**(現在這一節各班在上什麼課、誰在上,已套用當天的調代課);v1.3.2 新增**重設管理員密碼**的指令(忘了密碼或第一次就登不進去時,不必刪資料或還原備份);v1.3.1 新增**帳號管理**(系統管理員可設定教學組長、教務主任的帳號);v1.3.0 支援**單雙週課程**(同一節單週、雙週輪流上不同的課,排課、請假代課、調課、巡堂表、鐘點都分單雙週;⚠️ 首次改動資料表結構,升級前請先備份);v1.2.19 支援**日薪代課**(國小常見:月結統計把鐘點與日薪分開列)並可**整批指派代課**(整張假單或整天一次派給同一位老師);v1.2.18 可**檢查課表**(發布前列出衝堂、教師不可排時段等衝突;事後修改不可排時段時當場提示已排的課);v1.2.17 修正登入按一次送出兩筆請求(輸錯密碼約第 3 次就被鎖定);v1.2.15、v1.2.16 修正跑班群組的兩個問題(同一位老師在群組裡重複配課時自動排課會排出撞課的課表;同一格有多筆同科目配課時,手動排課把每日節數重複計算);v1.2.12~v1.2.14 可列印**巡堂表**並匯出 Excel(依當天的調代課結果產生,社團另出分組巡堂單);v1.2.10、v1.2.11 讓**國中小、完全中學**跨部上課的老師,課表與通知單都標出實際上課時間,兩部節數不同(國中七節、高中八節)也不會漏課;v1.2.9 可一次匯出**全校教師課表**(總表與批次打包);v1.2.8 可用 Excel **批次更新既有教師**(新學年職務異動),並能**停用/啟用教師登入帳號**(離職教師保留歷史紀錄又進不來);v1.2.7 補上**學期起訖日期**的填寫與修改(先前畫面上無處可填,導致請假被擋);v1.2.6 修掉第一批外部使用者回報的三個問題(教師帳號首次登入卡死、無法事後補開教師帳號、未排課務清單過長時拖不動),並可在畫面上自行修改與重設密碼;v1.2.5 可列印**教師代課通知單與班級代課通知單**(照學校紙本格式,代課時可選計費方式);v1.2.4 的調代課處理會寫出處置方式(代課或調課、哪天補課);v1.2.3 起系統會顯示目前版本,並在有新版時提醒系統管理員(只提醒、不自動升級);v1.2.2 可列印**教師調課通知單與班級調課通知單**(照學校紙本格式);v1.2.1 補上**調課**的操作畫面——請假(含研習)的節次可直接列出雙方都有空的對調節次,支援跨週(最多四週)與連堂,補課日也會出現在今日看板。v1.2.0 起另有**一鍵示範資料**,裝好後兩分鐘內就能看到一張排好的全校課表。 -**請直接從最新版開始安裝**(見上方快速開始);`v1.4.19` 是目前建議使用的版本。各版變更見 [CHANGELOG](CHANGELOG.md),開發歷程見 [docs/tasks.md](docs/tasks.md)。 +**請直接從最新版開始安裝**(見上方快速開始);`v1.4.20` 是目前建議使用的版本。各版變更見 [CHANGELOG](CHANGELOG.md),開發歷程見 [docs/tasks.md](docs/tasks.md)。 系統仍在實際校園環境試用中,若你是第一批使用者,歡迎加入 [LINE 社群](https://line.me/ti/g2/hP0Lg7mqvE5rvWg0sE9MHI-QsLkd94Cfp3wKcg) 或透過 [Issues](https://github.com/begin0808/Course_Scheduling_System/issues) 回報任何問題。 diff --git a/backend/alembic/versions/0022_triangle_swaps.py b/backend/alembic/versions/0022_triangle_swaps.py new file mode 100644 index 00000000..c7190798 --- /dev/null +++ b/backend/alembic/versions/0022_triangle_swaps.py @@ -0,0 +1,46 @@ +"""v1.4.20:三角調課(同一班三位老師輪流換課)。 + +`substitutions` 加上第三位老師與中間那一節(乙原本的課,改由丙上),全部可為空; +既有的調課都是兩人互調,這些欄位留空,資料不變。 + +Revision ID: 0022_triangle_swaps +Revises: 0021_class_suspensions +""" + +import sqlalchemy as sa + +from alembic import op + +revision = "0022_triangle_swaps" +down_revision = "0021_class_suspensions" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table("substitutions") as t: + t.add_column(sa.Column("tri_teacher_id", sa.Integer(), nullable=True)) + t.add_column(sa.Column("tri_date", sa.Date(), nullable=True)) + t.add_column(sa.Column("tri_period_no", sa.Integer(), nullable=True)) + t.add_column(sa.Column("tri_period_name", sa.String(32), nullable=False, + server_default="")) + t.add_column(sa.Column("tri_class_names", sa.String(128), nullable=False, + server_default="")) + t.add_column(sa.Column("tri_subject_name", sa.String(64), nullable=False, + server_default="")) + t.add_column(sa.Column("tri_entry_id", sa.Integer(), nullable=True)) + t.create_foreign_key("fk_substitutions_tri_teacher", "teachers", + ["tri_teacher_id"], ["id"], ondelete="SET NULL") + t.create_foreign_key("fk_substitutions_tri_entry", "schedule_entries", + ["tri_entry_id"], ["id"], ondelete="SET NULL") + t.create_index("ix_substitutions_tri_teacher_id", ["tri_teacher_id"]) + + +def downgrade() -> None: + with op.batch_alter_table("substitutions") as t: + t.drop_index("ix_substitutions_tri_teacher_id") + t.drop_constraint("fk_substitutions_tri_entry", type_="foreignkey") + t.drop_constraint("fk_substitutions_tri_teacher", type_="foreignkey") + for c in ("tri_entry_id", "tri_subject_name", "tri_class_names", "tri_period_name", + "tri_period_no", "tri_date", "tri_teacher_id"): + t.drop_column(c) diff --git a/backend/app/api/leaves.py b/backend/app/api/leaves.py index 4eeaadee..ecec3c3c 100644 --- a/backend/app/api/leaves.py +++ b/backend/app/api/leaves.py @@ -97,6 +97,10 @@ def _serialize(leave: LeaveRequest) -> LeaveRequestOut: sub_type=p.substitution.type if p.substitution else None, swap_date=p.substitution.swap_date if p.substitution else None, swap_period_name=p.substitution.swap_period_name if p.substitution else "", + tri_teacher_name=(p.substitution.tri_teacher.name + if p.substitution and p.substitution.tri_teacher else ""), + tri_date=p.substitution.tri_date if p.substitution else None, + tri_period_name=p.substitution.tri_period_name if p.substitution else "", funding_source=p.substitution.funding_source if p.substitution else "", counts_toward_hours=( p.substitution.counts_toward_hours if p.substitution else None), diff --git a/backend/app/api/substitutions.py b/backend/app/api/substitutions.py index 48575f78..871079df 100644 --- a/backend/app/api/substitutions.py +++ b/backend/app/api/substitutions.py @@ -34,6 +34,7 @@ SlipsOut, SubstitutionOut, SwapOptionsOut, + TriangleOptionsOut, ) from app.services import sub_slips, swap_options, swap_slips from app.services import substitution_recommender as recommender @@ -61,6 +62,10 @@ def _sub_out(sub: Substitution) -> SubstitutionOut: counts_toward_hours=sub.counts_toward_hours, funding_source=sub.funding_source, swap_date=sub.swap_date, swap_period_name=sub.swap_period_name, swap_class_names=sub.swap_class_names, swap_subject_name=sub.swap_subject_name, + tri_teacher_id=sub.tri_teacher_id, + tri_teacher_name=sub.tri_teacher.name if sub.tri_teacher else "", + tri_date=sub.tri_date, tri_period_name=sub.tri_period_name, + tri_class_names=sub.tri_class_names, tri_subject_name=sub.tri_subject_name, created_by_name=sub.created_by_name, ) @@ -114,6 +119,21 @@ def get_swap_options( db, affected, teacher_id=teacher_id, weeks=weeks, start=start))) +@router.get("/affected-periods/{affected_id}/triangle-options", + response_model=TriangleOptionsOut) +def get_triangle_options( + affected_id: int, + weeks: int = Query(default=swap_options.DEFAULT_WEEKS, ge=1, le=swap_options.MAX_WEEKS), + start: date | None = Query(default=None), + db: Session = Depends(get_db), + _: User = Depends(editor), +): + """三角調課(v1.4.20):同一班三位老師輪流換課的可行組合,範圍與互調相同。""" + affected = _get_affected(db, affected_id) + return TriangleOptionsOut.model_validate(asdict(swap_options.triangle_search( + db, affected, weeks=weeks, start=start))) + + @router.get("/swap-slips", response_model=SlipsOut) def get_swap_slips( semester_id: int = Query(...), @@ -162,6 +182,8 @@ def assign_substitution( swap_entry_id=body.swap_entry_id, swap_date=body.swap_date, swap_period_no=body.swap_period_no, created_by_user_id=user.id, created_by_name=user.username, + tri_teacher_id=body.tri_teacher_id, tri_entry_id=body.tri_entry_id, + tri_date=body.tri_date, tri_period_no=body.tri_period_no, ) except sub_service.SubstitutionError as exc: raise HTTPException(status.HTTP_409_CONFLICT, str(exc)) from exc @@ -172,8 +194,9 @@ def assign_substitution( detail=( ("補登 " if backfill else "") + f"{affected.leave_request.teacher.name} {affected.date} {affected.period_name}" - f" → {SUBSTITUTION_TYPE_CN.get(sub.type, sub.type)}" + f" → {'三角調課' if sub.is_triangle else SUBSTITUTION_TYPE_CN.get(sub.type, sub.type)}" + (f"({sub.handler.name})" if sub.handler else "") + + (f"、{sub.tri_teacher.name}" if sub.tri_teacher else "") )[:500], )) db.commit() diff --git a/backend/app/models/substitution.py b/backend/app/models/substitution.py index 2539e828..b74551f9 100644 --- a/backend/app/models/substitution.py +++ b/backend/app/models/substitution.py @@ -10,6 +10,11 @@ **swap(調課)的語意**:甲請假日的某節由乙代;交換條件是甲之後補乙一節(乙原本那節放掉)。 因此要驗四件事都無衝突:乙在甲那節、甲在乙那節、以及兩個班各自不重複排課。 `swap_*` 欄位記錄「乙原本要放掉、改由甲補」的那一節(以快照保存,課表改版不影響已成立的調課)。 + +**三角調課**(v1.4.20,`tri_teacher_id` 非空):同一班三位老師輪流換課—— +甲請假那節由乙上、乙原本的一節(`tri_*`)由丙上、丙原本的一節(`swap_*`)由甲回來上。 +`swap_*` 仍是「甲回來上的那一節」,只是那一節變成丙的課;三格記在同一筆,撤回時一起撤。 +各處要逐格處理時用 `services.swap_legs.legs`,不要自己拼。 """ import enum @@ -95,6 +100,19 @@ class Substitution(Base): ForeignKey("schedule_entries.id", ondelete="SET NULL"), nullable=True ) + # ── 三角調課(v1.4.20):第三位老師丙,與乙原本那一節(改由丙上)── + tri_teacher_id: Mapped[int | None] = mapped_column( + ForeignKey("teachers.id", ondelete="SET NULL"), nullable=True, index=True + ) + tri_date: Mapped[date | None] = mapped_column(Date, nullable=True) + tri_period_no: Mapped[int | None] = mapped_column(Integer, nullable=True) + tri_period_name: Mapped[str] = mapped_column(String(32), default="") + tri_class_names: Mapped[str] = mapped_column(String(128), default="") + tri_subject_name: Mapped[str] = mapped_column(String(64), default="") + tri_entry_id: Mapped[int | None] = mapped_column( + ForeignKey("schedule_entries.id", ondelete="SET NULL"), nullable=True + ) + note: Mapped[str] = mapped_column(Text, default="") created_by_user_id: Mapped[int | None] = mapped_column( ForeignKey("users.id", ondelete="SET NULL"), nullable=True @@ -105,4 +123,11 @@ class Substitution(Base): DateTime(timezone=True), server_default=func.now(), onupdate=func.now() ) - handler: Mapped[Teacher | None] = relationship(lazy="selectin") + handler: Mapped[Teacher | None] = relationship( + lazy="selectin", foreign_keys=[handler_teacher_id]) + tri_teacher: Mapped[Teacher | None] = relationship( + lazy="selectin", foreign_keys=[tri_teacher_id]) + + @property + def is_triangle(self) -> bool: + return self.type == SubstitutionType.swap.value and self.tri_teacher_id is not None diff --git a/backend/app/schemas/leave.py b/backend/app/schemas/leave.py index fe852ce2..dafa77f3 100644 --- a/backend/app/schemas/leave.py +++ b/backend/app/schemas/leave.py @@ -28,6 +28,10 @@ class AffectedPeriodOut(BaseModel): # 調課才有:請假教師回來補課的那一節(讓清單直接寫出「王師 10/8 第二節補課」) swap_date: _Date | None = None swap_period_name: str = "" + # 三角調課(v1.4.20):丙來上乙的那一節 + tri_teacher_name: str = "" + tri_date: _Date | None = None + tri_period_name: str = "" # 代課的計費方式與是否計入鐘點(v1.4.4 起可事後修改,畫面要顯示目前的值) funding_source: str = "" counts_toward_hours: bool | None = None diff --git a/backend/app/schemas/substitution.py b/backend/app/schemas/substitution.py index f2a9f76a..a1966448 100644 --- a/backend/app/schemas/substitution.py +++ b/backend/app/schemas/substitution.py @@ -49,6 +49,11 @@ class AssignRequest(BaseModel): swap_entry_id: int | None = None swap_date: date | None = None swap_period_no: int | None = None # 連堂格位換其中哪一節;空 = 第一節 + # 三角調課(v1.4.20):丙來上乙的 tri 那一節;swap_* 改指丙那一節(甲回來上) + tri_teacher_id: int | None = None + tri_entry_id: int | None = None + tri_date: date | None = None + tri_period_no: int | None = None class BatchAssignRequest(BaseModel): @@ -98,6 +103,12 @@ class SubstitutionOut(BaseModel): swap_period_name: str = "" swap_class_names: str = "" swap_subject_name: str = "" + tri_teacher_id: int | None = None + tri_teacher_name: str = "" + tri_date: date | None = None + tri_period_name: str = "" + tri_class_names: str = "" + tri_subject_name: str = "" created_by_name: str @@ -136,6 +147,39 @@ class SwapOptionsOut(BaseModel): +class TriangleLessonOut(BaseModel): + entry_id: int + date: date + weekday: int + period_no: int + period_name: str + class_names: str + subject_name: str + in_block: bool = False + teacher_id: int + teacher_name: str + + +class TriangleOptionOut(BaseModel): + partner_id: int + partner_name: str + mid: TriangleLessonOut # 乙原本的那一節,丙來上 + third_id: int + third_name: str + makeup: TriangleLessonOut # 丙原本的那一節,甲回來上 + + +class TriangleOptionsOut(BaseModel): + """三角調課(v1.4.20):可行的三人組合。`unavailable` 非空 = 這一節不能三角調課。""" + + affected_period_id: int + date_from: date + date_to: date + unavailable: str = "" + total: int = 0 + options: list[TriangleOptionOut] = [] + + class SlipRowOut(BaseModel): ordinal: int start_time: time | None = None diff --git a/backend/app/schemas/substitution_log.py b/backend/app/schemas/substitution_log.py index 4953dde7..fe14ced0 100644 --- a/backend/app/schemas/substitution_log.py +++ b/backend/app/schemas/substitution_log.py @@ -40,6 +40,11 @@ class LogEntryOut(BaseModel): swap_subject_name: str = "" note: str = "" row_kind: str = "leave" # leave / swap_makeup(調課補課日被換來的那一節) + # 三角調課(v1.4.20):請假那一列另記丙與乙原本那一節 + is_triangle: bool = False + tri_teacher_name: str = "" + tri_date: _Date | None = None + tri_period_name: str = "" class PatrolCellOut(BaseModel): diff --git a/backend/app/services/availability.py b/backend/app/services/availability.py index f42dca07..381707b6 100644 --- a/backend/app/services/availability.py +++ b/backend/app/services/availability.py @@ -233,6 +233,21 @@ def _already_covering(self, teacher_id: int, when: date, slot: Interval) -> Inte for (swap_period_no,) in swaps: if swap_period_no == slot.period_no: # 調課補課以節次號記錄 return Interval(slot.weekday, swap_period_no, None, None) + # (c) 三角調課的丙:來上乙原本那一節(tri_date,v1.4.20) + tris = self.db.execute( + select(Substitution.tri_period_no) + .join(AffectedPeriod, Substitution.affected_period_id == AffectedPeriod.id) + .join(LeaveRequest, AffectedPeriod.leave_request_id == LeaveRequest.id) + .where( + Substitution.tri_date == when, + Substitution.tri_teacher_id == teacher_id, + LeaveRequest.status == LeaveStatus.registered.value, + AffectedPeriod.status != AffectedStatus.cancelled.value, + ) + ).all() + for (tri_period_no,) in tris: + if tri_period_no == slot.period_no: + return Interval(slot.weekday, tri_period_no, None, None) return None # ── 對外:某教師某時段能不能用 ── diff --git a/backend/app/services/leaves.py b/backend/app/services/leaves.py index 897ebd18..ef0d1482 100644 --- a/backend/app/services/leaves.py +++ b/backend/app/services/leaves.py @@ -475,6 +475,20 @@ def cancel( body=f"以下 {len(periods)} 節課不需要您代課了:{detail}", ) + # 三角調課的丙(v1.4.20):不必來上乙那一節,自己那一節也照原課表 + for period in revoked: + sub = period.substitution + if sub is not None and sub.is_triangle and sub.tri_teacher_id is not None: + notifications.notify( + db, semester_id=leave.semester_id, teacher_id=sub.tri_teacher_id, + type=NotificationType.substitution_cancelled, + title=f"原訂三角調課已取消({leave.teacher.name} " + f"{'取消調課' if swap_only else '銷假'})", + body=(f"您不必於 {sub.tri_date} {sub.tri_period_name} 上" + f"{sub.tri_class_names}的課,{sub.swap_date} {sub.swap_period_name}" + " 照原課表上課"), + ) + # 代導:已經過完的日子保留(代過了,代導費照算),其餘取消並通知代導老師 revoked_covers: list[HomeroomCover] = [] covers_by_handler: dict[int, list[HomeroomCover]] = {} diff --git a/backend/app/services/patrol_sheets.py b/backend/app/services/patrol_sheets.py index 7dcdbf6e..b550e584 100644 --- a/backend/app/services/patrol_sheets.py +++ b/backend/app/services/patrol_sheets.py @@ -22,7 +22,7 @@ from dataclasses import dataclass, field from datetime import date, time, timedelta -from sqlalchemy import select +from sqlalchemy import or_, select from sqlalchemy.orm import Session from app.core.week_parity import runs_in_week, week_parity @@ -36,6 +36,7 @@ from app.services import period_tables as pt_service from app.services import settings as app_settings from app.services import suspensions as suspension_service +from app.services import swap_legs from app.services.availability import published_timetable from app.services.slip_layout import school_title @@ -58,6 +59,7 @@ SubstitutionType.cancel.value: "停課", } _PENDING = "請假待處理" +TRIANGLE_NOTE = "三角調課" # v1.4.20 @dataclass(frozen=True, slots=True) @@ -126,7 +128,7 @@ class _Lesson: room: str note: str original: str = "" # 有異動時,課表上原本的老師(v1.4.15 課表查詢的週課表用) - swap_with: str = "" # 調課:對調的另一節「11/20 第三節」(v1.4.17 週課表用) + swap_with: str = "" # 調課:「與 11/20 第三節對調」(v1.4.17 週課表用;三角調課寫另兩節) reason: str = "" # 停課的說明「校慶補假」(v1.4.19 週課表用) @@ -157,15 +159,6 @@ def is_morning(p: Period) -> bool: return [half for half in (morning, afternoon) if half] -def _slot(day: date, period_name: str) -> str: - """調課對調的另一節:「11/20 第三節」。""" - return f"{day.month}/{day.day} {period_name}".strip() - - -def _same_class(ap: AffectedPeriod, sub: Substitution) -> bool: - return ap.class_names == sub.swap_class_names - - class Day: """某一天的實際課表:週課表格位 + 當天的請假與調代課。 @@ -205,19 +198,24 @@ def __init__(self, db: Session, semester_id: int, timetable_id: int, on: date) - self.absent: dict[tuple[int | None, int], tuple[AffectedPeriod, Substitution | None]] = { (a.course_assignment_id, a.period_no): (a, subs.get(a.id)) for a in absent } - # 當天因調課回來補課的節次:(格位, 節次) → (請假那一節, 調課處置) - self.makeup: dict[tuple[int | None, int | None], tuple[AffectedPeriod, Substitution]] = {} + # 當天因調課換人上的其他節次(互調:甲回來補課;三角調課:丙上乙那節、甲上丙那節): + # (格位, 節次) → (請假那一節, 調課處置, 這一格) + self.makeup: dict[tuple[int | None, int | None], + tuple[AffectedPeriod, Substitution, swap_legs.Leg]] = {} for sub in db.scalars( select(Substitution) .join(AffectedPeriod, Substitution.affected_period_id == AffectedPeriod.id) .join(LeaveRequest, AffectedPeriod.leave_request_id == LeaveRequest.id) .where( Substitution.type == SubstitutionType.swap.value, - Substitution.swap_date == on, *live) + or_(Substitution.swap_date == on, Substitution.tri_date == on), *live) ): ap = db.get(AffectedPeriod, sub.affected_period_id) - if ap is not None: - self.makeup[(sub.swap_entry_id, sub.swap_period_no)] = (ap, sub) + if ap is None: + continue + for leg in swap_legs.legs(ap, sub): + if not leg.absent_slot and leg.date == on: + self.makeup[(leg.entry_id, leg.period_no)] = (ap, sub, leg) # 停課日(v1.4.19):停課的課不上,優先於當天的調代課(停課是事後設的,設定時已提醒組長) self.calendar = suspension_service.Calendar(db, semester_id, on, on) @@ -265,20 +263,18 @@ def replace(absent_name: str, by: str) -> None: replace(absent_name, sub.handler.name) elif absent_name in names: # 自習、停課:沒有人接手,請假的那位不會來 names.remove(absent_name) + if sub.is_triangle: + note = TRIANGLE_NOTE if sub.type == SubstitutionType.swap.value: - if sub.swap_date is not None: - swap_with = _slot(sub.swap_date, sub.swap_period_name) - if _same_class(ap, sub): - subject = sub.swap_subject_name or subject # 同班互調:科目跟著老師走 + legs = swap_legs.legs(ap, sub) + swap_with = swap_legs.partner_text(ap, sub, legs[0]) + subject = legs[0].subject_taught or subject # 同班:科目跟著老師走 elif (entry.id, period_no) in self.makeup: - ap, sub = self.makeup[(entry.id, period_no)] - note = _NOTE[SubstitutionType.swap.value] - partner = sub.handler.name if sub.handler else "" - back = ap.leave_request.teacher.name if ap.leave_request.teacher else "" - replace(partner, back) - swap_with = _slot(ap.date, ap.period_name) - if _same_class(ap, sub): - subject = ap.subject_name or subject + ap, sub, leg = self.makeup[(entry.id, period_no)] + note = TRIANGLE_NOTE if sub.is_triangle else _NOTE[SubstitutionType.swap.value] + replace(leg.owner_name, leg.teacher_name) + swap_with = swap_legs.partner_text(ap, sub, leg) + subject = leg.subject_taught or subject return _Lesson( unit_id=unit.id, unit_name=unit.name, is_group=unit.unit_type == "group", diff --git a/backend/app/services/substitution_log.py b/backend/app/services/substitution_log.py index 1163c277..150db41d 100644 --- a/backend/app/services/substitution_log.py +++ b/backend/app/services/substitution_log.py @@ -29,7 +29,7 @@ ) from app.models.substitution import SUBSTITUTION_TYPE_CN, Substitution, SubstitutionType from app.models.timetable import ScheduleEntry -from app.services import leaves +from app.services import leaves, swap_legs from app.services.availability import Availability # 欄位名 date/start_time 會遮蔽同名型別,故以別名標註型別 @@ -79,6 +79,12 @@ class LogEntry: # leave:請假的那一節。swap_makeup:調課補課日的那一節——「原任教師」是對調的乙, # 「接手」是回來補課的甲,swap_* 反過來記請假那一節(兩列互相指向對方)。 row_kind: str = ROW_LEAVE + # 三角調課(v1.4.20):請假那一列另記丙與乙原本那一節(丙來上)。 + # swap_makeup 列的 swap_* 是「來上的老師自己空出來的那一節」 + is_triangle: bool = False + tri_teacher_name: str = "" + tri_date: _Date | None = None + tri_period_name: str = "" def school_today() -> date: @@ -133,6 +139,10 @@ def _build(ap: AffectedPeriod, sub: Substitution | None) -> LogEntry: swap_class_names=sub.swap_class_names if sub else "", swap_subject_name=sub.swap_subject_name if sub else "", note=ap.note or (sub.note if sub else ""), + is_triangle=bool(sub and sub.is_triangle), + tri_teacher_name=sub.tri_teacher.name if sub and sub.tri_teacher else "", + tri_date=sub.tri_date if sub else None, + tri_period_name=sub.tri_period_name if sub else "", ) @@ -142,6 +152,7 @@ def _makeup_rows(db: Session, semester_id: int, on: date) -> list[LogEntry]: 調課成立後那天有兩處異動:請假日由乙代甲,補課日由甲上乙原本那節。後者在 `affected_period` 裡沒有一列(乙沒請假),只記在 `substitution.swap_*`—— 不另外列出,補課那天的看板與公告單就會漏掉,那一班會看到「課表上是乙、來的是甲」。 + 三角調課(v1.4.20)另有丙上乙原本那一節,一樣列出(見 `swap_legs`)。 """ subs = db.scalars( select(Substitution) @@ -150,7 +161,7 @@ def _makeup_rows(db: Session, semester_id: int, on: date) -> list[LogEntry]: .where( Substitution.semester_id == semester_id, Substitution.type == SubstitutionType.swap.value, - Substitution.swap_date == on, + or_(Substitution.swap_date == on, Substitution.tri_date == on), LeaveRequest.status == LeaveStatus.registered.value, AffectedPeriod.status != AffectedStatus.cancelled.value, ) @@ -164,47 +175,50 @@ def _makeup_rows(db: Session, semester_id: int, on: date) -> list[LogEntry]: ap = db.get(AffectedPeriod, sub.affected_period_id) if ap is None: continue - leave = ap.leave_request - entry = db.get(ScheduleEntry, sub.swap_entry_id) if sub.swap_entry_id else None - period = av.entry_period(entry, sub.swap_period_no) if entry else None - start = period.start_time if period else None - end = period.end_time if period else None - room_name = "" - if entry is not None: - room_id = entry.room_id if entry.room_id is not None else entry.assignment.room_id - room = db.get(Room, room_id) if room_id else None - room_name = room.name if room else "" - status = leaves.effective_status(ap.status, on, end) - out.append(LogEntry( - affected_period_id=ap.id, - date=on, - weekday=on.isoweekday(), - period_no=sub.swap_period_no or 0, - period_name=sub.swap_period_name, - start_time=start, - end_time=end, - class_names=sub.swap_class_names, - subject_name=sub.swap_subject_name, - room_name=room_name, - absent_teacher_id=sub.handler_teacher_id or 0, - absent_teacher_name=sub.handler.name if sub.handler else "(已移除)", - leave_type="", - leave_type_label="調課補課", - status=status, - status_label=AFFECTED_STATUS_CN.get(status, status), - disposed=True, - sub_type=sub.type, - sub_type_label=SUBSTITUTION_TYPE_CN.get(sub.type), - handler_teacher_id=leave.teacher_id, - handler_name=leave.teacher.name if leave.teacher else "(已移除)", - counts_toward_hours=sub.counts_toward_hours, - swap_date=ap.date, - swap_period_name=ap.period_name, - swap_class_names=ap.class_names, - swap_subject_name=ap.subject_name, - note="", - row_kind=ROW_SWAP_MAKEUP, - )) + for leg in swap_legs.legs(ap, sub): + if leg.absent_slot or leg.date != on: + continue + entry = db.get(ScheduleEntry, leg.entry_id) if leg.entry_id else None + period = av.entry_period(entry, leg.period_no) if entry else None + start = period.start_time if period else None + end = period.end_time if period else None + room_name = "" + if entry is not None: + room_id = entry.room_id if entry.room_id is not None else entry.assignment.room_id + room = db.get(Room, room_id) if room_id else None + room_name = room.name if room else "" + status = leaves.effective_status(ap.status, on, end) + out.append(LogEntry( + affected_period_id=ap.id, + date=on, + weekday=on.isoweekday(), + period_no=leg.period_no, + period_name=leg.period_name, + start_time=start, + end_time=end, + class_names=leg.class_names, + subject_name=leg.subject_name, + room_name=room_name, + absent_teacher_id=leg.owner_id or 0, + absent_teacher_name=leg.owner_name or "(已移除)", + leave_type="", + leave_type_label="三角調課" if sub.is_triangle else "調課補課", + status=status, + status_label=AFFECTED_STATUS_CN.get(status, status), + disposed=True, + sub_type=sub.type, + sub_type_label=SUBSTITUTION_TYPE_CN.get(sub.type), + handler_teacher_id=leg.teacher_id, + handler_name=leg.teacher_name or "(已移除)", + counts_toward_hours=sub.counts_toward_hours, + swap_date=leg.back_date, + swap_period_name=leg.back_period_name, + swap_class_names=leg.back_class_names, + swap_subject_name=leg.back_subject_name, + note="", + row_kind=ROW_SWAP_MAKEUP, + is_triangle=sub.is_triangle, + )) return out @@ -264,6 +278,9 @@ def query( stmt = stmt.where(or_( LeaveRequest.teacher_id == teacher_id, AffectedPeriod.handler_teacher_id == teacher_id, + # 三角調課的丙(v1.4.20):他也換了課 + AffectedPeriod.id.in_(select(Substitution.affected_period_id) + .where(Substitution.tri_teacher_id == teacher_id)), )) rows = db.scalars( stmt.order_by(AffectedPeriod.date.desc(), AffectedPeriod.period_no).limit(limit) diff --git a/backend/app/services/substitutions.py b/backend/app/services/substitutions.py index 25cc98df..dd41ce2d 100644 --- a/backend/app/services/substitutions.py +++ b/backend/app/services/substitutions.py @@ -9,6 +9,10 @@ 各處置的鐘點:代課計、併班/自習/不處理不計(§5.4 月結)。 調課(swap)要驗兩位教師交換後都無衝突,拒絕時說出是誰在哪一節撞課。 + +**三角調課**(v1.4.20,給了 `tri_teacher_id`):乙來上請假那節、丙來上乙的 `tri_*` 那節、 +甲回來上丙的 `swap_*` 那節。三格都要驗;成立時三位老師都收到通知,撤回時一起撤、都收到取消通知。 +鐘點都不計(和互調一樣)。 """ from dataclasses import dataclass @@ -38,7 +42,7 @@ from app.models.timetable import ScheduleEntry from app.services import notifications from app.services.availability import Availability -from app.services.swap_options import SwapChecker, block_periods +from app.services.swap_options import SwapChecker, block_periods, triangle_unit class SubstitutionError(Exception): @@ -78,8 +82,16 @@ def assign( created_by_name: str, swap_period_no: int | None = None, availability: Availability | None = None, + tri_teacher_id: int | None = None, + tri_entry_id: int | None = None, + tri_date: date | None = None, + tri_period_no: int | None = None, ) -> Substitution: - """對一個受影響節次做處置。呼叫端負責 commit。""" + """對一個受影響節次做處置。呼叫端負責 commit。 + + `tri_*` 給了就是三角調課(只限調課):丙(`tri_teacher_id`)來上乙的 `tri_entry_id` 那節, + 甲回來上丙的 `swap_entry_id` 那節。 + """ if affected.status == AffectedStatus.cancelled.value: raise SubstitutionError("此節次已因銷假取消,無法處置") backfill = is_backfill(affected) @@ -103,8 +115,17 @@ def assign( av = availability or Availability(db, affected.semester_id) handler = _resolve_handler(db, affected, sub_type, handler_teacher_id, av) + triangle = tri_teacher_id is not None + if triangle and sub_type != SubstitutionType.swap.value: + raise SubstitutionError("三角調課只能選調課") swap_fields: dict = {} - if sub_type == SubstitutionType.swap.value: + if sub_type == SubstitutionType.swap.value and triangle: + swap_fields = _validate_triangle( + db, affected, handler, av, + tri_teacher_id=tri_teacher_id, tri_entry_id=tri_entry_id, tri_date=tri_date, + tri_period_no=tri_period_no, swap_entry_id=swap_entry_id, swap_date=swap_date, + swap_period_no=swap_period_no) + elif sub_type == SubstitutionType.swap.value: swap_fields = _validate_swap( db, affected, handler, swap_entry_id, swap_date, swap_period_no, av) @@ -121,10 +142,15 @@ def assign( sub_type, affected.leave_request.leave_type) sub.created_by_user_id = created_by_user_id sub.created_by_name = created_by_name + if sub.is_triangle and sub.tri_teacher_id != tri_teacher_id: + # 改派:原本三角調課的丙要知道不用來了 + _notify_tri_cancelled(db, affected, sub, created_by_name) for k, v in swap_fields.items(): setattr(sub, k, v) if sub_type != SubstitutionType.swap.value: _clear_swap(sub) + if not triangle: + _clear_tri(sub) affected.status = AffectedStatus.resolved.value affected.handler_teacher_id = handler.id if handler else None @@ -349,6 +375,113 @@ def _validate_swap( } +def _lesson_of( + db: Session, av: Availability, affected: AffectedPeriod, unit_id: int, + teacher: Teacher, entry_id: int | None, when: date | None, period_no: int | None, + what: str, +) -> tuple[ScheduleEntry, int]: + """三角調課的一格:確認是這個班、這位老師在已發布課表裡的課,日期星期相符。""" + if entry_id is None or when is None: + raise SubstitutionError(f"三角調課需要指定{what}") + entry = db.get(ScheduleEntry, entry_id) + if entry is None or av.timetable is None or entry.timetable_id != av.timetable.id: + raise SubstitutionError(f"找不到{what}(需為已發布課表中的課)") + a = entry.assignment + if a.scheduling_unit_id != unit_id: + raise SubstitutionError(f"{what}不是 {affected.class_names} 的課(三角調課只限同一個班)") + if [t.teacher_id for t in a.teachers] != [teacher.id]: + raise SubstitutionError(f"{what}不是 {teacher.name} 一個人上的課") + if when.isoweekday() != entry.weekday: + raise SubstitutionError( + f"{when} 是 {_wd(when.isoweekday())},但{what}在 {_wd(entry.weekday)}") + if not av.entry_runs_on(entry, when): + raise SubstitutionError(f"{when} 那一週沒有{what}(單雙週的課)") + no = entry.period_no if period_no is None else period_no + if no not in block_periods(av, entry): + raise SubstitutionError(f"指定的節次不在{what}的時段內") + if when == affected.date and no == affected.period_no: + raise SubstitutionError(f"{what}不能是請假的同一節") + return entry, no + + +def _validate_triangle( + db: Session, + affected: AffectedPeriod, + handler: Teacher | None, + av: Availability, + *, + tri_teacher_id: int | None, + tri_entry_id: int | None, + tri_date: date | None, + tri_period_no: int | None, + swap_entry_id: int | None, + swap_date: date | None, + swap_period_no: int | None, +) -> dict: + """三角調課(v1.4.20):三格與 `swap_options.triangle_search` 同一套規則。 + + ① 乙(handler)在甲請假那節有空 + ② 乙的 tri 那一節讓得出來(沒停課、乙沒請假、沒拿去調過),丙那節有空 + ③ 丙的 swap 那一節,甲回得來(與互調的補課節次同一套檢查) + """ + if handler is None: + raise SubstitutionError("調課需要指定對調教師") + unit_id, why = triangle_unit(db, affected) + if unit_id is None: + raise SubstitutionError(why) + third = db.scalar(select(Teacher).where( + Teacher.id == tri_teacher_id, Teacher.semester_id == affected.semester_id)) + if third is None: + raise SubstitutionError("找不到三角調課的第三位老師") + absent_id = affected.leave_request.teacher_id + if third.id in (absent_id, handler.id): + raise SubstitutionError("三角調課要三位不同的老師") + + mid, mid_no = _lesson_of(db, av, affected, unit_id, handler, tri_entry_id, tri_date, + tri_period_no, f"{handler.name}要讓出的那一節") + makeup, makeup_no = _lesson_of(db, av, affected, unit_id, third, swap_entry_id, swap_date, + swap_period_no, f"{third.name}要讓出的那一節") + assert tri_date is not None and swap_date is not None + + checker = SwapChecker(db, affected, av) + blocked = checker.partner_blocker(handler) + if blocked is not None: + raise SubstitutionError(f"{blocked},無法三角調課") + for entry, when, no in ((mid, tri_date, mid_no), (makeup, swap_date, makeup_no)): + if checker.out_of_reach(entry, when, no): + raise SubstitutionError( + f"{when} {_entry_period_name(av, entry, no)} 已經上過或不在學期內,無法調課") + reason = checker.mid_reason(handler, third, mid, tri_date, mid_no) + if reason: + raise SubstitutionError(f"{tri_date} {_entry_period_name(av, mid, mid_no)} {reason}") + blocked = checker.option_blocker(third, makeup, swap_date, makeup_no) + if blocked is not None: + raise SubstitutionError(blocked) + + def snap(entry: ScheduleEntry) -> tuple[str, str]: + a = entry.assignment + return ("、".join(m.class_unit.name for m in a.scheduling_unit.members), + a.subject.name if a.subject else "") + + mid_classes, mid_subject = snap(mid) + makeup_classes, makeup_subject = snap(makeup) + return { + "tri_teacher_id": third.id, + "tri_date": tri_date, + "tri_period_no": mid_no, + "tri_period_name": _entry_period_name(av, mid, mid_no), + "tri_class_names": mid_classes, + "tri_subject_name": mid_subject, + "tri_entry_id": mid.id, + "swap_date": swap_date, + "swap_period_no": makeup_no, + "swap_period_name": _entry_period_name(av, makeup, makeup_no), + "swap_class_names": makeup_classes, + "swap_subject_name": makeup_subject, + "swap_entry_id": makeup.id, + } + + def _entry_period_name(av: Availability, entry: ScheduleEntry, period_no: int) -> str: p = av.entry_period(entry, period_no) return p.name if p else f"第 {period_no} 格" @@ -363,12 +496,41 @@ def _clear_swap(sub: Substitution) -> None: sub.swap_entry_id = None +def _clear_tri(sub: Substitution) -> None: + sub.tri_teacher_id = None + sub.tri_date = None + sub.tri_period_no = None + sub.tri_period_name = "" + sub.tri_class_names = "" + sub.tri_subject_name = "" + sub.tri_entry_id = None + + +def _notify_tri_cancelled( + db: Session, affected: AffectedPeriod, sub: Substitution, actor_name: str +) -> None: + """三角調課取消:丙不必來上乙那一節(乙、甲另有通知)。""" + if sub.tri_teacher_id is None: + return + notifications.notify( + db, semester_id=affected.semester_id, teacher_id=sub.tri_teacher_id, + type=NotificationType.substitution_cancelled, + title="原訂三角調課已取消", + body=(f"{actor_name} 取消了 {affected.date} {affected.period_name} 的三角調課;" + f"您不必於 {sub.tri_date} {sub.tri_period_name} 上" + f"{sub.tri_class_names}的課,{sub.swap_date} {sub.swap_period_name} 照原課表上課"), + ) + + def _notify_handler( db: Session, affected: AffectedPeriod, sub: Substitution, handler: Teacher ) -> None: absent = affected.leave_request.teacher type_cn = SUBSTITUTION_TYPE_CN[sub.type] where = f"{affected.date} {affected.period_name}({affected.class_names}{affected.subject_name})" + if sub.is_triangle and sub.tri_teacher is not None: + _notify_triangle(db, affected, sub, handler, sub.tri_teacher, where) + return if sub.type == SubstitutionType.swap.value: body = ( f"請於 {where} 代 {absent.name} 一節;" @@ -397,6 +559,33 @@ def _notify_handler( ) +def _notify_triangle( + db: Session, affected: AffectedPeriod, sub: Substitution, handler: Teacher, third: Teacher, + where: str, +) -> None: + """三角調課:三位老師各要去上一節,各收一則通知。""" + absent = affected.leave_request.teacher + mid = f"{sub.tri_date} {sub.tri_period_name}({sub.tri_class_names}{sub.tri_subject_name})" + makeup = (f"{sub.swap_date} {sub.swap_period_name}" + f"({sub.swap_class_names}{sub.swap_subject_name})") + who = f"{absent.name}、{handler.name}、{third.name}" + for teacher, title, body in ( + (handler, f"三角調課通知:{affected.date} {affected.period_name}", + f"請於 {where} 上課(代 {absent.name});您 {mid} 那一節由 {third.name} 上"), + (third, f"三角調課通知:{sub.tri_date} {sub.tri_period_name}", + f"請於 {sub.tri_date} {sub.tri_period_name} 上課(代 {handler.name} 的" + f"{sub.tri_class_names}{sub.tri_subject_name});您 {makeup} 那一節由 {absent.name} 上"), + (absent, f"三角調課補課通知:{sub.swap_date} {sub.swap_period_name}", + f"{handler.name} 將於 {where} 代您上課;請您於 {sub.swap_date} {sub.swap_period_name} " + f"上 {third.name} 的{sub.swap_class_names}{sub.swap_subject_name}"), + ): + notifications.notify( + db, semester_id=affected.semester_id, teacher_id=teacher.id, + type=NotificationType.substitution_assigned, title=title, + body=f"{body}({who} 三人輪流換課)", + ) + + def clear(db: Session, affected: AffectedPeriod, *, actor_name: str) -> None: """撤回處置:受影響節次退回『待處理』,已指派的教師收到取消通知。呼叫端負責 commit。""" if affected.leave_request.status == LeaveStatus.cancelled.value: @@ -413,6 +602,8 @@ def clear(db: Session, affected: AffectedPeriod, *, actor_name: str) -> None: title=f"原訂{SUBSTITUTION_TYPE_CN[sub.type]}已取消", body=f"{actor_name} 取消了 {affected.date} {affected.period_name} 的處置", ) + if sub.is_triangle: + _notify_tri_cancelled(db, affected, sub, actor_name) if sub.type == SubstitutionType.swap.value: notifications.notify( db, semester_id=affected.semester_id, teacher_id=affected.leave_request.teacher_id, diff --git a/backend/app/services/suspensions.py b/backend/app/services/suspensions.py index 7274b1c0..e953ca2f 100644 --- a/backend/app/services/suspensions.py +++ b/backend/app/services/suspensions.py @@ -13,7 +13,7 @@ from dataclasses import dataclass from datetime import date -from sqlalchemy import select +from sqlalchemy import and_, or_, select from sqlalchemy.orm import Session from app.models.assignment import CourseAssignment @@ -31,6 +31,7 @@ from app.models.suspension import ClassSuspension from app.models.timetable import ScheduleEntry from app.services import period_tables as pt_service +from app.services import swap_legs def label(s: ClassSuspension) -> str: @@ -216,17 +217,26 @@ def conflicts(db: Session, s: ClassSuspension) -> list[Conflict]: .join(LeaveRequest, AffectedPeriod.leave_request_id == LeaveRequest.id) .where( Substitution.type == SubstitutionType.swap.value, - Substitution.swap_date >= s.start_date, Substitution.swap_date <= s.end_date, *live) + or_(and_(Substitution.swap_date >= s.start_date, + Substitution.swap_date <= s.end_date), + and_(Substitution.tri_date >= s.start_date, + Substitution.tri_date <= s.end_date)), *live) ): - entry = db.get(ScheduleEntry, sub.swap_entry_id) if sub.swap_entry_id else None - if (entry is None or sub.swap_date is None or sub.swap_period_no is None - or cal.for_entry(entry, sub.swap_date, sub.swap_period_no) is None): - continue absent = db.get(AffectedPeriod, sub.affected_period_id) - who = absent.leave_request.teacher.name if absent and absent.leave_request.teacher else "" - out.append(Conflict(sub.swap_date, ( - f"{_md(sub.swap_date)} {sub.swap_period_name} {sub.swap_class_names}:" - f"{who} 調課回來補課"))) + if absent is None: + continue + # 調課換人上的其他節次(互調:甲回來補課;三角調課另有丙上乙那節) + for leg in swap_legs.legs(absent, sub): + entry = db.get(ScheduleEntry, leg.entry_id) if leg.entry_id else None + if (leg.absent_slot or entry is None + or not s.start_date <= leg.date <= s.end_date + or cal.for_entry(entry, leg.date, leg.period_no) is None): + continue + back_home = leg.teacher_id == absent.leave_request.teacher_id + what = "調課回來補課" if back_home else "三角調課來上課" + out.append(Conflict(leg.date, ( + f"{_md(leg.date)} {leg.period_name} {leg.class_names}:" + f"{leg.teacher_name} {what}"))) for cover in db.scalars( select(HomeroomCover) diff --git a/backend/app/services/swap_legs.py b/backend/app/services/swap_legs.py new file mode 100644 index 00000000..665d0480 --- /dev/null +++ b/backend/app/services/swap_legs.py @@ -0,0 +1,154 @@ +"""一筆調課裡「換人上」的每一格(v1.4.20,三角調課時抽出來共用)。 + +- 兩人互調:兩格。甲請假那節由乙上;乙原本那節(`swap_*`)由甲回來上。 +- 三角調課:三格。甲請假那節由乙上;乙原本那節(`tri_*`)由丙上; + 丙原本那節(`swap_*`)由甲回來上。 + +巡堂表、週課表、教師週總表、調課單、調代課紀錄、停課衝突都從這裡取, +不要各自用 `swap_*` / `tri_*` 拼——三角調課每一格的「原本是誰、誰來上、上什麼」都不一樣。 + +**科目怎麼寫**(與調課單相同):同班互調時科目跟著老師走(學生只是幾科前後對換); +跨班對調時去的是別人的班、上的是那一節原本的課。三角調課只限同一班,一律跟著老師走。 + +**back** 是「來上的這位老師自己空出來的那一節」:調課單、教師週總表的 +[調月/日_星期節次] 記號指向它(乙的記號指向乙原本那節,以此類推)。 +""" + +from dataclasses import dataclass +from datetime import date as _Date + +from app.models.leave import AffectedPeriod +from app.models.substitution import Substitution, SubstitutionType + + +@dataclass(frozen=True, slots=True) +class Slot: + """課表上的某一天某一節(快照):請假那一節以配課記,其他以課表格子記。""" + + date: _Date + period_no: int + period_name: str + class_names: str + subject_name: str + entry_id: int | None = None + assignment_id: int | None = None + + +@dataclass(frozen=True, slots=True) +class Leg: + date: _Date + period_no: int + period_name: str + entry_id: int | None # 課表格子;請假那一節為 None(以配課比對) + assignment_id: int | None # 請假那一節的配課;其他格為 None(要時由 entry 取) + class_names: str + subject_name: str # 這一格原本的科目 + owner_id: int | None # 課表上原本的老師 + owner_name: str + teacher_id: int | None # 實際來上的老師 + teacher_name: str + subject_taught: str # 實際上的科目 + back: Slot | None # 來上的老師自己空出來的那一節 + absent_slot: bool = False # 是請假(或調課未請假)的那一節 + + # 給呼叫端少寫一層 + @property + def back_date(self) -> _Date | None: + return self.back.date if self.back else None + + @property + def back_period_no(self) -> int | None: + return self.back.period_no if self.back else None + + @property + def back_period_name(self) -> str: + return self.back.period_name if self.back else "" + + @property + def back_entry_id(self) -> int | None: + return self.back.entry_id if self.back else None + + @property + def back_assignment_id(self) -> int | None: + return self.back.assignment_id if self.back else None + + @property + def back_class_names(self) -> str: + return self.back.class_names if self.back else "" + + @property + def back_subject_name(self) -> str: + return self.back.subject_name if self.back else "" + + +def _name(t) -> str: + return t.name if t is not None else "" + + +def _leg(slot: Slot, owner, teacher, subject_taught: str, back: Slot | None, + absent_slot: bool = False) -> Leg: + return Leg( + date=slot.date, period_no=slot.period_no, period_name=slot.period_name, + entry_id=slot.entry_id, assignment_id=slot.assignment_id, + class_names=slot.class_names, subject_name=slot.subject_name, + owner_id=owner.id if owner is not None else None, owner_name=_name(owner), + teacher_id=teacher.id if teacher is not None else None, teacher_name=_name(teacher), + subject_taught=subject_taught, back=back, absent_slot=absent_slot, + ) + + +def legs(ap: AffectedPeriod, sub: Substitution) -> list[Leg]: + """這筆調課換人上的每一格,第一格一定是請假那一節。 + + 補課那一節資料不完整(對調的課被刪除)時只回請假那一格,back 為空。 + """ + if sub.type != SubstitutionType.swap.value: + return [] + absent = ap.leave_request.teacher + handler = sub.handler + x = Slot(ap.date, ap.period_no, ap.period_name, ap.class_names, ap.subject_name, + assignment_id=ap.course_assignment_id) + z = None + if sub.swap_date is not None and sub.swap_period_no is not None: + z = Slot(sub.swap_date, sub.swap_period_no, sub.swap_period_name, + sub.swap_class_names, sub.swap_subject_name, entry_id=sub.swap_entry_id) + + if sub.tri_teacher_id is not None and sub.tri_date is not None \ + and sub.tri_period_no is not None: + third = sub.tri_teacher + y = Slot(sub.tri_date, sub.tri_period_no, sub.tri_period_name, + sub.tri_class_names, sub.tri_subject_name, entry_id=sub.tri_entry_id) + out = [ + _leg(x, absent, handler, y.subject_name, y, absent_slot=True), + _leg(y, handler, third, z.subject_name if z else "", z), + ] + if z is not None: + out.append(_leg(z, third, absent, x.subject_name, x)) + return out + + if z is None: + return [_leg(x, absent, handler, x.subject_name, None, absent_slot=True)] + same_class = x.class_names == z.class_names + return [ + _leg(x, absent, handler, (z.subject_name or x.subject_name) if same_class + else x.subject_name, z, absent_slot=True), + _leg(z, handler, absent, (x.subject_name or z.subject_name) if same_class + else z.subject_name, x), + ] + + +def slot_text(day: _Date, period_name: str) -> str: + """「11/20 第三節」。""" + return f"{day.month}/{day.day} {period_name}".strip() + + +def partner_text(ap: AffectedPeriod, sub: Substitution, leg: Leg) -> str: + """週課表那一格的補充說明:互調寫「與 11/20 第三節對調」;三角調課寫「另兩節 …」。""" + if sub.is_triangle: + others = [slot_text(x.date, x.period_name) for x in legs(ap, sub) + if (x.date, x.period_no, x.absent_slot) + != (leg.date, leg.period_no, leg.absent_slot)] + return f"另兩節 {'、'.join(others)}" + if leg.back is None: + return "" + return f"與 {slot_text(leg.back.date, leg.back.period_name)}對調" diff --git a/backend/app/services/swap_options.py b/backend/app/services/swap_options.py index bb482d64..ea2dd5cc 100644 --- a/backend/app/services/swap_options.py +++ b/backend/app/services/swap_options.py @@ -7,6 +7,10 @@ **列出的與送出時驗的必須是同一套規則**,否則清單上點得到、按下去卻被拒絕。 所以逐項檢查集中在 `SwapChecker`,`substitutions._validate_swap` 也呼叫它。 + +**三角調課**(v1.4.20,`triangle_search`):兩人互調湊不出來時,同一班三位老師輪流換課—— +乙來上甲請假那節、丙來上乙原本的一節、甲回來上丙原本的一節。只限同一個班的一般課 +(一位老師上的課;跑班、單雙週組、協同教學不列),找的範圍與互調相同。 """ from dataclasses import dataclass, field @@ -29,6 +33,7 @@ from app.models.semester import Semester from app.models.substitution import Substitution, SubstitutionType from app.models.timetable import ScheduleEntry +from app.services import leaves from app.services import suspensions as suspension_service from app.services.availability import Availability, Interval @@ -65,6 +70,7 @@ def __init__(self, db: Session, affected: AffectedPeriod, av: Availability) -> N self.absent: Teacher = affected.leave_request.teacher self.semester = db.get(Semester, affected.semester_id) self._taken: set[tuple[int, date, int]] | None = None + self._in_leave: dict[tuple[int, date], dict[int, str]] = {} self._labels: dict[int, str] = {} # 停課的那一節不上課,不能拿來補課(v1.4.19) self.calendar = suspension_service.Calendar( @@ -87,11 +93,15 @@ def partner_blocker(self, partner: Teacher) -> str | None: return f"{partner.name} {a.date} {a.period_name} {conflict.detail}" def _taken_slots(self) -> set[tuple[int, date, int]]: - """已經被其他有效調課拿去換的 (乙的格位, 日期, 節次)。同一節課不能換給兩個人補。""" + """已經被其他有效調課拿去換的 (乙的格位, 日期, 節次)。同一節課不能換給兩個人補。 + + 三角調課(v1.4.20)換掉的兩格(乙那節、丙那節)都算,三角調的節次不能再調。 + """ if self._taken is None: rows = self.db.execute( select(Substitution.swap_entry_id, Substitution.swap_date, - Substitution.swap_period_no) + Substitution.swap_period_no, Substitution.tri_entry_id, + Substitution.tri_date, Substitution.tri_period_no) .join(AffectedPeriod, Substitution.affected_period_id == AffectedPeriod.id) .join(LeaveRequest, AffectedPeriod.leave_request_id == LeaveRequest.id) .where( @@ -103,10 +113,24 @@ def _taken_slots(self) -> set[tuple[int, date, int]]: ) ).all() self._taken = { - (e, d, n) for e, d, n in rows if e is not None and d is not None and n is not None + (e, d, n) for r in rows for e, d, n in (r[:3], r[3:]) + if e is not None and d is not None and n is not None } return self._taken + def in_leave(self, teacher: Teacher, when: date, period_no: int) -> str: + """這位老師這一節已經在別張有效的假單或「調課(未請假)」裡 → 那張的假別名稱。 + + 那一節已經交給別人處理了,不能再拿來對調(v1.4.20)。請假的本人不算 + (他那幾節就是這一筆要處理的)。 + """ + if teacher.id == self.absent.id: + return "" + key = (teacher.id, when) + if key not in self._in_leave: + self._in_leave[key] = leaves.taken_periods(self.db, teacher.id, when) + return self._in_leave[key].get(period_no, "") + def option_blocker( self, partner: Teacher, entry: ScheduleEntry, when: date, period_no: int ) -> str | None: @@ -148,6 +172,9 @@ def reason( return f"{partner.name}這節也請假,這節課本身就需要安排,不能拿來對調" if (entry.id, when, period_no) in self._taken_slots(): return f"{partner.name}這節已經和別的老師調課了" + taken = self.in_leave(partner, when, period_no) + if taken: + return f"{partner.name}這節已經在「{taken}」裡,不能拿來對調" absent = self.absent.name released = self._released(when) if self.av.is_on_leave(self.absent.id, when, slot): @@ -165,6 +192,43 @@ def reason( return f"{absent}{conflict.detail}" return None + def mid_reason( + self, owner: Teacher, third: Teacher, entry: ScheduleEntry, when: date, period_no: int + ) -> str | None: + """三角調課的中間那一節:乙(`owner`)原本的這一節,能不能改由丙(`third`)來上。""" + return (self.mid_base_reason(owner, entry, when, period_no) + or self.third_reason(third, entry, when, period_no)) + + def mid_base_reason( + self, owner: Teacher, entry: ScheduleEntry, when: date, period_no: int + ) -> str | None: + """中間那一節本身能不能讓出來(與來上的是誰無關)。""" + off = self.calendar.for_entry(entry, when, period_no) + if off is not None: + return f"這節{suspension_service.label(off)},不能調課" + slot = self.av.entry_slot(entry, period_no) + if self.av.is_on_leave(owner.id, when, slot): + return f"{owner.name}這節也請假,這節課本身就需要安排,不能拿來對調" + if (entry.id, when, period_no) in self._taken_slots(): + return f"{owner.name}這節已經和別的老師調課了" + taken = self.in_leave(owner, when, period_no) + if taken: + return f"{owner.name}這節已經在「{taken}」裡,不能拿來對調" + return None + + def third_reason( + self, third: Teacher, entry: ScheduleEntry, when: date, period_no: int + ) -> str | None: + """丙這一節能不能來上課(自己有課、請假、已被安排代課都不行)。""" + slot = self.av.entry_slot(entry, period_no) + hit = self.av.lesson_at(third.id, slot, when) + if hit is not None: + return f"{third.name}這節自己有課({self._lesson_label(hit[1])})" + conflict = self.av.conflict_for(third.id, when, slot) + if conflict is not None: + return f"{third.name}{conflict.detail}" + return None + def _lesson_label(self, assignment_id: int) -> str: """「702 自然」:配課的班級與科目。""" if assignment_id not in self._labels: @@ -369,3 +433,167 @@ def search( result.partners.sort(key=lambda p: ( not p.options, not p.teaches_same_class, p.teacher_name)) return result + + +# ── 三角調課(v1.4.20)──────────────────────────────────────── + + +@dataclass(frozen=True, slots=True) +class Lesson: + """這一班某一天某一節的一般課(一位老師上),三角調課的候選格。""" + + entry_id: int + date: date + weekday: int + period_no: int + period_name: str + class_names: str + subject_name: str + in_block: bool + teacher_id: int + teacher_name: str + + +@dataclass(frozen=True, slots=True) +class TriangleOption: + """一組三角調課:乙來上請假那節;丙來上乙的 `mid`;甲回來上丙的 `makeup`。""" + + partner_id: int + partner_name: str + mid: Lesson + third_id: int + third_name: str + makeup: Lesson + + +@dataclass +class TriangleSearch: + affected_period_id: int + date_from: date + date_to: date + unavailable: str = "" # 非空 = 這一節不能三角調課的原因(跑班、協同教學…) + total: int = 0 # 一共幾組(清單只回前 MAX_TRIANGLES 組) + options: list[TriangleOption] = field(default_factory=list) + + +MAX_TRIANGLES = 200 + + +def triangle_unit(db: Session, affected: AffectedPeriod) -> tuple[int | None, str]: + """請假那節能不能三角調課:回 (排課單位 id, 不能的原因)。 + + 只限一個班、一位老師上的一般課——跑班、單雙週組、協同教學一節裡有好幾門課或好幾位老師, + 三個人輪流換,學生那一節到底上什麼會說不清楚。 + """ + a = (db.get(CourseAssignment, affected.course_assignment_id) + if affected.course_assignment_id else None) + if a is None: + return None, "找不到這一節的配課" + if a.scheduling_unit.unit_type != "single": + return None, "跑班或單雙週組的課不能三角調課,請用互調或代課" + if len(a.teachers) != 1: + return None, "協同教學的課不能三角調課,請用互調或代課" + return a.scheduling_unit_id, "" + + +def class_lessons( + db: Session, av: Availability, checker: SwapChecker, unit_id: int, dates: list[date], +) -> list[Lesson]: + """這個班在這段期間、請假老師以外的每一節一般課(還沒上過的)。""" + assert av.timetable is not None + affected = checker.affected + out: list[Lesson] = [] + entries = db.scalars( + select(ScheduleEntry) + .join(CourseAssignment, ScheduleEntry.course_assignment_id == CourseAssignment.id) + .where(ScheduleEntry.timetable_id == av.timetable.id, + CourseAssignment.scheduling_unit_id == unit_id) + ).all() + for entry in entries: + a = entry.assignment + if len(a.teachers) != 1: + continue + teacher = a.teachers[0].teacher + if teacher.id == checker.absent.id or not teacher.is_active: + continue + class_names = "、".join(m.class_unit.name for m in a.scheduling_unit.members) + for when in dates: + if when.isoweekday() != entry.weekday or not av.entry_runs_on(entry, when): + continue + for no in block_periods(av, entry): + if when == affected.date and no == affected.period_no: + continue + if checker.out_of_reach(entry, when, no): + continue + out.append(Lesson( + entry_id=entry.id, date=when, weekday=entry.weekday, period_no=no, + period_name=_period_label(av, entry, no), class_names=class_names, + subject_name=a.subject.name if a.subject else "", + in_block=entry.span > 1, teacher_id=teacher.id, teacher_name=teacher.name, + )) + return out + + +def triangle_search( + db: Session, + affected: AffectedPeriod, + *, + weeks: int = DEFAULT_WEEKS, + start: date | None = None, + availability: Availability | None = None, +) -> TriangleSearch: + """列出可行的三人組合:乙在甲那節有空、丙在乙那節有空、甲在丙那節有空。 + + 每一格的檢查與互調同一套(`SwapChecker`):停課、請假、已經拿去調課、自己有課、 + 已被安排代課都不行。依兩節裡較晚的那天排序(越早換完越好)。 + """ + av = availability or Availability(db, affected.semester_id) + date_from, date_to = search_window(affected.date, weeks, start) + result = TriangleSearch(affected_period_id=affected.id, date_from=date_from, date_to=date_to) + if av.timetable is None: + result.unavailable = "此學期尚無已發布的課表" + return result + unit_id, why = triangle_unit(db, affected) + if unit_id is None: + result.unavailable = why + return result + + checker = SwapChecker(db, affected, av) + dates = [date_from + timedelta(days=i) for i in range((date_to - date_from).days + 1)] + lessons = class_lessons(db, av, checker, unit_id, dates) + teachers = {t.id: t for t in db.scalars( + select(Teacher).where(Teacher.id.in_({x.teacher_id for x in lessons} or [0])))} + entries = {e.id: e for e in db.scalars( + select(ScheduleEntry).where(ScheduleEntry.id.in_({x.entry_id for x in lessons} or [0])))} + + partner_ok = {tid: checker.partner_blocker(t) is None for tid, t in teachers.items()} + # 甲能不能回來上這一節(丙的課) + makeups: dict[int, list[Lesson]] = {} + for x in lessons: + if checker.reason(teachers[x.teacher_id], entries[x.entry_id], x.date, + x.period_no) is None: + makeups.setdefault(x.teacher_id, []).append(x) + + found: list[TriangleOption] = [] + for mid in lessons: + if not partner_ok[mid.teacher_id]: + continue + owner, entry = teachers[mid.teacher_id], entries[mid.entry_id] + if checker.mid_base_reason(owner, entry, mid.date, mid.period_no) is not None: + continue + for third_id, options in makeups.items(): + if third_id == mid.teacher_id: + continue + third = teachers[third_id] + if checker.third_reason(third, entry, mid.date, mid.period_no) is not None: + continue + for z in options: + found.append(TriangleOption( + partner_id=owner.id, partner_name=owner.name, mid=mid, + third_id=third.id, third_name=third.name, makeup=z)) + + found.sort(key=lambda o: (max(o.mid.date, o.makeup.date), o.mid.date, o.mid.period_no, + o.makeup.date, o.makeup.period_no, o.partner_name, o.third_name)) + result.total = len(found) + result.options = found[:MAX_TRIANGLES] + return result diff --git a/backend/app/services/swap_relink.py b/backend/app/services/swap_relink.py index fdeb90fe..580bde65 100644 --- a/backend/app/services/swap_relink.py +++ b/backend/app/services/swap_relink.py @@ -15,6 +15,7 @@ 沒有這門課——不猜,留著原樣,由 `unlinked_count` 數出來提醒組長重新處理。 升級時的一次性修正見 alembic `0020_relink_swaps`(同一套規則,以 SQL 寫成)。 +三角調課(v1.4.20)另有中間那一節(`tri_entry_id`),同一套規則一起接。 """ from datetime import date @@ -51,18 +52,27 @@ def relink(db: Session, timetable: Timetable) -> int: for e in db.scalars(select(ScheduleEntry).where(ScheduleEntry.timetable_id == timetable.id)): index.setdefault((e.course_assignment_id, e.weekday), []).append(e) + def link(entry_id: int | None, on: date | None, period_no: int | None) -> int | None: + """接到新課表的格子 id;不必接或接不上回 None。""" + old = db.get(ScheduleEntry, entry_id) if entry_id else None + if old is None or old.timetable_id == timetable.id or on is None: + return None + no = period_no if period_no is not None else old.period_no + new = _find(index.get((old.course_assignment_id, on.isoweekday()), []), no) + return new.id if new is not None else None + moved = 0 for sub in _swaps(db, timetable.semester_id): - old = db.get(ScheduleEntry, sub.swap_entry_id) if sub.swap_entry_id else None - if old is None or old.timetable_id == timetable.id or sub.swap_date is None: - continue - period_no = sub.swap_period_no if sub.swap_period_no is not None else old.period_no - new = _find(index.get((old.course_assignment_id, sub.swap_date.isoweekday()), []), - period_no) - if new is not None: - sub.swap_entry_id = new.id - sub.swap_period_no = period_no + new_id = link(sub.swap_entry_id, sub.swap_date, sub.swap_period_no) + if new_id is not None: + if sub.swap_period_no is None: + old = db.get(ScheduleEntry, sub.swap_entry_id) + sub.swap_period_no = old.period_no if old else None + sub.swap_entry_id = new_id moved += 1 + tri_id = link(sub.tri_entry_id, sub.tri_date, sub.tri_period_no) + if tri_id is not None: + sub.tri_entry_id = tri_id db.flush() return moved @@ -71,7 +81,8 @@ def unlinked_count(db: Session, timetable: Timetable, today: date | None = None) """今天以後、仍有效的調課裡,補課那一節不在這份課表上的筆數(發布後提醒組長)。""" today = today or clock.school_today() rows = db.execute( - select(Substitution.swap_entry_id) + select(Substitution.swap_entry_id, Substitution.tri_entry_id, + Substitution.tri_teacher_id) .join(AffectedPeriod, Substitution.affected_period_id == AffectedPeriod.id) .join(LeaveRequest, AffectedPeriod.leave_request_id == LeaveRequest.id) .where( @@ -82,12 +93,13 @@ def unlinked_count(db: Session, timetable: Timetable, today: date | None = None) AffectedPeriod.status != AffectedStatus.cancelled.value, ) ).all() - ids = [r for (r,) in rows] - if not ids: + if not rows: return 0 + ids = {i for r in rows for i in (r[0], r[1]) if i is not None} on_this = set(db.scalars( select(ScheduleEntry.id).where( - ScheduleEntry.timetable_id == timetable.id, - ScheduleEntry.id.in_([i for i in ids if i is not None] or [0])) + ScheduleEntry.timetable_id == timetable.id, ScheduleEntry.id.in_(ids or [0])) )) - return sum(1 for i in ids if i not in on_this) + # 三角調課兩格都要在新課表上才算接好;算一筆 + return sum(1 for swap_id, tri_id, tri_teacher in rows + if swap_id not in on_this or (tri_teacher is not None and tri_id not in on_this)) diff --git a/backend/app/services/swap_slips.py b/backend/app/services/swap_slips.py index 6555b497..6cf8bf85 100644 --- a/backend/app/services/swap_slips.py +++ b/backend/app/services/swap_slips.py @@ -6,6 +6,8 @@ 格線與跨週分頁等共用部分見 `slip_layout`。 **一筆調課 = 兩個異動格。** 甲請假那節改由乙上;乙原本那節改由甲上。 +三角調課(v1.4.20)是三格:甲那節由乙上、乙那節由丙上、丙那節由甲上; +記號指向「來上的老師自己空出來的那一節」。 - 教師調課單:每位老師一張,只列他「要去上」的那一格(空出來的那一格不列—— 他那節不用去,紙本上也沒有)。 @@ -25,6 +27,7 @@ from app.models.leave import AffectedPeriod, AffectedStatus, LeaveRequest, LeaveStatus from app.models.substitution import Substitution, SubstitutionType from app.models.timetable import ScheduleEntry +from app.services import swap_legs from app.services.slip_layout import Move, SlipError, Slips, Tables, assemble, school_title @@ -34,31 +37,32 @@ def _md(d: date) -> str: def _moves(db: Session, tables: Tables, ap: AffectedPeriod, sub: Substitution) -> list[Move]: - absent = ap.leave_request.teacher - partner = sub.handler - if partner is None or sub.swap_date is None or sub.swap_period_no is None: + """這筆調課換人上的每一格(互調兩格、三角調課三格,見 `swap_legs`)。""" + legs = swap_legs.legs(ap, sub) + if (sub.handler is None or len(legs) < 2 + or (sub.is_triangle and (sub.tri_teacher is None or len(legs) < 3))): raise SlipError("這筆調課資料不完整(對調教師或補課節次已被刪除),無法列印") - same_class = ap.class_names == sub.swap_class_names - leave_table = tables.of_assignment(ap.course_assignment_id) - entry = db.get(ScheduleEntry, sub.swap_entry_id) if sub.swap_entry_id else None - swap_table = tables.of_assignment(entry.course_assignment_id) if entry else leave_table - swap_wd, leave_wd = sub.swap_date.isoweekday(), ap.date.isoweekday() - swap_ord = tables.ordinal(swap_table, swap_wd, sub.swap_period_no) - leave_ord = tables.ordinal(leave_table, leave_wd, ap.period_no) - return [ - Move( # 請假那節:改由乙上 - date=ap.date, period_no=ap.period_no, class_names=ap.class_names, - subject_name=sub.swap_subject_name if same_class else ap.subject_name, - teacher_id=partner.id, teacher_name=partner.name, table_id=leave_table, - code=f"調{_md(sub.swap_date)}_{swap_wd}{swap_ord}", - ), - Move( # 乙原本那節:改由甲上 - date=sub.swap_date, period_no=sub.swap_period_no, class_names=sub.swap_class_names, - subject_name=ap.subject_name if same_class else sub.swap_subject_name, - teacher_id=absent.id, teacher_name=absent.name, table_id=swap_table, - code=f"調{_md(ap.date)}_{leave_wd}{leave_ord}", - ), - ] + + def table(leg_entry: int | None, assignment: int | None) -> int | None: + if assignment is None and leg_entry is not None: + entry = db.get(ScheduleEntry, leg_entry) + assignment = entry.course_assignment_id if entry else ap.course_assignment_id + return tables.of_assignment(assignment or ap.course_assignment_id) + + out: list[Move] = [] + for leg in legs: + assert leg.teacher_id is not None and leg.back_date is not None + assert leg.back_period_no is not None + back_wd = leg.back_date.isoweekday() + back_ord = tables.ordinal(table(leg.back_entry_id, leg.back_assignment_id), + back_wd, leg.back_period_no) + out.append(Move( + date=leg.date, period_no=leg.period_no, class_names=leg.class_names, + subject_name=leg.subject_taught, teacher_id=leg.teacher_id, + teacher_name=leg.teacher_name, table_id=table(leg.entry_id, leg.assignment_id), + code=f"調{_md(leg.back_date)}_{back_wd}{back_ord}", + )) + return out def build(db: Session, semester_id: int, affected_ids: list[int]) -> Slips: diff --git a/backend/app/services/teacher_week_sheets.py b/backend/app/services/teacher_week_sheets.py index 57cd1e8f..3b62323d 100644 --- a/backend/app/services/teacher_week_sheets.py +++ b/backend/app/services/teacher_week_sheets.py @@ -29,6 +29,7 @@ from app.models.substitution import Substitution, SubstitutionType from app.models.timetable import ScheduleEntry from app.services import suspensions as suspension_service +from app.services import swap_legs from app.services.availability import published_timetable from app.services.patrol_sheets import Day, classes_by_period_table from app.services.slip_layout import Tables, school_title @@ -218,18 +219,14 @@ def put(teacher_id: int | None, ordinal: int, item: Item) -> None: if sub is not None and sub.handler is not None: put(sub.handler_teacher_id, ordinal, _taken_over(b, ap, sub)) elif (e.id, p) in day.makeup: - ap, sub = day.makeup[(e.id, p)] - partner_id = sub.handler_teacher_id - absent = ap.leave_request.teacher + # 調課換人上的這一格:原本的老師劃掉寫「調給某師」,來上的老師紅字 + ap, sub, leg = day.makeup[(e.id, p)] for t in teacher_ids: - if t != partner_id: + if t != leg.owner_id: put(t, ordinal, Item(label)) - put(partner_id, ordinal, Item(label, OFF, f"調給{absent.name if absent else ''}")) - same_class = ap.class_names == sub.swap_class_names - subject = ap.subject_name if same_class else sub.swap_subject_name - put(ap.leave_request.teacher_id, ordinal, Item( - _snap(sub.swap_class_names, subject), SWAP, - b.swap_code(ap.date, ap.course_assignment_id, ap.period_no))) + put(leg.owner_id, ordinal, Item(label, OFF, f"調給{leg.teacher_name}")) + put(leg.teacher_id, ordinal, Item( + _snap(leg.class_names, leg.subject_taught), SWAP, _back_code(b, leg))) else: for t in teacher_ids: put(t, ordinal, Item(label)) @@ -241,15 +238,20 @@ def _taken_over(b: Builder, ap: AffectedPeriod, sub: Substitution) -> Item: absent = ap.leave_request.teacher absent_name = absent.name if absent else "" if sub.type == SubstitutionType.swap.value and sub.swap_date and sub.swap_period_no: - same_class = ap.class_names == sub.swap_class_names - subject = sub.swap_subject_name if same_class else ap.subject_name - code = b.swap_code(sub.swap_date, b.entry_assignment(sub.swap_entry_id), - sub.swap_period_no) - return Item(_snap(ap.class_names, subject), SWAP, code) + leg = swap_legs.legs(ap, sub)[0] + return Item(_snap(ap.class_names, leg.subject_taught), SWAP, _back_code(b, leg)) verb = "併" if sub.type == SubstitutionType.merge.value else "代" return Item(_snap(ap.class_names, ap.subject_name), COVER, f"{verb}{absent_name}") +def _back_code(b: Builder, leg: swap_legs.Leg) -> str: + """來上這一格的老師,自己空出來的那一節:「調11/20_53」。""" + if leg.back_date is None or leg.back_period_no is None: + return "" + assignment = leg.back_assignment_id or b.entry_assignment(leg.back_entry_id) + return b.swap_code(leg.back_date, assignment, leg.back_period_no) + + def _row_names(b: Builder, tables: list[int], weekday: int) -> list[str]: """這一天的節次名稱。`tables` 第一個是班級最多的那套節次表,名稱以它為準; 別套節次表節數較多時(例如國中部有第八節),多出來的列補上「第八節」。""" diff --git a/backend/app/services/timetable_week.py b/backend/app/services/timetable_week.py index 75776f89..39213326 100644 --- a/backend/app/services/timetable_week.py +++ b/backend/app/services/timetable_week.py @@ -27,7 +27,7 @@ # 班級課表的異動種類:巡堂表的備註 → 格子樣式(與教師週總表同一套顏色) _KIND = { - "代課": tw.COVER, "併班": tw.COVER, "調課": tw.SWAP, + "代課": tw.COVER, "併班": tw.COVER, "調課": tw.SWAP, "三角調課": tw.SWAP, "自習": tw.OFF, "停課": tw.OFF, "請假待處理": tw.PENDING, } @@ -69,7 +69,7 @@ def _note(x: _Lesson) -> str: 補課排在隔天,只看到一格變色,以為只有一個人被調)。""" extra = [f"原:{x.original}"] if x.original and x.teacher != x.original else [] if x.swap_with: - extra.append(f"與 {x.swap_with}對調") + extra.append(x.swap_with) if x.reason: extra.append(x.reason) # 停課的說明「校慶補假」(v1.4.19) return f"{x.note}({','.join(extra)})" if extra else x.note diff --git a/backend/tests/test_triangle_swap_v1420.py b/backend/tests/test_triangle_swap_v1420.py new file mode 100644 index 00000000..b7509db5 --- /dev/null +++ b/backend/tests/test_triangle_swap_v1420.py @@ -0,0 +1,283 @@ +"""三角調課(v1.4.20,組長拿別家系統的畫面來問:「會出三角調課嗎?」)。 + +同一班三位老師輪流換課:王師週三第一節請假,林師來上;林師週四第二節由陳師上; +陳師週五第三節由王師回來上。兩人互調湊不出來(王師週四第二節有別班的課、 +陳師週三第一節有別班的課)時,只有三個人一起換才換得成。 + +規則(使用者 2026-11-17 同意):只限同一個班、請假老師發起、範圍與互調相同、 +鐘點不計、三位老師各一張調課單(只列自己要去上的那格)與班級一張、撤回三格一起撤、 +三角調的節次不能再調。 +""" + +from datetime import timedelta + +from app.models.substitution import Substitution +from app.services.availability import Availability, Interval +from tests.dates import WED +from tests.test_substitutions import _notif_titles, _options, _slips +from tests.test_teacher_week_sheets import _cell, _sheets +from tests.test_timetable_week import _at, _week, w # noqa: F401 - w 為 fixture + +THU = WED + timedelta(days=1) +FRI = WED + timedelta(days=2) + + +def _md(d): + return f"{d.month}/{d.day}" + + +def _world(world): + """701:王師週三第一節國文、林師週四第二節數學、陳師週五第三節英語。""" + world.teacher("王師", ["國文"]) + world.teacher("林師", ["數學"]) + world.teacher("陳師", ["英語"]) + world.place("王師", "國文", "701", 0, weekday=3) + world.place("林師", "數學", "701", 1, weekday=4) + world.place("陳師", "英語", "701", 2, weekday=5) + world.place("王師", "國文", "702", 1, weekday=4) # 王師週四第二節有 702 的課:不能和林師互調 + world.place("陳師", "英語", "703", 0, weekday=3) # 陳師週三第一節有 703 的課:不能來代 + world.publish() + return world.leave("王師")[0]["id"] + + +def _triangles(world, aid, **q): + qs = "&".join(f"{k}={v}" for k, v in q.items()) + r = world.client.get(f"/api/affected-periods/{aid}/triangle-options?{qs}") + assert r.status_code == 200, r.json() + return r.json() + + +def _assign(world, aid, opt): + return world.assign( + aid, type="swap", handler_teacher_id=opt["partner_id"], + tri_teacher_id=opt["third_id"], tri_entry_id=opt["mid"]["entry_id"], + tri_date=opt["mid"]["date"], tri_period_no=opt["mid"]["period_no"], + swap_entry_id=opt["makeup"]["entry_id"], swap_date=opt["makeup"]["date"], + swap_period_no=opt["makeup"]["period_no"]) + + +def _first(world, aid): + opt = _triangles(world, aid)["options"][0] + code, body = _assign(world, aid, opt) + assert code == 200, body + return body + + +def test_two_way_swaps_fail_but_the_rotation_is_listed(w): # noqa: F811 + aid = _world(w) + partners = {p["teacher_name"]: p for p in _options(w, aid)["partners"]} + assert partners["林師"]["options"] == [] # 王師週四第二節自己有課 + assert partners["陳師"]["blocked_reason"] # 陳師週三第一節自己有課 + + body = _triangles(w, aid) + assert body["unavailable"] == "" + got = [(o["partner_name"], o["mid"]["date"], o["mid"]["subject_name"], o["third_name"], + o["makeup"]["date"], o["makeup"]["subject_name"]) for o in body["options"]] + nxt = timedelta(days=7) + # 範圍與互調相同(預設兩週);兩節都早的排前面 + assert got[0] == ("林師", THU.isoformat(), "數學", "陳師", FRI.isoformat(), "英語") + assert body["total"] == 4 and set(got) == { + ("林師", THU.isoformat(), "數學", "陳師", FRI.isoformat(), "英語"), + ("林師", THU.isoformat(), "數學", "陳師", (FRI + nxt).isoformat(), "英語"), + ("林師", (THU + nxt).isoformat(), "數學", "陳師", FRI.isoformat(), "英語"), + ("林師", (THU + nxt).isoformat(), "數學", "陳師", (FRI + nxt).isoformat(), "英語"), + } + + +def test_rotation_is_recorded_and_all_three_are_notified(w): # noqa: F811 + aid = _world(w) + body = _first(w, aid) + assert (body["handler_name"], body["tri_teacher_name"]) == ("林師", "陳師") + assert (body["tri_date"], body["tri_subject_name"]) == (THU.isoformat(), "數學") + assert (body["swap_date"], body["swap_subject_name"]) == (FRI.isoformat(), "英語") + assert body["counts_toward_hours"] is False # 鐘點都不計 + + assert any(t.startswith("三角調課通知") for t in _notif_titles(w, "林師")) + assert any(t.startswith("三角調課通知") for t in _notif_titles(w, "陳師")) + assert any(t.startswith("三角調課補課通知") for t in _notif_titles(w, "王師")) + + listed = w.client.get(f"/api/leaves{w.q}").json()[0]["affected_periods"][0] + assert (listed["tri_teacher_name"], listed["tri_date"]) == ("陳師", THU.isoformat()) + + # 陳師週四第二節已經有安排:找人代別的課時他不是空的 + w.db.expire_all() + av = Availability(w.db, w.sid) + slot = Interval(4, w.wed[1]["period_no"], None, None) + assert av.conflict_for(w.teachers["陳師"], THU, slot) is not None + + +def test_week_views_and_master_sheet_show_three_cells(w): # noqa: F811 + aid = _world(w) + _first(w, aid) + cls = _week(w, "class", w.classes["701"]).json() + assert _at(cls, WED, 1) == [("數學", "林師", "swap", + f"三角調課(原:王師,另兩節 {_md(THU)} 第二節、{_md(FRI)} 第三節)")] + assert _at(cls, THU, 2)[0][:3] == ("英語", "陳師", "swap") + assert _at(cls, FRI, 3)[0][:3] == ("國文", "王師", "swap") + chen = _week(w, "teacher", w.teachers["陳師"]).json() + assert _at(chen, THU, 2)[0][2] == "swap" # 老師本人的週課表看得到要去上的那一節 + + sheet = _sheets(w).json() + assert _cell(sheet, "林師", WED, 1) == [("701 數學", "swap", f"調{_md(THU)}_42")] + assert _cell(sheet, "林師", THU, 2) == [("701 數學", "off", "調給陳師")] + assert _cell(sheet, "陳師", THU, 2) == [("701 英語", "swap", f"調{_md(FRI)}_53")] + assert _cell(sheet, "陳師", FRI, 3) == [("701 英語", "off", "調給王師")] + assert _cell(sheet, "王師", FRI, 3) == [("701 國文", "swap", f"調{_md(WED)}_31")] + + patrol = w.client.get(f"/api/patrol-sheets{w.q}&date_from={THU.isoformat()}").json() + page = next(p for p in patrol["pages"] if "701" in p["classes"]) + cell = page["rows"][1]["cells"][page["classes"].index("701")] + assert (cell["subject"], cell["teacher"], cell["note"]) == ("英語", "陳師", "三角調課") + + +def test_slips_one_per_teacher_and_one_for_the_class(w): # noqa: F811 + aid = _world(w) + _first(w, aid) + body = _slips(w, aid).json() + kinds = [(s["kind"], s["teacher_name"]) for s in body["slips"]] + assert kinds == [("teacher", "林師"), ("teacher", "陳師"), ("teacher", "王師"), + ("class", "")] + + def cells(slip): + return [(c["date"], c["ordinal"], c["subject_name"], c["actor"], c["code"]) + for week in slip["weeks"] for c in week["cells"]] + + lin, chen, wang, klass = body["slips"] + assert cells(lin) == [(WED.isoformat(), 1, "數學", "林師", f"調{_md(THU)}_42")] + assert cells(chen) == [(THU.isoformat(), 2, "英語", "陳師", f"調{_md(FRI)}_53")] + assert cells(wang) == [(FRI.isoformat(), 3, "國文", "王師", f"調{_md(WED)}_31")] + assert len(cells(klass)) == 3 + + +def test_board_and_log_list_every_cell(w): # noqa: F811 + aid = _world(w) + _first(w, aid) + wed = w.client.get(f"/api/daily-board{w.q}&on={WED.isoformat()}").json()["entries"] + assert [(e["row_kind"], e["handler_name"], e["is_triangle"], e["tri_teacher_name"]) + for e in wed] == [("leave", "林師", True, "陳師")] + thu = w.client.get(f"/api/daily-board{w.q}&on={THU.isoformat()}").json()["entries"] + assert [(e["row_kind"], e["absent_teacher_name"], e["handler_name"], e["swap_date"], + e["leave_type_label"]) for e in thu] == [ + ("swap_makeup", "林師", "陳師", FRI.isoformat(), "三角調課")] + fri = w.client.get(f"/api/daily-board{w.q}&on={FRI.isoformat()}").json()["entries"] + assert [(e["absent_teacher_name"], e["handler_name"], e["swap_date"]) for e in fri] == [ + ("陳師", "王師", WED.isoformat())] + + # 查陳師的紀錄也查得到(他換了課) + log = w.client.get(f"/api/substitution-log{w.q}&teacher_id={w.teachers['陳師']}").json() + assert [e["absent_teacher_name"] for e in log] == ["王師"] + + +def test_withdrawing_undoes_all_three_cells(w): # noqa: F811 + aid = _world(w) + _first(w, aid) + assert w.client.delete(f"/api/affected-periods/{aid}/substitution").status_code == 200 + assert "原訂三角調課已取消" in _notif_titles(w, "陳師") + assert "原訂調課已取消" in _notif_titles(w, "林師") + assert "原訂調課已取消" in _notif_titles(w, "王師") + cls = _week(w, "class", w.classes["701"]).json() + assert _at(cls, THU, 2) == [("數學", "林師", "normal", "")] + assert _at(cls, FRI, 3) == [("英語", "陳師", "normal", "")] + + +def test_cancelling_the_leave_tells_the_third_teacher(w): # noqa: F811 + aid = _world(w) + _first(w, aid) + leave = w.client.get(f"/api/leaves{w.q}").json()[0] + assert w.client.post(f"/api/leaves/{leave['id']}/cancel").status_code == 200 + assert any(t.startswith("原訂三角調課已取消") for t in _notif_titles(w, "陳師")) + assert _at(_week(w, "class", w.classes["701"]).json(), THU, 2)[0][2] == "normal" + + +def test_rotated_periods_cannot_be_swapped_again(w): # noqa: F811 + """三角調的節次不能再調:黃師週三第二節請假,林師週四第二節、陳師週五第三節都不能再拿來換。""" + aid = _world(w) + _first(w, aid) + w.teacher("黃師", ["自然"]) + new = w.client.post(f"/api/timetables/{w.tt}/duplicate", json={"name": "草稿B"}).json() + w.tt = new["id"] + w.place("黃師", "自然", "701", 1, weekday=3) + w.publish() + other = w.leave("黃師")[0]["id"] + for who, day in (("林師", THU), ("陳師", FRI)): + p = _options(w, other, who)["partners"][0] + blocked = [o for o in p["blocked"] if o["date"] == day.isoformat()] + assert blocked and "已經和別的老師調課了" in blocked[0]["blocked_reason"], (who, p) + tri = _triangles(w, other) + assert all((o["mid"]["date"], o["mid"]["teacher_name"]) != (THU.isoformat(), "林師") + for o in tri["options"]) + + +def test_invalid_rotations_are_explained(w): # noqa: F811 + aid = _world(w) + opt = _triangles(w, aid)["options"][0] + + def bad(**over): + body = dict(opt) + merged = {**body, **over} + code, out = _assign(w, aid, merged) + assert code == 409, out + return out["detail"] + + assert "三位不同" in bad(third_id=w.teachers["林師"]) + assert "不是 陳師" in bad(makeup={**opt["makeup"], "entry_id": opt["mid"]["entry_id"], + "date": opt["mid"]["date"]}) + # 陳師週四第二節另有安排(臨時排了 703 的課)→ 不能來上林師那節 + new = w.client.post(f"/api/timetables/{w.tt}/duplicate", json={"name": "草稿B"}).json() + w.tt = new["id"] + w.place("陳師", "英語", "703", 1, weekday=4) + w.publish() + opt2 = {**opt, "mid": {**opt["mid"], "entry_id": _entry(w, "林師", 4)}, + "makeup": {**opt["makeup"], "entry_id": _entry(w, "陳師", 5)}} + code, out = _assign(w, aid, opt2) + assert code == 409 and "陳師這節自己有課" in out["detail"], out + assert w.db.query(Substitution).count() == 0 + + +def _entry(world, teacher, weekday): + tt = world.client.get(f"/api/timetables/{world.tt}").json() + a_ids = {a["id"] for a in world.client.get(f"/api/assignments{world.q}").json() + if any(t["teacher_id"] == world.teachers[teacher] for t in a["teachers"]) + and a["scheduling_unit"]["name"] == "701"} + return next(e["id"] for e in tt["entries"] + if e["course_assignment_id"] in a_ids and e["weekday"] == weekday) + + +def test_group_lessons_are_not_offered(w): # noqa: F811 + """跑班、協同教學的課不能三角調課(那一節不只一門課或一位老師)。""" + w.teacher("王師", ["國文"]) + w.teacher("林師", ["國文"]) + a = w.client.post(f"/api/assignments{w.q}", json={ + "class_id": w.klass("701"), "subject_id": w.subject("國文"), "periods_per_week": 1, + "teachers": [{"teacher_id": w.teachers["王師"], "is_lead": True}, + {"teacher_id": w.teachers["林師"], "is_lead": False}], + "block_rules": []}).json() + r = w.client.post(f"/api/timetables/{w.tt}/entries", json={ + "course_assignment_id": a["id"], "weekday": 3, "period_no": w.wed[0]["period_no"], + "span": 1}) + assert r.status_code == 201, r.json() + w.publish() + aid = w.leave("王師")[0]["id"] + assert "協同教學" in _triangles(w, aid)["unavailable"] + + +def test_republish_keeps_both_rotated_cells(w): # noqa: F811 + aid = _world(w) + _first(w, aid) + new = w.client.post(f"/api/timetables/{w.tt}/duplicate", json={"name": "草稿B"}).json() + r = w.client.post(f"/api/timetables/{new['id']}/publish?force=true") + assert r.status_code == 200 and r.json()["swap_unlinked"] == 0, r.json() + w.tt = new["id"] + cls = _week(w, "class", w.classes["701"]).json() + assert _at(cls, THU, 2)[0][:3] == ("英語", "陳師", "swap") + assert _at(cls, FRI, 3)[0][:3] == ("國文", "王師", "swap") + + +def test_suspension_lists_the_third_teacher(w): # noqa: F811 + aid = _world(w) + _first(w, aid) + r = w.client.post(f"/api/suspensions{w.q}", json={ + "start_date": THU.isoformat(), "end_date": THU.isoformat(), "whole_school": False, + "class_ids": [w.classes["701"]], "all_day": True, "reason": "戶外教學"}) + assert r.status_code == 201, r.json() + assert r.json()["conflicts"] == [f"{_md(THU)} 第二節 701:陳師 三角調課來上課"] diff --git a/docs/architecture.html b/docs/architecture.html index 10cd3544..51ced74a 100644 --- a/docs/architecture.html +++ b/docs/architecture.html @@ -768,7 +768,7 @@

2.2 核心實體定義

substitution 調代課處置 - 類型:substitute(代課)/swap(調課)/merge(併班)/self_study(自習)/cancel(不處理);代課教師、是否計鐘點、經費來源標記。調課另記補課那一節:swap_date、swap_period_no、swap_entry_id(已發布課表的格子)。格子屬於某一份課表,學期中重新發布時新課表每一格都是新的一列,所以發布時要把這學期的調課接到新課表「同一配課、同一星期、涵蓋該節」的格子(services/swap_relink.py,v1.4.18);接不上(那堂課被搬走)的維持原樣,發布回傳 swap_unlinked 提醒組長重排。週課表、巡堂表、調課清單都以 swap_entry_id 比對已發布課表,沒接上就畫不出補課那一節、也可能重複調課。遷移 0020 只改資料:把升級前已發生的接回目前已發布的課表 + 類型:substitute(代課)/swap(調課)/merge(併班)/self_study(自習)/cancel(不處理);代課教師、是否計鐘點、經費來源標記。調課另記補課那一節:swap_date、swap_period_no、swap_entry_id(已發布課表的格子)。格子屬於某一份課表,學期中重新發布時新課表每一格都是新的一列,所以發布時要把這學期的調課接到新課表「同一配課、同一星期、涵蓋該節」的格子(services/swap_relink.py,v1.4.18);接不上(那堂課被搬走)的維持原樣,發布回傳 swap_unlinked 提醒組長重排。週課表、巡堂表、調課清單都以 swap_entry_id 比對已發布課表,沒接上就畫不出補課那一節、也可能重複調課。遷移 0020 只改資料:把升級前已發生的接回目前已發布的課表。三角調課(v1.4.20,遷移 0022):tri_teacher_id(丙)與 tri_date/tri_period_no/tri_entry_id(乙原本那一節,改由丙上);swap_* 仍是「請假的老師回來上的那一節」,此時是丙的課。三格記在同一筆,撤回一起撤。各處要逐格處理一律用 services/swap_legs.py(原本是誰、誰來上、上什麼、自己空出哪一節),不要自己拼 swap_*/tri_*;可行組合的搜尋與檢查在 swap_options.triangle_search,與送出時的 substitutions._validate_triangle 共用 SwapChecker class_suspension diff --git a/docs/architecture.md b/docs/architecture.md index 458299d8..e7a0e3f6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -196,7 +196,7 @@ erDiagram | `leave_request` | 請假 | 教師、假別(公/事/病/婚/喪/產/進修)、起訖日期時間、事由、登記人 | | `affected_period` | 受影響節次 | 請假展開後的每一節課;狀態機見 §5.3 | | `homeroom_cover` | **代導**(v1.4.0,遷移 0019) | 導師請假時,依「他帶的班 × 請假期間的上課日」各一列(`uq(leave_request_id, class_name, date)`),**與課表無關**——當天沒課也要有人帶班。快照:班名、年級;該日請假時段 `from_time`/`to_time`(兩端皆空 = 全天,否則為半天,顯示為上午/下午);狀態沿用 `affected_period` 的待處理/已確認/已取消(已完成為讀取時推導:那天過完);`no_cover`(不需代導)、代導教師 `handler_teacher_id`。人選不檢查課務(有課也能代導),只排除當天整天請假者。月結只記全天/半天天數,不計算代導費 | -| `substitution` | 調代課處置 | 類型:`substitute`(代課)/`swap`(調課)/`merge`(併班)/`self_study`(自習)/`cancel`(不處理);代課教師、是否計鐘點、經費來源標記。調課另記補課那一節:`swap_date`、`swap_period_no`、`swap_entry_id`(**已發布課表的格子**)。格子屬於某一份課表,學期中重新發布時新課表每一格都是新的一列,所以**發布時要把這學期的調課接到新課表**「同一配課、同一星期、涵蓋該節」的格子(`services/swap_relink.py`,v1.4.18);接不上(那堂課被搬走)的維持原樣,發布回傳 `swap_unlinked` 提醒組長重排。週課表、巡堂表、調課清單都以 `swap_entry_id` 比對已發布課表,沒接上就畫不出補課那一節、也可能重複調課。遷移 0020 只改資料:把升級前已發生的接回目前已發布的課表 | +| `substitution` | 調代課處置 | 類型:`substitute`(代課)/`swap`(調課)/`merge`(併班)/`self_study`(自習)/`cancel`(不處理);代課教師、是否計鐘點、經費來源標記。調課另記補課那一節:`swap_date`、`swap_period_no`、`swap_entry_id`(**已發布課表的格子**)。格子屬於某一份課表,學期中重新發布時新課表每一格都是新的一列,所以**發布時要把這學期的調課接到新課表**「同一配課、同一星期、涵蓋該節」的格子(`services/swap_relink.py`,v1.4.18);接不上(那堂課被搬走)的維持原樣,發布回傳 `swap_unlinked` 提醒組長重排。週課表、巡堂表、調課清單都以 `swap_entry_id` 比對已發布課表,沒接上就畫不出補課那一節、也可能重複調課。遷移 0020 只改資料:把升級前已發生的接回目前已發布的課表。**三角調課**(v1.4.20,遷移 0022):`tri_teacher_id`(丙)與 `tri_date`/`tri_period_no`/`tri_entry_id`(乙原本那一節,改由丙上);`swap_*` 仍是「請假的老師回來上的那一節」,此時是丙的課。三格記在同一筆,撤回一起撤。各處要逐格處理一律用 `services/swap_legs.py`(原本是誰、誰來上、上什麼、自己空出哪一節),不要自己拼 `swap_*`/`tri_*`;可行組合的搜尋與檢查在 `swap_options.triangle_search`,與送出時的 `substitutions._validate_triangle` 共用 `SwapChecker` | | `class_suspension` | **停課日**(v1.4.19,遷移 0021) | 起訖日期、對象(`whole_school`,或經 `class_suspension_classes` 指定班級;畫面上勾年級 = 勾整個年級的班)、範圍(`from_ordinal`~`to_ordinal`:第幾節,只數一般課,依各班自己的節次表換算;兩個都空 = 整天)、說明。判斷集中在 `services/suspensions.py`:**一門課的每一個班都停課才算停課**(合班、跑班還有一班要上,老師就要去)。效果:請假展開時不列受影響節次(回傳 `skipped`「停課(…)」)、整天停課的班不產生代導、調課清單不能拿停課的那一節補課;`patrol_sheets.Day` 把停課的課標「停課」並**優先於當天的調代課**,全校整天停課的日子巡堂表與教師週總表略過。停課是事後設的,之前已安排的調代課**不自動改**(可能已通知老師),儲存時回傳 `conflicts` 讓組長自行撤回或改成「不處理」 | | `notification` | 通知 | 站內+Email(v2 經 channel adapter 加 LINE/webhook);類型、收件人、已讀狀態 | | `user` / `user_role` | 帳號與角色 | 本地帳密(bcrypt);角色:admin / director(教務主任)/ scheduler(教學組長)/ teacher | diff --git a/docs/deploy/upgrade.html b/docs/deploy/upgrade.html index 201673e2..86b98f4b 100644 --- a/docs/deploy/upgrade.html +++ b/docs/deploy/upgrade.html @@ -172,7 +172,7 @@ 路線圖開發用 開發任務卡開發用 -
本頁目錄
+
本頁目錄
@@ -190,6 +190,10 @@

升級指南

開始前先備份。 升級本身不會刪資料,但任何重大操作前留一份備份是好習慣。到「系統管理 → 資料備份與還原 → 立即備份」,或見備份指南。

+

升級到 v1.4.20:調代課處置的資料表新增三角調課欄位

+

v1.4.20 在「調代課處置」的資料表新增幾個欄位(三角調課的第三位老師與中間那一節,都可以是空的), + 既有的資料都不動——升級前的調課都是兩人互調,這些欄位留空。和 v1.4.19 一樣,api 容器發現資料庫結構 + 需要升級時,會先自動備份一次再升級,照下方方式 A 或方式 B 一般升級即可。

升級到 v1.4.19:新增停課日用的資料表

v1.4.19 新增「停課日」用的兩張資料表,既有的資料表與資料都不動。和 v1.4.0 一樣,api 容器發現資料庫結構 需要升級時,會先自動備份一次再升級,照下方方式 A 或方式 B 一般升級即可。升級前已登記的請假不會因此改變; @@ -261,6 +265,17 @@

退回舊版(升級後發現問題)

⚠️ 注意資料庫遷移方向:若新版本引入了資料表結構變更,退回舊映像後其程式可能不認得新結構。最保險的退回方式是:退回舊映像 + 還原「升級前那份備份」(見備份指南的還原流程)。若該次升級的 CHANGELOG 未標註 schema 變更,則單純換映像即可。

+

從 v1.4.20 退回 v1.4.19

+

v1.4.20 改了資料表結構,直接把版本號改回 v1.4.19,舊版會啟動失敗。兩種退回方式擇一:

+
    +
  • 方式一:用升級前自動備份還原——做法同下方「從 v1.3.0 退回 v1.2.x」的方式一。升級後才登記的請假、調代課不會保留。
  • +
  • 方式二:退回指令(資料保留,只移除三角調課的欄位)——在 docker-compose.yml 所在資料夾,先以 v1.4.20 執行:
  • +
+

bash + docker compose run --rm --entrypoint alembic api downgrade 0021_class_suspensions

+

這會移除三角調課用的欄位。執行前請先到「調代課處理」撤回已經成立的三角調課——舊版看不懂 + 三角調課,會把它當成兩人互調而顯示錯誤。課表、請假、代課等其他資料都不動。 + 接著把 .env 的 IMAGE_TAG 改回 v1.4.19,執行 docker compose pull 與 docker compose up -d。

從 v1.4.19 退回 v1.4.18

v1.4.19 新增了停課日的資料表,直接把版本號改回 v1.4.18,舊版會啟動失敗。兩種退回方式擇一:

    diff --git a/docs/deploy/upgrade.md b/docs/deploy/upgrade.md index 102b7697..4a0b5e99 100644 --- a/docs/deploy/upgrade.md +++ b/docs/deploy/upgrade.md @@ -8,6 +8,12 @@ > **開始前先備份。** 升級本身不會刪資料,但任何重大操作前留一份備份是好習慣。到「系統管理 → 資料備份與還原 → 立即備份」,或見[備份指南](backup.md)。 +## 升級到 v1.4.20:調代課處置的資料表新增三角調課欄位 + +v1.4.20 在「調代課處置」的資料表新增幾個欄位(三角調課的第三位老師與中間那一節,都可以是空的), +**既有的資料都不動**——升級前的調課都是兩人互調,這些欄位留空。和 v1.4.19 一樣,`api` 容器發現資料庫結構 +需要升級時,**會先自動備份一次再升級**,照下方方式 A 或方式 B 一般升級即可。 + ## 升級到 v1.4.19:新增停課日用的資料表 v1.4.19 新增「停課日」用的兩張資料表,**既有的資料表與資料都不動**。和 v1.4.0 一樣,`api` 容器發現資料庫結構 @@ -112,6 +118,21 @@ docker compose up -d > ⚠️ **注意資料庫遷移方向**:若新版本引入了資料表結構變更,退回舊映像後其程式可能不認得新結構。**最保險的退回方式是:退回舊映像 + 還原「升級前那份備份」**(見[備份指南](backup.md)的還原流程)。若該次升級的 CHANGELOG 未標註 schema 變更,則單純換映像即可。 +### 從 v1.4.20 退回 v1.4.19 + +v1.4.20 改了資料表結構,**直接把版本號改回 v1.4.19,舊版會啟動失敗**。兩種退回方式擇一: + +- **方式一:用升級前自動備份還原**——做法同下方「從 v1.3.0 退回 v1.2.x」的方式一。升級後才登記的請假、調代課不會保留。 +- **方式二:退回指令(資料保留,只移除三角調課的欄位)**——在 `docker-compose.yml` 所在資料夾,**先以 v1.4.20 執行**: + + ```bash + docker compose run --rm --entrypoint alembic api downgrade 0021_class_suspensions + ``` + + 這會移除三角調課用的欄位。**執行前請先到「調代課處理」撤回已經成立的三角調課**——舊版看不懂 + 三角調課,會把它當成兩人互調而顯示錯誤。課表、請假、代課等其他資料都不動。 + 接著把 `.env` 的 `IMAGE_TAG` 改回 v1.4.19,執行 `docker compose pull` 與 `docker compose up -d`。 + ### 從 v1.4.19 退回 v1.4.18 v1.4.19 新增了停課日的資料表,**直接把版本號改回 v1.4.18,舊版會啟動失敗**。兩種退回方式擇一: diff --git a/docs/features.html b/docs/features.html index e1115799..8b29ebe4 100644 --- a/docs/features.html +++ b/docs/features.html @@ -3,7 +3,7 @@ - + 功能總覽 · 排課與調代課系統 diff --git a/frontend/src/views/substitution/logText.test.ts b/frontend/src/views/substitution/logText.test.ts index b1b4df69..af1b7d1b 100644 --- a/frontend/src/views/substitution/logText.test.ts +++ b/frontend/src/views/substitution/logText.test.ts @@ -10,6 +10,7 @@ const base: LogEntry = { sub_type: 'swap', sub_type_label: '調課', handler_teacher_id: 2, handler_name: '林師', counts_toward_hours: null, swap_date: '2026-11-20', swap_period_name: '第三節', swap_class_names: '802', swap_subject_name: '輔導', note: '', row_kind: 'leave', + is_triangle: false, tri_teacher_name: '', tri_date: null, tri_period_name: '', } describe('調代課紀錄的處置欄', () => { @@ -27,6 +28,17 @@ describe('調代課紀錄的處置欄', () => { .toBe('調課補課 · 王師(與 11/19(週四) 第五節 對調)') }) + it('三角調課寫出三位老師各上哪一節(v1.4.20)', () => { + const tri = { ...base, leave_type: 'sick', is_triangle: true, tri_teacher_name: '陳師', + tri_date: '2026-11-20', tri_period_name: '第二節', swap_date: '2026-11-23', + swap_period_name: '第三節' } + expect(logDisposition(tri)) + .toBe('三角調課 · 林師(陳師 11/20(週五) 第二節代林師、王師 11/23(週一) 第三節補課)') + expect(logDisposition({ ...tri, row_kind: 'swap_makeup', handler_name: '陳師', + swap_date: '2026-11-23', swap_period_name: '第三節' })) + .toBe('三角調課 · 陳師(陳師原本的 11/23(週一) 第三節 由別人上)') + }) + it('代課、待處理照舊', () => { expect(logDisposition({ ...base, sub_type: 'substitute', sub_type_label: '代課', swap_date: null, swap_period_name: '' })).toBe('代課 · 林師') diff --git a/frontend/src/views/substitution/logText.ts b/frontend/src/views/substitution/logText.ts index 4da3b57e..8d3a86b1 100644 --- a/frontend/src/views/substitution/logText.ts +++ b/frontend/src/views/substitution/logText.ts @@ -17,6 +17,16 @@ export function shortDate(iso: string): string { */ export function logDisposition(e: LogEntry): string { if (!e.disposed) return '—' + // 三角調課(v1.4.20):請假那一列寫出另外兩位;其他兩列寫來上的老師空出哪一節 + if (e.is_triangle && e.row_kind === 'swap_makeup' && e.swap_date) { + return `三角調課 · ${e.handler_name}(${e.handler_name}原本的 ` + + `${shortDate(e.swap_date)} ${e.swap_period_name} 由別人上)` + } + if (e.is_triangle && e.swap_date) { + const tri = e.tri_date ? `${shortDate(e.tri_date)} ${e.tri_period_name}` : e.tri_period_name + return `三角調課 · ${e.handler_name}(${e.tri_teacher_name} ${tri}代${e.handler_name}、` + + `${e.absent_teacher_name} ${shortDate(e.swap_date)} ${e.swap_period_name}補課)` + } if (e.sub_type === 'swap' && e.swap_date) { const when = `${shortDate(e.swap_date)} ${e.swap_period_name}`.trim() if (e.row_kind === 'swap_makeup') return `調課補課 · ${e.handler_name}(與 ${when} 對調)` diff --git a/frontend/src/views/substitution/triangleText.test.ts b/frontend/src/views/substitution/triangleText.test.ts new file mode 100644 index 00000000..edbb0d64 --- /dev/null +++ b/frontend/src/views/substitution/triangleText.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest' +import type { TriangleOption } from '@/api/substitutions' +import { triangleDisposition, triangleSteps } from './triangleText' + +const lesson = (date: string, period: string, subject: string, teacher: string) => ({ + entry_id: 1, date, weekday: 4, period_no: 2, period_name: period, class_names: '701', + subject_name: subject, in_block: false, teacher_id: 1, teacher_name: teacher, +}) + +const opt: TriangleOption = { + partner_id: 2, partner_name: '林師', mid: lesson('2026-11-19', '第二節', '數學', '林師'), + third_id: 3, third_name: '陳師', makeup: lesson('2026-11-20', '第三節', '英語', '陳師'), +} + +describe('三角調課的文字(v1.4.20)', () => { + it('清單上一組寫成三個步驟', () => { + expect(triangleSteps('王師', opt)).toEqual([ + '林師 來上這一節', + '陳師 上林師的 11/19(週四) 第二節 數學', + '王師 上陳師的 11/20(週五) 第三節 英語', + ]) + }) + + it('成立後的處置寫出另外兩位各上哪一節', () => { + expect(triangleDisposition({ + handler: '林師', absent: '王師', third: '陳師', triDate: '2026-11-19', + triPeriod: '第二節', swapDate: '2026-11-20', swapPeriod: '第三節', + })).toBe('三角調課 → 林師(陳師 11/19(週四) 第二節代林師、王師 11/20(週五) 第三節補課)') + }) +}) diff --git a/frontend/src/views/substitution/triangleText.ts b/frontend/src/views/substitution/triangleText.ts new file mode 100644 index 00000000..797b17a9 --- /dev/null +++ b/frontend/src/views/substitution/triangleText.ts @@ -0,0 +1,35 @@ +import type { TriangleOption } from '@/api/substitutions' +import { shortDate } from './logText' + +/** + * 三角調課(v1.4.20)的文字:同一班三位老師輪流換課。 + * 乙來上請假那節、丙來上乙原本的一節、請假老師回來上丙原本的一節。 + */ + +/** 清單上一組的三個步驟:「林師 來上這一節」「陳師 上林師的 11/20(週四) 第二節 數學」… */ +export function triangleSteps(absentName: string, o: TriangleOption): string[] { + const slot = (x: TriangleOption['mid']) => + `${shortDate(x.date)} ${x.period_name} ${x.subject_name}`.trim() + return [ + `${o.partner_name} 來上這一節`, + `${o.third_name} 上${o.partner_name}的 ${slot(o.mid)}`, + `${absentName} 上${o.third_name}的 ${slot(o.makeup)}`, + ] +} + +export interface TriangleParts { + handler: string // 乙:來上請假那節 + absent: string // 請假(發起)的老師 + third: string // 丙 + triDate: string | null + triPeriod: string + swapDate: string | null + swapPeriod: string +} + +/** 已成立的三角調課:「三角調課 → 林師(陳師 11/20(週四) 第二節代林師、王師 11/21(週五) 第三節補課)」 */ +export function triangleDisposition(p: TriangleParts): string { + const at = (d: string | null, name: string) => `${d ? shortDate(d) : ''} ${name}`.trim() + return `三角調課 → ${p.handler}(${p.third} ${at(p.triDate, p.triPeriod)}代${p.handler}、` + + `${p.absent} ${at(p.swapDate, p.swapPeriod)}補課)` +}