Compare commits

...
114 Commits
Author SHA1 Message Date
walkdoggo.yehandClaude Opus 5 ba992f1c31 Merge PR #44: 管理權限搬進主看板,不再是獨立頁面
CI / build (push) Successful in 46s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 09:20:04 +00:00
walkdoggo.yehandClaude Opus 5 fd1d2d374c 刪除 permissions.html(已搬進主看板)
CI / build (push) Successful in 31s
CI / build (pull_request) Successful in 33s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 08:48:16 +00:00
walkdoggo.yehandClaude Opus 5 5442cb39a0 server 測試跟著 /permissions 導回看板調整
CI / build (push) Successful in 35s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 08:48:07 +00:00
walkdoggo.yehandClaude Opus 5 aed0d1cb03 語法測試移除 permissions.html
CI / build (push) Failing after 19s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 08:47:35 +00:00
walkdoggo.yehandClaude Opus 5 27869d3e72 Dockerfile 移除 permissions.html
CI / build (push) Failing after 19s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 08:47:26 +00:00
walkdoggo.yehandClaude Opus 5 2f813c4691 看板支援 ?view= 直接打開指定區塊
CI / build (push) Failing after 20s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 08:47:17 +00:00
walkdoggo.yehandClaude Opus 5 bd1f6f1cdc /permissions 導回主看板的權限區塊
CI / build (push) Failing after 18s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 08:43:14 +00:00
walkdoggo.yehandClaude Opus 5 41aa9295d2 權限管理搬進主看板,成為一個區塊
CI / build (push) Successful in 36s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 08:42:51 +00:00
walkdoggo.yehandClaude Opus 5 dff0a3c51c Merge PR #43: 部長頁顯示部門的人員異動
CI / build (push) Successful in 41s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 08:38:43 +00:00
walkdoggo.yehandClaude Opus 5 aa7ae3e5a0 Merge PR #42: 測試:檢查 html 內嵌與瀏覽器用的 JavaScript 語法
CI / build (push) Successful in 44s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 08:38:23 +00:00
walkdoggo.yehandClaude Opus 5 2aada28e91 測試修正:轉出的部門本來就看得到那個人離開
CI / build (pull_request) Successful in 34s
CI / build (push) Successful in 35s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 08:12:27 +00:00
walkdoggo.yehandClaude Opus 5 feca9bf668 測試:部長看到的人員異動清單
CI / build (push) Failing after 19s
CI / build (pull_request) Failing after 22s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 08:09:00 +00:00
walkdoggo.yehandClaude Opus 5 43be043dc3 部長頁顯示人員異動區塊
CI / build (push) Successful in 33s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 08:08:34 +00:00
walkdoggo.yehandClaude Opus 5 58b672bde1 部長頁的範圍資料帶上預排,才算得出誰離開
CI / build (push) Successful in 34s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 08:07:57 +00:00
walkdoggo.yehandClaude Opus 5 dc809df1da 部長頁帶出部門的人員異動(誰離開、誰加入、生效月份)
CI / build (push) Successful in 37s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 08:07:27 +00:00
walkdoggo.yehandClaude Opus 5 295250c8e5 測試:檢查 html 內嵌與瀏覽器用的 JavaScript 語法
CI / build (push) Successful in 32s
CI / build (pull_request) Successful in 30s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 07:22:12 +00:00
walkdoggo.yehandClaude Opus 5 ab4a3c9842 Merge PR #41: 預計轉調加上主管職設定
CI / build (push) Successful in 43s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 07:14:19 +00:00
walkdoggo.yehandClaude Opus 5 497bd6e773 預計轉調介面加上主管職設定與提醒
CI / build (push) Successful in 34s
CI / build (pull_request) Successful in 29s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 07:03:37 +00:00
walkdoggo.yehandClaude Opus 5 8a8cb653cd 測試:轉調的主管職卸任、保留、接任者與提醒
CI / build (push) Successful in 31s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 07:02:44 +00:00
walkdoggo.yehandClaude Opus 5 e8bca4ab60 預計轉調加上主管職:卸任/保留、接任者,HR 主管沒處理就持續提醒
CI / build (push) Successful in 32s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 07:02:03 +00:00
walkdoggo.yehandClaude Opus 5 126c1e48c5 Merge PR #40: 核心參數加上 CODA 分配規則的編輯介面
CI / build (push) Successful in 43s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 07:00:02 +00:00
walkdoggo.yehandClaude Opus 5 6f6ce47142 核心參數加上 CODA 分配規則的編輯介面
CI / build (push) Successful in 35s
CI / build (pull_request) Successful in 30s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 06:53:32 +00:00
walkdoggo.yehandClaude Opus 5 52840d4377 Merge PR #39: 預排異動頁面加上「預計轉調」
CI / build (push) Successful in 42s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 06:45:59 +00:00
walkdoggo.yehandClaude Opus 5 09608b11c5 預排異動頁面加上「預計轉調」
CI / build (push) Successful in 34s
CI / build (pull_request) Successful in 32s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 06:43:14 +00:00
walkdoggo.yehandClaude Opus 5 f05704c66f Merge PR #38: 預排異動新增「預計轉調」
CI / build (push) Successful in 45s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 02:20:29 +00:00
walkdoggo.yehandClaude Opus 5 49a70e15a5 測試:空的預排現在也會帶 transfers
CI / build (push) Successful in 36s
CI / build (pull_request) Successful in 35s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 01:46:35 +00:00
walkdoggo.yehandClaude Opus 5 907b51f85f 測試:空的預排現在也會帶 transfers
CI / build (push) Failing after 21s
CI / build (pull_request) Failing after 21s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 01:46:19 +00:00
walkdoggo.yehandClaude Opus 5 e84fb5ffee 測試:預計轉調的驗證、套用、拆月、自動核對與衝突
CI / build (push) Failing after 19s
CI / build (pull_request) Failing after 20s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 01:45:07 +00:00
walkdoggo.yehandClaude Opus 5 a5dfd69f6d 看板套用預排轉調
CI / build (push) Failing after 21s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 01:44:30 +00:00
walkdoggo.yehandClaude Opus 5 a8d70af4df 預排異動新增「預計轉調」:生效月份起算新部門,HR 同步後自動移除
CI / build (push) Failing after 21s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 01:44:15 +00:00
walkdoggo.yehandClaude Opus 5 5f974a618c Merge PR #37: CODA 分配規則改由核心參數設定
CI / build (push) Successful in 49s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 01:40:13 +00:00
walkdoggo.yehandClaude Opus 5 0fa7cc733d 測試:核心參數的 CODA 分配規則與來源部門不顯示倍率
CI / build (push) Successful in 32s
CI / build (pull_request) Successful in 32s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 01:34:46 +00:00
walkdoggo.yehandClaude Opus 5 0c09b8857c 測試:CODA 分配規則的驗證與保存
CI / build (push) Successful in 31s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 01:34:25 +00:00
walkdoggo.yehandClaude Opus 5 80a35755fa 看板存檔時帶回 CODA 分配規則,避免被覆蓋
CI / build (push) Successful in 36s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 01:34:03 +00:00
walkdoggo.yehandClaude Opus 5 c5fd992f50 伺服器:驗證並保存 CODA 分配規則
CI / build (push) Successful in 37s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 01:33:47 +00:00
walkdoggo.yehandClaude Opus 5 c8836e52c8 CODA 分配規則改由核心參數設定;來源部門不顯示倍率
CI / build (push) Successful in 40s
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-25 01:33:22 +00:00
walkdoggo.yehandClaude Sonnet 5.5 09ae39e059 Merge PR #36: 全站按鈕加上極小的滑過與按下動畫
CI / build (push) Successful in 50s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 09:35:40 +00:00
walkdoggo.yehandClaude Sonnet 5.5 8b2adc5b75 測試:樣式表可取得且四頁都引用
CI / build (push) Successful in 37s
CI / build (pull_request) Successful in 37s
測試:樣式表可取得且四頁都引用

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 09:17:04 +00:00
walkdoggo.yehandClaude Sonnet 5.5 298c057988 Dockerfile 複製 buttons.css
CI / build (push) Successful in 36s
Dockerfile 複製 buttons.css

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 09:17:02 +00:00
walkdoggo.yehandClaude Sonnet 5.5 9d85a9f0ec 伺服器開放 /buttons.css
CI / build (push) Successful in 35s
伺服器開放 /buttons.css

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 09:17:01 +00:00
walkdoggo.yehandClaude Sonnet 5.5 d2875f33c4 頁面引用共用按鈕樣式表
CI / build (push) Successful in 35s
頁面引用共用按鈕樣式表

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 09:17:00 +00:00
walkdoggo.yehandClaude Sonnet 5.5 08a8cfb5e8 頁面引用共用按鈕樣式表
CI / build (push) Successful in 32s
頁面引用共用按鈕樣式表

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 09:16:59 +00:00
walkdoggo.yehandClaude Sonnet 5.5 0aa3529ba2 頁面引用共用按鈕樣式表
CI / build (push) Successful in 31s
頁面引用共用按鈕樣式表

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 09:16:57 +00:00
walkdoggo.yehandClaude Sonnet 5.5 10a314b762 頁面引用共用按鈕樣式表
CI / build (push) Successful in 31s
頁面引用共用按鈕樣式表

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 09:16:56 +00:00
walkdoggo.yehandClaude Sonnet 5.5 308c96fc3f 共用按鈕樣式表:滑過與按下的極小動畫
CI / build (push) Successful in 34s
新增 buttons.css,全站按鈕共用 120ms 顏色轉場與按下時 3% 微縮;尊重減少動態效果設定。

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 09:16:42 +00:00
walkdoggo.yehandClaude Sonnet 5.5 afc6cef808 Merge pull request '/my:「顯示薪資」按鈕移到頁面最上方' (#35) from feat/salary-toggle-top into main
CI / build (push) Successful in 43s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:56:47 +00:00
walkdoggo.yehandClaude Sonnet 5.5 92c2d489c2 /my:「顯示薪資」按鈕移到頁面最上方
CI / build (push) Successful in 38s
CI / build (pull_request) Successful in 31s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:55:52 +00:00
walkdoggo.yehandClaude Sonnet 5.5 5729b38d41 Merge pull request 'cookie 名稱 pm_board_* 改為 leadboard_*' (#34) from feat/cookie-rename into main
CI / build (push) Successful in 45s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:45:45 +00:00
walkdoggo.yehandClaude Sonnet 5.5 8fef96b659 測試:cookie 名稱改為 leadboard_*
CI / build (push) Successful in 35s
CI / build (pull_request) Successful in 34s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:44:47 +00:00
walkdoggo.yehandClaude Sonnet 5.5 12d30d0c8a 登入用的 cookie 名稱 pm_board_* 改為 leadboard_*(所有人會重新登入一次)
CI / build (push) Failing after 17s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:44:46 +00:00
walkdoggo.yehandClaude Sonnet 5.5 f6621fc61c Merge pull request '資料改存 SQLite(leadboard.db)' (#33) from feature/sqlite-storage into main
CI / build (push) Successful in 44s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:34:00 +00:00
walkdoggo.yehandClaude Sonnet 5.5 091c93993f 新增測試:SQLite 存檔、migration、匯入與核對
CI / build (push) Successful in 32s
CI / build (pull_request) Successful in 33s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:05:33 +00:00
walkdoggo.yehandClaude Sonnet 5.5 2a8625b93d 測試:伺服器存檔改從 leadboard.db 讀取
CI / build (push) Successful in 33s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:04:54 +00:00
walkdoggo.yehandClaude Sonnet 5.5 b28497767b Dockerfile:把 storage.js、db.js、import-json.js、data-store.js 放進映像
CI / build (push) Failing after 19s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:04:53 +00:00
walkdoggo.yehandClaude Sonnet 5.5 cd77f1488a 伺服器的所有存檔改存 leadboard.db(第一次啟動自動匯入並核對 JSON)
CI / build (push) Failing after 19s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:04:38 +00:00
walkdoggo.yehandClaude Sonnet 5.5 4b642e57e5 登入狀態存檔改接共用存檔介面(storage.js)
CI / build (push) Failing after 29s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:04:03 +00:00
walkdoggo.yehandClaude Sonnet 5.5 2ce8f284a2 年度封存改接共用存檔介面(storage.js)
CI / build (push) Failing after 30s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:04:01 +00:00
walkdoggo.yehandClaude Sonnet 5.5 ef9d246f2d 預排異動存檔改接共用存檔介面(storage.js)
CI / build (push) Failing after 29s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:03:48 +00:00
walkdoggo.yehandClaude Sonnet 5.5 6f48e75af6 手動權限存檔改接共用存檔介面(storage.js)
CI / build (push) Failing after 28s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:03:47 +00:00
walkdoggo.yehandClaude Sonnet 5.5 d1e5938267 定錨存檔改接共用存檔介面(storage.js)
CI / build (push) Failing after 31s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:03:45 +00:00
walkdoggo.yehandClaude Sonnet 5.5 6e29fe5e8d 新增 import-json.js:可重跑的 JSON → leadboard.db 匯入與逐筆核對
CI / build (push) Successful in 34s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:03:32 +00:00
walkdoggo.yehandClaude Sonnet 5.5 2dee848652 新增 data-store.js:啟動時選擇存檔位置並首次匯入
CI / build (push) Successful in 30s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:03:06 +00:00
walkdoggo.yehandClaude Sonnet 5.5 731cc1ba14 新增 db.js:leadboard.db 與建表 migration
CI / build (push) Successful in 34s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:03:05 +00:00
walkdoggo.yehandClaude Sonnet 5.5 69bd6770c0 新增 storage.js:檔案/SQLite 共用的存檔介面
CI / build (push) Successful in 34s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 08:03:03 +00:00
walkdoggo.yehandClaude Sonnet 5.5 4d76db48ee Merge pull request '部門 CODA:新增各部門平均日工作 CODA 卡片' (#32) from feat/coda-avg-card into main
CI / build (push) Successful in 43s
Reviewed-on: #32

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 07:25:22 +00:00
walkdoggo.yehandClaude Sonnet 5.5 0b2412a712 部門 CODA 頁:全公司總 CODA 左邊新增各部門平均日工作 CODA
CI / build (push) Successful in 34s
CI / build (pull_request) Successful in 31s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 07:24:32 +00:00
walkdoggo.yehandClaude Sonnet 5.5 8a6d22c5cc 部門 CODA 頁:新增平均日工作 CODA 卡片(翻譯)
CI / build (push) Successful in 38s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 07:24:30 +00:00
walkdoggo.yehandClaude Sonnet 5.5 f9b3bcc805 Merge pull request '對外接口代號改為 leadboard(階段 B)' (#31) from feat/external-api-leadboard into main
CI / build (push) Successful in 46s
Reviewed-on: #31

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 06:42:35 +00:00
walkdoggo.yehandClaude Sonnet 5.5 c369c84694 對外接口代號改為 leadboard:skill 改名
CI / build (push) Successful in 30s
CI / build (pull_request) Successful in 30s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 06:40:58 +00:00
walkdoggo.yehandClaude Sonnet 5.5 a41a8b4f8a 對外接口代號改為 leadboard:README.md
CI / build (push) Successful in 31s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 06:40:56 +00:00
walkdoggo.yehandClaude Sonnet 5.5 79c0f5e433 對外接口代號改為 leadboard:EXTERNAL-API-SPEC.md
CI / build (push) Successful in 29s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 06:40:55 +00:00
walkdoggo.yehandClaude Sonnet 5.5 f771ef7b0a 對外接口代號改為 leadboard:AUTHENTIK-HANDOFF.md
CI / build (push) Successful in 30s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 06:40:54 +00:00
walkdoggo.yehandClaude Sonnet 5.5 8a53f77475 對外接口代號改為 leadboard:tests/external-api.test.mjs
CI / build (push) Successful in 36s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 06:40:52 +00:00
walkdoggo.yehandClaude Sonnet 5.5 d0b521fe7a 對外接口代號改為 leadboard:server.js
CI / build (push) Failing after 20s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 06:40:50 +00:00
walkdoggo.yehandClaude Sonnet 5.5 cb4ba76f30 對外接口代號改為 leadboard:external-api.js
CI / build (push) Failing after 18s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 06:40:49 +00:00
walkdoggo.yehandClaude Sonnet 5.5 b4300554be Merge pull request 'LeadBoard 改名(階段 A,切換當晚才合併)' (#30) from feat/leadboard-rename into main
CI / build (push) Successful in 53s
Reviewed-on: #30

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-23 04:18:34 +00:00
walkdoggo.yehandClaude Sonnet 5.5 7a3fd8fd91 LeadBoard 改名(階段 A):skills/pm-board-external-api/SKILL.md
CI / build (push) Successful in 31s
CI / build (pull_request) Successful in 30s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-19 06:46:17 +00:00
walkdoggo.yehandClaude Sonnet 5.5 c9d11344af LeadBoard 改名(階段 A):AUTHENTIK-HANDOFF.md
CI / build (push) Successful in 32s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-19 06:46:16 +00:00
walkdoggo.yehandClaude Sonnet 5.5 a8327f8578 LeadBoard 改名(階段 A):HR-INTEGRATION.md
CI / build (push) Successful in 33s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-19 06:46:14 +00:00
walkdoggo.yehandClaude Sonnet 5.5 814d88f2dc LeadBoard 改名(階段 A):EXTERNAL-API-SPEC.md
CI / build (push) Successful in 33s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-19 06:46:13 +00:00
walkdoggo.yehandClaude Sonnet 5.5 fdcad12cba LeadBoard 改名(階段 A):README.md
CI / build (push) Successful in 33s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-19 06:46:11 +00:00
walkdoggo.yehandClaude Sonnet 5.5 1717ba1d28 LeadBoard 改名(階段 A):i18n.js
CI / build (push) Successful in 33s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-19 06:46:10 +00:00
walkdoggo.yehandClaude Sonnet 5.5 0db0446d54 LeadBoard 改名(階段 A):server.js
CI / build (push) Successful in 35s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-19 06:46:09 +00:00
walkdoggo.yehandClaude Sonnet 5.5 c7f4bd882c LeadBoard 改名(階段 A):scope-ui.js
CI / build (push) Successful in 34s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-19 06:46:06 +00:00
walkdoggo.yehandClaude Sonnet 5.5 47fb4b32ac LeadBoard 改名(階段 A):archive.html
CI / build (push) Successful in 36s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-19 06:46:05 +00:00
walkdoggo.yehandClaude Sonnet 5.5 c8695a2382 LeadBoard 改名(階段 A):permissions.html
CI / build (push) Successful in 34s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-19 06:46:03 +00:00
walkdoggo.yehandClaude Sonnet 5.5 e513ad2bc7 LeadBoard 改名(階段 A):my.html
CI / build (push) Successful in 35s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-19 06:46:02 +00:00
walkdoggo.yehandClaude Sonnet 5.5 4628d1195d LeadBoard 改名(階段 A):index.html
CI / build (push) Successful in 36s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-19 06:46:00 +00:00
walkdoggo.yehandClaude Opus 5.5 88c6876570 Merge pull request '預排異動:HR 有結果就自動核對移除' (#29) from feat/plans-auto-reconcile into main
CI / build (push) Successful in 47s
Reviewed-on: walkdoggo.yeh/pm-board#29

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 06:29:12 +00:00
walkdoggo.yehandClaude Opus 5.5 871d8c0320 test: plans include history
CI / build (push) Successful in 35s
CI / build (pull_request) Successful in 32s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 06:27:10 +00:00
walkdoggo.yehandClaude Opus 5.5 972a7e6167 test: reconcilePlans
CI / build (push) Failing after 21s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 06:27:09 +00:00
walkdoggo.yehandClaude Opus 5.5 f6f64297fb i18n: strings for auto-reconcile
CI / build (push) Failing after 21s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 06:27:08 +00:00
walkdoggo.yehandClaude Opus 5.5 1c1da5658e feat: plan statuses show auto-removal month; auto-removal log
CI / build (push) Failing after 20s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 06:27:06 +00:00
walkdoggo.yehandClaude Opus 5.5 6e64909e2c feat: reconcile plans on top-admin board loads
CI / build (push) Failing after 20s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 06:27:05 +00:00
walkdoggo.yehandClaude Opus 5.5 d8cce8ee8c feat: auto-reconcile planned changes with the HR list; 1-month grace; removal history
CI / build (push) Failing after 19s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 06:27:04 +00:00
walkdoggo.yehandClaude Opus 5.5 fbf3faf058 Merge pull request '預排異動(一):預計離職、預計新進' (#28) from feat/planned-changes into main
CI / build (push) Successful in 45s
Reviewed-on: walkdoggo.yeh/pm-board#28

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 06:02:33 +00:00
walkdoggo.yehandClaude Opus 5.5 a77636d915 test: /api/plans is top-admin only; planned hires persist
CI / build (push) Successful in 28s
CI / build (pull_request) Successful in 28s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 05:59:07 +00:00
walkdoggo.yehandClaude Opus 5.5 8e4d5a54c8 test: plans.js unit tests
CI / build (push) Successful in 29s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 05:59:06 +00:00
walkdoggo.yehandClaude Opus 5.5 60fb423d9d i18n: English strings for 預排異動
CI / build (push) Successful in 30s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 05:59:04 +00:00
walkdoggo.yehandClaude Opus 5.5 1980eb8f05 feat: 預排異動 view, planned tags in staff table, anchor-panel counts, overdue banner
CI / build (push) Successful in 32s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 05:59:03 +00:00
walkdoggo.yehandClaude Opus 5.5 84a6d9137b build: copy plans.js into the image
CI / build (push) Successful in 32s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 05:59:01 +00:00
walkdoggo.yehandClaude Opus 5.5 da118c4af6 feat: plans.js — planned departures and hires store
CI / build (push) Failing after 26s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 05:58:59 +00:00
walkdoggo.yehandClaude Opus 5.5 0a2a515614 feat: apply planned departures/hires to every board computation; /api/plans (top admin only)
CI / build (push) Failing after 28s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 05:58:58 +00:00
walkdoggo.yehandClaude Opus 5.5 5b668ea947 Merge pull request 'fix: 登入資料加密存放(符合平台規範)' (#27) from fix/session-encryption into main
CI / build (push) Successful in 46s
Reviewed-on: walkdoggo.yeh/pm-board#27

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 05:48:34 +00:00
walkdoggo.yehandClaude Opus 5.5 012a770c5b test: 重新部署後登入資料是加密的
CI / build (push) Successful in 31s
CI / build (pull_request) Successful in 28s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 05:47:02 +00:00
walkdoggo.yehandClaude Opus 5.5 cc09f75e72 test: 加密存放、換密鑰讀不到、舊檔自動改寫
CI / build (push) Successful in 33s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 05:47:01 +00:00
walkdoggo.yehandClaude Opus 5.5 771e5eaa59 fix: 登入資料加密金鑰由執行期密鑰導出
CI / build (push) Failing after 19s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 05:47:00 +00:00
walkdoggo.yehandClaude Opus 5.5 d7d64ca9fb fix: 登入資料(含 refresh token)用 AES-256-GCM 加密存放
CI / build (push) Failing after 18s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 05:46:58 +00:00
walkdoggo.yehandClaude Opus 5.5 7dee63343d Merge pull request 'fix: 英文名只回傳權限範圍內的人' (#26) from fix/names-scope into main
CI / build (push) Successful in 41s
Reviewed-on: walkdoggo.yeh/pm-board#26

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 04:10:47 +00:00
walkdoggo.yehandClaude Opus 5.5 fb898f9b54 test: 一般同仁呼叫定錨、HR 組織、薪資、英文名一律擋下
CI / build (push) Successful in 30s
CI / build (pull_request) Successful in 31s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 04:09:26 +00:00
walkdoggo.yehandClaude Opus 5.5 fdf07d9f27 test: 英文名依權限範圍
CI / build (push) Successful in 32s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 04:09:25 +00:00
walkdoggo.yehandClaude Opus 5.5 5b5b791325 fix: /api/names 依權限裁切,不洩漏其他部門名單
CI / build (push) Successful in 34s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 04:09:24 +00:00
walkdoggo.yehandClaude Opus 5.5 3969754fa4 fix: 英文名只回傳權限範圍內的人
CI / build (push) Successful in 35s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-17 04:09:22 +00:00
walkdoggo.yehandClaude Opus 5.5 731ae3f568 Merge pull request 'feat: 中英切換與美金顯示(第一階段:主看板、/my)' (#25) from feat/i18n-currency into main
CI / build (push) Successful in 42s
Reviewed-on: walkdoggo.yeh/pm-board#25

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-11 17:38:51 +00:00
38 changed files with 2452 additions and 561 deletions
+13 -13
View File
@@ -8,8 +8,8 @@ Authentik 端 RD 已於 2026-10-29 設定並實測完成;這份只寫程式端
目前 `hr-sync.js` 用登入者的 session 換 token,所以沒人登入就讀不到 HR。排程改用站台自己的服務身分:
- **不需要新的環境變數或密鑰。** 沿用平台已注入的 `OIDC_CLIENT_ID`、`OIDC_CLIENT_SECRET`、`RESOURCE_SERVERS`。
這個 client(Authentik provider `vibe-pm-board`)已開放 `client_credentials`,
對應的服務帳號 `ak-vibe-pm-board-client_credentials` 已核准 `hr:read`、`hr:salary:read`。
這個 client(Authentik provider `vibe-leadboard`)已開放 `client_credentials`,
對應的服務帳號 `ak-vibe-leadboard-client_credentials` 已核准 `hr:read`、`hr:salary:read`(站台由 pm-board 改名 leadboard 時,RD 重新開放 `client_credentials` 並重新核准)。
- 要走兩步。`client_credentials` 拿到的 token,`aud` 是自己的 client_id,HR Sync 不收;
要再用 token exchange 換成 `aud: hr-sync-api`。
@@ -43,19 +43,19 @@ client_id=$OIDC_CLIENT_ID client_secret=$OIDC_CLIENT_SECRET
## 2. 對外接口 `/api/external/v1/{invoice,coda}` 的驗證
呼叫端送 `Authorization: Bearer <token>`。token 由 Authentik 的 `PM Board` provider 簽發,
呼叫端送 `Authorization: Bearer <token>`。token 由 Authentik 的 `leadboard` provider 簽發,
呼叫端用 token exchange 換來(vibe 站台由平台處理,見第 3 節)。
| 檢查 | 值 |
|---|---|
| 簽章 | JWKS `https://auth.moonshine-studio.net/application/o/pm-board/jwks/`(RS256,依 `kid` 取 key,快取) |
| `iss` | `https://auth.moonshine-studio.net/application/o/pm-board/`(含結尾斜線) |
| `aud` | `pm-board-api` |
| 簽章 | JWKS `https://auth.moonshine-studio.net/application/o/leadboard/jwks/`(RS256,依 `kid` 取 key,快取) |
| `iss` | `https://auth.moonshine-studio.net/application/o/leadboard/`(含結尾斜線) |
| `aud` | `leadboard-api` |
| `exp` | 未過期(效期 300 秒) |
| `scope` | 以空白分隔,要包含 `pm-board:read` |
| `scope` | 以空白分隔,要包含 `leadboard:read` |
- 沒有 token、簽章錯、`iss`/`aud` 不符、過期:`401`。
- token 有效但沒有 `pm-board:read`:`403`。Authentik 只發這個 scope 給群組 `pm-board-read`,
- token 有效但沒有 `leadboard:read`:`403`。Authentik 只發這個 scope 給群組 `leadboard-read`,
但後端仍要自己檢查。
- 只接受 `GET`。不要用登入 session 或 cookie 驗這兩支,也不要套 `access.js` 的工號白名單——
呼叫端可能是服務帳號,沒有工號。
@@ -69,14 +69,14 @@ client_id=$OIDC_CLIENT_ID client_secret=$OIDC_CLIENT_SECRET
```yaml
auth:
resource_servers:
pm-board:
leadboard:
scopes:
- pm-board:read
- leadboard:read
```
部署時平台會把它登記成可以換 `pm-board-api` 的 token,並在它的 `RESOURCE_SERVERS` 給
部署時平台會把它登記成可以換 `leadboard-api` 的 token,並在它的 `RESOURCE_SERVERS` 給
`base_url: http://192.168.8.64:9114`(這個站台在 `.64` 的容器)。需要 Deployment API
合併並上線 `pm-board` 註冊表條目後才能宣告。
- vibe 站台是代表登入者呼叫(OBO),所以**實際操作的使用者**要在 `pm-board-read` 群組;
合併並上線 `leadboard` 註冊表條目後才能宣告。
- vibe 站台是代表登入者呼叫(OBO),所以**實際操作的使用者**要在 `leadboard-read` 群組;
不在群組的人換 token 時整張被拒(`invalid_grant`)。
- 非 vibe 的系統要接,由 RD 個別建立服務帳號並登記。
+1 -1
View File
@@ -7,7 +7,7 @@ ENV NODE_ENV=production \
WORKDIR /app
COPY --chown=node:node package.json server.js access.js hr-sync.js hr-org.js cost-model.js contractor-store.js settings-store.js calc-core.js scope-ui.js i18n.js english-names.js calc-engine.js anchor-calc.js anchor-store.js permissions.js scope-view.js simulate.js external-api.js archive-store.js session-store.js index.html my.html permissions.html archive.html 2022_Moonshine_Logo_MS_logo_w_EN.png ./
COPY --chown=node:node package.json server.js access.js hr-sync.js hr-org.js cost-model.js contractor-store.js settings-store.js calc-core.js scope-ui.js i18n.js buttons.css english-names.js plans.js calc-engine.js anchor-calc.js anchor-store.js permissions.js scope-view.js simulate.js external-api.js archive-store.js session-store.js storage.js db.js import-json.js data-store.js index.html my.html archive.html 2022_Moonshine_Logo_MS_logo_w_EN.png ./
COPY --chown=node:node seed ./seed
COPY --chown=node:node fonts ./fonts
RUN mkdir -p /app/data && chown node:node /app/data
+6 -4
View File
@@ -1,6 +1,8 @@
# 對外接口規格與發布規則
PM Board(https://pm-board-vibe.moonshine-studio.net/)提供給公司內部其他系統讀取的「彙整後結果」。
LeadBoard(https://leadboard-vibe.moonshine-studio.net/)提供給公司內部其他系統讀取的「彙整後結果」。
(原名 PM Board,2026-11 改名;對外接口的代號也已同步改為 leadboard。)
本文件是這個接口的正式依據:給什麼、怎麼算、什麼時候更新、怎麼發布、怎麼記錄變更,都以這份為準。
- 文件狀態:規格已確認,程式已上線(2026-10-28;2026-11-04 更新:CODA 分為實際 CODA 與定錨 CODA;2026-11-12:接口已上線,第一次定錨前一律回 503 尚未定錨)。發票半年定錨的實作計畫見 PLAN-ANCHOR.md。
@@ -10,7 +12,7 @@ PM Board(https://pm-board-vibe.moonshine-studio.net/)提供給公司內部
## 1. 目的與範圍
- 讓公司內部其他專案讀取 PM Board 算好的**年度發票**與 **CODA** 數字,不必自己重算。
- 讓公司內部其他專案讀取 LeadBoard 算好的**年度發票**與 **CODA** 數字,不必自己重算。
- 只提供**彙整到部門/組別**的結果。不提供個人資料,也不提供 HR 原始資料。
- 只提供**當年度**的資料。
- 對方只能讀取,不能寫入。
@@ -233,7 +235,7 @@ PM Board(https://pm-board-vibe.moonshine-studio.net/)提供給公司內部
## 7. 存取與安全
- 對方系統的存取權限由 RD 設定(群組 `pm-board-read`)。
- 對方系統的存取權限由 RD 設定(群組 `leadboard-read`)。
- 伺服器讀取 HR 用的系統帳號已由 RD 建立(2026-10-29),權限 hr:read、hr:salary:read。
- 密鑰只放在部署環境變數裡,不寫進程式、不進 Git、不貼在對話中。
- 接口只開放讀取(GET)。
@@ -344,6 +346,6 @@ PM Board(https://pm-board-vibe.moonshine-studio.net/)提供給公司內部
已確認(2026-10-29,RD):
1. 伺服器系統帳號:沿用站台既有的 `OIDC_CLIENT_ID`/`OIDC_CLIENT_SECRET`,不新增環境變數,見 AUTHENTIK-HANDOFF.md §1。
2. 對方系統的認證方式:Bearer token,audience `pm-board-api`、scope `pm-board:read`,見 AUTHENTIK-HANDOFF.md §2。
2. 對方系統的認證方式:Bearer token,audience `leadboard-api`、scope `leadboard:read`,見 AUTHENTIK-HANDOFF.md §2。
已確認(2026-10-28):夢想創造總 CODA = 四個部門合計;部門平均日 CODA 的人數包含常態型外包。
+2 -2
View File
@@ -4,7 +4,7 @@
## 需要平台核准
1. `pm-board` 使用 HR Sync 的 `hr:read`,由伺服器讀取在職名冊與組織資料;API 不接受瀏覽器指定任意員工來代查。
1. `leadboard` 使用 HR Sync 的 `hr:read`,由伺服器讀取在職名冊與組織資料;API 不接受瀏覽器指定任意員工來代查。
2. 平台已核准此站的 `hr:salary:read`,僅供伺服器以指定薪資端點取得目前薪資。瀏覽器只取得試算表需要的欄位,沒有 HR Sync token。
3. `vibe.yaml` 已宣告兩項核准 scope。token exchange 的 `invalid_grant` 與 HR Sync `403` 會分別處理,不會使公司登入卡住。
@@ -26,4 +26,4 @@
## 給平台組的申請內容
`pm-board` 是供葉傳耀(員工編號 `20150906`)使用的公司成本報表。請核准 HR Sync 的 `hr:read` 供伺服器讀取全員名冊、組織與異動;站台白名單位於 `access.js`,報表資料 API 在 `server.js` 驗證登入後才回傳。預計於 `vibe.yaml` 宣告 `auth.resource_servers.hr-sync.scopes: [hr:read]`。全員薪資另請與 HR 資料負責人確認服務帳號核准、最小資料範圍、稽核和提供方式;現行互動式 token 無 `hr:salary:read`,不可直接開啟。網站只在伺服器處理上游憑證和全員資料,送到瀏覽器的內容依站台權限限制。
`leadboard` 是供葉傳耀(員工編號 `20150906`)使用的公司成本報表。請核准 HR Sync 的 `hr:read` 供伺服器讀取全員名冊、組織與異動;站台白名單位於 `access.js`,報表資料 API 在 `server.js` 驗證登入後才回傳。預計於 `vibe.yaml` 宣告 `auth.resource_servers.hr-sync.scopes: [hr:read]`。全員薪資另請與 HR 資料負責人確認服務帳號核准、最小資料範圍、稽核和提供方式;現行互動式 token 無 `hr:salary:read`,不可直接開啟。網站只在伺服器處理上游憑證和全員資料,送到瀏覽器的內容依站台權限限制。
+2 -2
View File
@@ -1,6 +1,6 @@
# pm-board
# LeadBoard
MoonShine 成本與發票目標試算站。內部人員以 HR Sync 的在職名冊、組織與目前薪資轉入 2027 試算;常態型外包仍獨立維護。
MoonShine 成本與發票目標試算站(原名 PM Board,2026-11 改名;對外接口的代號也已同步改為 leadboard。)。內部人員以 HR Sync 的在職名冊、組織與目前薪資轉入 2027 試算;常態型外包仍獨立維護。
## 本機預覽
+10 -17
View File
@@ -1,34 +1,27 @@
// 定錨存檔:COST_MODEL_DATA_DIR/anchors.json(新檔案,不進 Git)。
// 定錨存檔:anchors.json(存在 COST_MODEL_DATA_DIR/leadboard.db 的 documents 表;STORAGE_BACKEND=json 時是同名檔案,不進 Git)。
// 快照一旦存下就不改;之後只會新增下一次定錨、記錄最高點與調動生效月份。
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
import { bindFile } from './storage.js';
import { HALVES, anchoredCoda, anchoredInvoice, buildSnapshot, detectChanges, detectTransfers, halves } from './anchor-calc.js';
const emptyYear = () => ({ anchors: [], peaks: {}, transfers: {}, log: [], undone: [], peakResets: [], version: 0 });
export function createAnchorStore(path) {
export function createAnchorStore(source) {
const file = bindFile(source);
let state = null;
let queue = Promise.resolve();
async function load() {
if (state) return state;
if (!path) return (state = { version: 1, years: {} });
try {
state = JSON.parse(await readFile(path, 'utf8'));
if (!state || typeof state !== 'object' || !state.years) state = { version: 1, years: {} };
} catch (error) {
if (error.code !== 'ENOENT') throw error;
state = { version: 1, years: {} };
}
if (!file) return (state = { version: 1, years: {} });
const text = file.read();
state = text === null ? null : JSON.parse(text);
if (!state || typeof state !== 'object' || !state.years) state = { version: 1, years: {} };
return state;
}
async function save() {
if (!path) return;
await mkdir(dirname(path), { recursive: true });
const temporary = `${path}.${process.pid}.tmp`;
await writeFile(temporary, `${JSON.stringify(state)}\n`, { mode: 0o600 });
await rename(temporary, path);
if (!file) return;
file.write(`${JSON.stringify(state)}\n`);
}
// 所有寫入排隊執行,避免同時寫檔。
+15 -16
View File
@@ -1,7 +1,6 @@
// 年度封存:年底(H2 定錨之後)把這一年的結果存成唯讀快照,之後可以切換年份查看。
// 存在 COST_MODEL_DATA_DIR/archives/<年>.json(新檔案)。封存後不能修改或覆蓋。
import { mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';
// 存在 archives/<年>.json(leadboard.db 的 documents 表;STORAGE_BACKEND=json 時是 COST_MODEL_DATA_DIR/archives/ 資料夾)。封存後不能修改或覆蓋。
import { bindDirectory } from './storage.js';
const round = (value) => Math.round(Number(value) || 0);
@@ -26,29 +25,29 @@ export function buildArchive(model, anchors, { year, by, note, at }) {
};
}
export function createArchiveStore(dir) {
export function createArchiveStore(source) {
const memory = new Map();
const file = (year) => resolve(dir, `${Number(year)}.json`);
const storage = bindDirectory(source);
const name = (year) => `${Number(year)}.json`;
return {
async list() {
if (!dir) return [...memory.keys()].sort();
try {
return (await readdir(dir)).map(name => /^(\d{4})\.json$/.exec(name)?.[1]).filter(Boolean).map(Number).sort();
} catch (error) { if (error.code === 'ENOENT') return []; throw error; }
if (!storage) return [...memory.keys()].sort();
return storage.list().map(entry => /^(\d{4})\.json$/.exec(entry)?.[1]).filter(Boolean).map(Number).sort();
},
async get(year) {
if (!dir) return memory.get(Number(year)) || null;
try { return JSON.parse(await readFile(file(year), 'utf8')); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
if (!storage) return memory.get(Number(year)) || null;
const text = storage.read(name(year));
return text === null ? null : JSON.parse(text);
},
async save(archive) {
const year = Number(archive.year);
if (!Number.isInteger(year)) throw new RangeError('invalid year');
if (await this.get(year)) throw new RangeError(`${year} already archived`);
if (!dir) { memory.set(year, archive); return; }
await mkdir(dir, { recursive: true });
const temporary = `${file(year)}.${process.pid}.tmp`;
await writeFile(temporary, `${JSON.stringify(archive)}\n`, { mode: 0o600, flag: 'wx' });
await rename(temporary, file(year));
if (!storage) { memory.set(year, archive); return; }
try { storage.write(name(year), `${JSON.stringify(archive)}\n`, { exclusive: true }); } catch (error) {
if (error.code === 'EEXIST') throw new RangeError(`${year} already archived`);
throw error;
}
},
};
}
+3 -2
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MoonShine PM Board · 年度封存</title>
<title>MoonShine LeadBoard · 年度封存</title>
<link rel="icon" href="/2022_Moonshine_Logo_MS_logo_w_EN.png">
<style>
:root { --bg:#f6f4ef; --card:#ffffff; --text:#1f2328; --muted:#5f6670; --line:#e4e0d8; --accent:#4f6bed; --warn:#b4540a; }
@@ -27,10 +27,11 @@ button { font:inherit; border:1px solid var(--line); background:var(--card); col
button:focus-visible, a:focus-visible, input:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }
.warn { color:var(--warn); }
</style>
<link rel="stylesheet" href="/buttons.css">
</head>
<body>
<main>
<a href="/" class="sub">← 回到 PM Board(目前年度)</a>
<a href="/" class="sub">← 回到 LeadBoard(目前年度)</a>
<h1>年度封存與年份切換</h1>
<p class="sub">年底在 H2 定錨之後封存,封存後的年份唯讀、不能修改或覆蓋。封存只存部門與組的數字和定錨結果,不含個人資料。</p>
<div class="card"><div class="years" id="years">讀取中…</div><div id="action" style="margin-top:12px;"></div></div>
+54
View File
@@ -0,0 +1,54 @@
/* Button motion: one shared, very small hover and press language for every page.
Each page keeps its own hover colours; this file only adds the easing and the press-down. */
button,
.btn,
.link-button,
select.btn-outline {
transition: background-color 120ms ease-out, border-color 120ms ease-out, color 120ms ease-out,
filter 120ms ease-out, box-shadow 120ms ease-out, transform 120ms ease-out;
}
/* Press down: a 3% shrink that springs back. Disabled controls never move. */
button:not(:disabled):active,
a.btn:active,
.btn:not(:disabled):not(select):active {
transform: scale(0.97);
transition-duration: 60ms;
}
/* Small, dense controls shrink a little less so they do not look jumpy. */
table button:not(:disabled):active,
.sx-row button:not(:disabled):active,
.sx-pick button:not(:disabled):active,
.role-seg button:not(:disabled):active,
.theme-toggle button:not(:disabled):active,
.theme button:not(:disabled):active,
.link-button:not(:disabled):active {
transform: scale(0.98);
}
button:disabled {
transition: none;
}
/* Reduced motion: keep the colour easing, drop the press-down. */
@media (prefers-reduced-motion: reduce) {
button,
.btn,
.link-button,
select.btn-outline {
transition: background-color 120ms ease-out, border-color 120ms ease-out, color 120ms ease-out;
}
button:not(:disabled):active,
a.btn:active,
.btn:not(:disabled):not(select):active,
table button:not(:disabled):active,
.sx-row button:not(:disabled):active,
.sx-pick button:not(:disabled):active,
.role-seg button:not(:disabled):active,
.theme-toggle button:not(:disabled):active,
.theme button:not(:disabled):active,
.link-button:not(:disabled):active {
transform: none;
}
}
+34 -5
View File
@@ -282,6 +282,7 @@
const merged = new Set(DASHBOARD_COMPANY_MULTIPLIERS);
const units = [];
const seen = new Set();
const sharedOut = codaSharedOutDepts();
depts.forEach(d => {
const company = shortCompanyName(map.get(d) || '');
if (merged.has(company)) {
@@ -293,6 +294,8 @@
if (artist > 0) units.push({ label: company, company: true, multiplier: internal / artist });
return;
}
// CODA 整包分出去的部門只算成本,不顯示倍率。
if (sharedOut.has(d)) return;
const stats = deptStats[d];
if (stats && stats.multiplier) units.push({ label: d, company: false, multiplier: stats.multiplier });
});
@@ -305,14 +308,40 @@
return p.costNoUtil !== undefined ? p.costNoUtil : (p.totalCost || 0);
}
// CODA sharing (夢境現實 only): the whole CODA of the "from" departments plus the P staff
// of that company who have no department (e.g. the CEO) is split over the "to" departments
// CODA sharing: the whole CODA of the "from" departments, plus (noDeptP) the P staff of
// that company who have no department (e.g. the CEO), is split over the "to" departments
// in proportion to their own CODA. Inside a receiving department it follows the normal
// group / person rules.
const CODA_SHARE_RULES = [
// group / person rules. A "from" department keeps no CODA of its own, so it carries no
// 倍率 and no A:P: it is a cost-only unit (see dashboardMultiplierUnits).
// 核心參數 codaShareRules 會覆寫這份清單;沒有設定時用下面的預設。
const DEFAULT_CODA_SHARE_RULES = [
{ company: '夢境現實', from: ['專案與場館營運部'], noDeptP: true, to: ['互動技術部', '互動美術部'] }
];
// 讀核心參數的分配規則。格式不對的整條跳過;已經在 from 的部門不會再被當成 to。
function codaShareRules() {
const configured = globalParams.codaShareRules;
if (!Array.isArray(configured)) return DEFAULT_CODA_SHARE_RULES;
const names = (value) => [...new Set((Array.isArray(value) ? value : [])
.map(name => String(name == null ? '' : name).trim()).filter(Boolean))];
const rules = [];
for (const rule of configured) {
if (!rule || typeof rule !== 'object' || Array.isArray(rule)) continue;
const from = names(rule.from);
const to = names(rule.to).filter(name => !from.includes(name));
if (!from.length || !to.length) continue;
rules.push({ company: String(rule.company || '').trim(), from, to, noDeptP: Boolean(rule.noDeptP) });
}
return rules;
}
// 整包把 CODA 分出去的部門:只算成本,不談指標(不顯示倍率、不看 A:P)。
function codaSharedOutDepts() {
const out = new Set();
codaShareRules().forEach(rule => rule.from.forEach(dept => out.add(dept)));
return out;
}
// Returns { add: {dept: amount}, out: {dept: amount}, rules: [...] } for the current data.
// ownCoda is each department's own P + A CODA before sharing.
function codaShares(current, ownCoda) {
@@ -320,7 +349,7 @@
const out = {};
const rules = [];
const map = deptCompanyMap(current);
CODA_SHARE_RULES.forEach(rule => {
codaShareRules().forEach(rule => {
const to = rule.to.filter(d => d in ownCoda);
if (!to.length) return;
const fromDepts = rule.from.filter(d => d in ownCoda);
+24
View File
@@ -0,0 +1,24 @@
// 伺服器啟動時決定資料存在哪裡。
// - 有 COST_MODEL_DATA_DIR:預設存進 <資料夾>/leadboard.db(SQLite);STORAGE_BACKEND=json 可以退回舊的 JSON 檔。
// - 第一次用資料庫(import_log 沒有成功紀錄)時,自動把資料夾裡現有的 JSON 搬進去並逐筆核對;
// 核對不過就啟動失敗(寧可不上線,也不讓大家看到一份空的或錯的資料)。JSON 檔不會被動到。
import { resolve } from 'node:path';
import { openDatabase } from './db.js';
import { importJson, formatReport } from './import-json.js';
import { fileStorage, sqliteStorage } from './storage.js';
export function openDataStorage(dir, { backend = process.env.STORAGE_BACKEND, log = console } = {}) {
if (!dir) return null;
if (String(backend || 'sqlite').toLowerCase() === 'json') {
log.warn?.('storage: STORAGE_BACKEND=json,資料存在 JSON 檔');
return fileStorage(dir);
}
const db = openDatabase(resolve(dir, 'leadboard.db'));
const done = db.prepare('SELECT COUNT(*) AS n FROM import_log WHERE ok = 1').get().n;
if (!done) {
const result = importJson({ dir, db });
log.log?.(`storage: 第一次使用 leadboard.db,匯入既有 JSON\n${formatReport(result)}`);
if (!result.ok) { db.close(); throw new Error('storage: JSON 匯入核對未通過,不啟動(JSON 檔未動,資料庫已有的內容也未被覆蓋)'); }
}
return sqliteStorage(db);
}
+79
View File
@@ -0,0 +1,79 @@
// leadboard.db:用 Node 內建的 node:sqlite,不另外裝套件。
// 資料表由 MIGRATIONS 建立;每個版本只跑一次,記在 schema_migrations。要改資料表就「新增」一個版本,不要改舊的。
import { chmodSync, existsSync, mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import { DatabaseSync } from 'node:sqlite';
export const MIGRATIONS = Object.freeze([
{
version: 1,
name: 'documents-and-import-log',
sql: `
-- 原本 /app/data 裡的每個 JSON 檔對應一列;name 就是原來的相對檔名(例如 archives/2027.json),
-- body 是檔案內容原樣的文字,sha256 / bytes 供核對。
CREATE TABLE documents (
name TEXT PRIMARY KEY NOT NULL,
body TEXT NOT NULL,
sha256 TEXT NOT NULL,
bytes INTEGER NOT NULL,
updated_at TEXT NOT NULL
) STRICT;
-- 每次匯入/核對的紀錄。
CREATE TABLE import_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
started_at TEXT NOT NULL,
finished_at TEXT NOT NULL,
source_dir TEXT NOT NULL,
mode TEXT NOT NULL,
imported INTEGER NOT NULL,
unchanged INTEGER NOT NULL,
conflicts INTEGER NOT NULL,
records_checked INTEGER NOT NULL,
ok INTEGER NOT NULL,
detail TEXT NOT NULL
) STRICT;
`,
},
]);
export function migrate(db, migrations = MIGRATIONS, now = () => new Date().toISOString()) {
db.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
version INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, applied_at TEXT NOT NULL) STRICT`);
const applied = new Map(db.prepare('SELECT version, name FROM schema_migrations').all().map(row => [row.version, row.name]));
const known = new Set(migrations.map(item => item.version));
for (const version of applied.keys()) {
if (!known.has(version)) throw new Error(`資料庫有這個程式不認得的版本 ${version}(程式比資料庫舊?)`);
}
const ran = [];
for (const item of [...migrations].sort((a, b) => a.version - b.version)) {
if (applied.has(item.version)) continue;
db.exec('BEGIN IMMEDIATE');
try {
db.exec(item.sql);
db.prepare('INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)').run(item.version, item.name, now());
db.exec('COMMIT');
} catch (error) {
db.exec('ROLLBACK');
throw new Error(`migration ${item.version} (${item.name}) 失敗:${error.message}`);
}
ran.push(item.version);
}
return ran;
}
// 開啟(沒有就建立)並套用 migration。日誌模式維持預設的 DELETE:整個資料庫只有 leadboard.db 一個檔案,
// 平台備份複製這一個檔案就是完整的(WAL 會多出 -wal / -shm,單檔備份可能漏掉最近的寫入)。
export function openDatabase(path, options = {}) {
if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true });
const fresh = path !== ':memory:' && !existsSync(path);
const db = new DatabaseSync(path);
if (fresh) {
try { chmodSync(path, 0o600); } catch {
// 權限改不了就維持預設
}
}
db.exec('PRAGMA busy_timeout = 5000');
db.exec('PRAGMA synchronous = FULL');
migrate(db, options.migrations, options.now);
return db;
}
+12
View File
@@ -38,3 +38,15 @@ export function englishNameMap(people, store) {
}
return names;
}
// 只回傳這個人看得到的人:最高管理者、全公司檢視看全部;部主管看自己部門;組主管看自己的組。
export function visiblePeople(people, permission) {
if (!permission || permission.denied) return [];
if (permission.admin || permission.company) return people || [];
const depts = new Set(permission.depts || []);
const groups = new Set(permission.groups || []);
return (people || []).filter(p => {
const dept = String(p?.dept || '').trim();
return depts.has(dept) || groups.has(`${dept}|${p?.group || '未分組'}`);
});
}
+6 -3
View File
@@ -1,10 +1,13 @@
// 對外接口 /api/external/v1/{invoice,coda}(EXTERNAL-API-SPEC.md 第 8 節、AUTHENTIK-HANDOFF.md 第 2 節)。
// - 驗證:Authorization: Bearer <token>,Authentik PM Board provider 簽發,aud = pm-board-api,scope 含 pm-board:read。
// - 驗證:Authorization: Bearer <token>,Authentik LeadBoard provider 簽發(iss = API_ISSUER),aud = leadboard-api,scope 含 leadboard:read。
// - 資料只來自定錨:第一次定錨之前一律 503 not_anchored。不含任何個人資料。
import { createPublicKey, verify } from 'node:crypto';
export const API_AUDIENCE = 'pm-board-api';
export const API_SCOPE = 'pm-board:read';
export const API_AUDIENCE = 'leadboard-api';
export const API_SCOPE = 'leadboard:read';
// 簽發者與金鑰(JWKS);與登入用的 OIDC_ISSUER 分開,避免兩邊的設定互相牽動。
export const API_ISSUER = 'https://auth.moonshine-studio.net/application/o/leadboard/';
export const API_JWKS_URI = `${API_ISSUER}jwks/`;
export const CALC_VERSION = 3;
export const CALC_CHANGELOG = Object.freeze([
{ calcVersion: 1, date: '2026-10-28', change: '初版(含夢境現實 CODA 分攤;指標 3 為 P 輕重,依 A:P 成本比)', reason: '對外接口開始提供' },
+12 -4
View File
@@ -42,8 +42,16 @@
// ---- 中文 → English 對照表 ----
var DICT = {
// 導覽與共用
'PM Board · 2027 試算': 'PM Board · 2027 Planning', 'PM Board': 'PM Board',
'LeadBoard · 2027 試算': 'LeadBoard · 2027 Planning', 'LeadBoard': 'LeadBoard', '各部門平均日工作 CODA': 'Avg daily CODA per dept',
'儀表板': 'Dashboard', '年度發票額': 'Annual Invoice', '人員資料': 'Staff', '常態型外包': 'Regular Contractors',
'預排異動': 'Planned Changes', '預計離職': 'Planned Departures', '預計新進': 'Planned Hires',
'預排離職:最後': 'Planned departure: last month', '預排新進:': 'Planned hire: ', '開始': 'start',
'最後工作月份': 'Last working month', '備註': 'Note', '名稱': 'Name', '期間': 'Period',
'預估薪資': 'Est. salary', '+ 加入': '+ Add', '選擇人員…': 'Choose a person…', '選擇部門…': 'Choose a department…',
'等待 HR': 'Waiting for HR', '時間到了 HR 還沒改': 'Past due, HR not updated', '之後自動移除': 'auto-removed after',
'自動移除紀錄': 'Auto-removal log', 'HR 名單上已經沒有這個人': 'No longer in HR', 'HR 已填離職日': 'HR has a leave date',
'HR 名單已出現': 'Now in HR', '時間過了 HR 一直沒改,自動移除': 'Expired — HR never updated', '對到': 'Matched',
'目前沒有預計離職。': 'No planned departures.', '目前沒有預計新進。': 'No planned hires.',
'組織架構': 'Organization', '核心參數': 'Core Parameters', '業務管理': 'Production & Management (P)', '藝術家': 'Artists (A)',
'部門 CODA': 'Department CODA', '組別分析': 'Team Analysis', '模擬試算': 'Simulation', '權限管理': 'Permissions',
'日間': 'Light', '夜間': 'Dark', '配色': 'Theme', '語言': 'Language', '幣別': 'Currency',
@@ -173,7 +181,7 @@
'本機未啟用公司登入': 'Company sign-in is not enabled locally', '公司帳號': 'Company account', '目前登入帳號': 'Signed-in account', '登入狀態確認失敗': 'Sign-in check failed',
'請重新整理或登入': 'Please refresh or sign in', '尚未登入或登入已逾時': 'Not signed in or session expired', '登入後即可載入資料': 'Sign in to load data', '重新登入': 'Sign in again',
'登入已失效,請按左下角「重新登入」載入資料。': 'Your session has expired. Press “Sign in again” at the lower left to load data.',
'目前登入的公司帳號不在 PM Board 的允許名單內。': 'The signed-in company account is not on the PM Board allow list.',
'目前登入的公司帳號不在 LeadBoard 的允許名單內。': 'The signed-in company account is not on the LeadBoard allow list.',
'本站尚未收到平台提供的 HR Sync 執行期設定;因此沒有使用合成資料替代。': 'This site has not received the HR Sync runtime settings from the platform, so no synthetic data is used instead.',
'公司登入成功,但 HR Sync 未核准這個帳號的資料交換權限。': 'Company sign-in succeeded, but HR Sync has not approved data exchange for this account.',
'HR Sync 已連線,但拒絕目前要求的資料範圍。': 'HR Sync is connected but refused the requested data scope.', '公司登入已過期,請重新登入。': 'Your company sign-in has expired. Please sign in again.',
@@ -190,7 +198,7 @@
'1月': 'Jan', '2月': 'Feb', '3月': 'Mar', '4月': 'Apr', '5月': 'May', '6月': 'Jun', '7月': 'Jul', '8月': 'Aug', '9月': 'Sep', '10月': 'Oct', '11月': 'Nov', '12月': 'Dec',
'H2 下半年合約期間': 'H2 Contract Period', '✓ 確認新增': '✓ Add',
// /my 與模擬試算(scope-ui.js)
'MoonShine PM Board · 我的範圍': 'MoonShine PM Board · My View', '我的範圍': 'My View', '讀取中…': 'Loading…',
'MoonShine LeadBoard · 我的範圍': 'MoonShine LeadBoard · My View', '我的範圍': 'My View', '讀取中…': 'Loading…',
'實際 CODA:即時計算,資料一變就跟著變,定價看「平均日 CODA」。定錨 CODA:半年的目標(1 月、7 月定錨),半年內只增不減。所有數字都由伺服器計算。': 'Actual CODA is calculated live and changes whenever the data changes; use “Avg. Daily CODA” for pricing. Anchored CODA is the half-year target (anchored in January and July) and can only increase within the half. All numbers are calculated on the server.',
'工號': 'Employee No.', '權限來源:': 'Access via: ', '目前': 'Current', '定錨': 'Anchor',
'A 藝術家': 'A Artist', 'P 製作': 'P Production', 'O 外包': 'O Contractor', '實習生': 'Intern', '工讀(算 O)': 'Part-time (counted as O)',
@@ -216,7 +224,7 @@
'在本部門加人或調薪,看看實際 CODA、平均日 CODA、定錨 CODA、發票、倍率會變多少。工讀算 O:日薪=時薪×8。實習生只進發票、不算 CODA。': 'Add people or raise pay in this department and see how Actual CODA, Avg. Daily CODA, Anchored CODA, invoice and multiplier change. Part-timers count as O: daily pay = hourly pay × 8. Interns count toward invoice only, not CODA.',
'+ 加一個人': '+ Add a person', '你目前沒有可以模擬的部門。': 'You have no department to simulate.', '目前沒有可以看的部門或組別。': 'There is no department or team for you to view.',
'試算失敗:': 'Simulation failed: ', '(請檢查在職月份與金額)': ' (check months employed and amounts)', '內容已改,請重新試算。下面是上一次試算的結果。': 'Inputs changed; please run again. Below are the previous results.',
'你目前沒有 PM Board 的檢視權限。需要的話請找管理者開通。': 'You do not have PM Board view access yet. Ask an administrator if you need it.',
'你目前沒有 LeadBoard 的檢視權限。需要的話請找管理者開通。': 'You do not have LeadBoard view access yet. Ask an administrator if you need it.',
'資料讀取失敗,請稍後重新整理。': 'Could not load data. Please refresh later.', '不調整': 'No change', '模擬薪資': 'simulated salary',
// 補充(畫面檢查時找到的)
+155
View File
@@ -0,0 +1,155 @@
// 把資料夾裡的 JSON 檔搬進 leadboard.db(可以重跑)。
// node import-json.js [--dir /app/data] [--db /app/data/leadboard.db] [--dry-run] [--verify-only] [--force]
// 規則:
// - 檔案內容原樣存進 documents(不重新排版、不改順序),再讀回來逐筆核對。
// - 重跑安全:DB 裡已經有、內容相同的略過;DB 裡已經有、內容不同的「不覆蓋」(那可能是上線後的新資料),
// 列為衝突並以非 0 結束;確定要用 JSON 蓋掉才加 --force。
// - 任何一個檔案不是合法 JSON,整批都不寫入。
// - 不會刪除或修改 JSON 檔。
import { readFileSync, readdirSync } from 'node:fs';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { isDeepStrictEqual } from 'node:util';
import { openDatabase } from './db.js';
import { sha256 } from './storage.js';
// 要搬的檔案:資料夾第一層的 *.json(含 month-overrides-<年>.json)和 archives/*.json。暫存檔(*.tmp)不算。
const TOP_LEVEL = /^[A-Za-z0-9][A-Za-z0-9._-]*\.json$/;
const ARCHIVE = /^\d{4}\.json$/;
export function discover(dir) {
const names = [];
const entries = (path) => { try { return readdirSync(path, { withFileTypes: true }); } catch (error) { if (error.code === 'ENOENT') return []; throw error; } };
for (const entry of entries(dir)) if (entry.isFile() && TOP_LEVEL.test(entry.name)) names.push(entry.name);
for (const entry of entries(resolve(dir, 'archives'))) if (entry.isFile() && ARCHIVE.test(entry.name)) names.push(`archives/${entry.name}`);
return names.sort();
}
// 「筆」:最上層是陣列就每個元素一筆;是物件就每個欄位一筆,欄位的值若是陣列或物件,再往下算一層(例如 grants 裡每個人、history 每一則)。
export function records(value) {
const out = [];
const add = (key, item) => out.push([key, item]);
const expand = (prefix, item) => {
if (Array.isArray(item)) item.forEach((entry, index) => add(`${prefix}[${index}]`, entry));
else if (item && typeof item === 'object') for (const [key, entry] of Object.entries(item)) add(`${prefix}.${key}`, entry);
else add(prefix, item);
};
if (Array.isArray(value)) value.forEach((entry, index) => add(`[${index}]`, entry));
else if (value && typeof value === 'object') for (const [key, entry] of Object.entries(value)) expand(key, entry);
else add('(value)', value);
return out;
}
// 逐筆核對兩份已解析的資料;回傳筆數與不一致的位置。
export function compareRecords(expected, actual) {
const left = new Map(records(expected));
const right = new Map(records(actual));
const bad = [];
for (const [key, item] of left) if (!right.has(key) || !isDeepStrictEqual(item, right.get(key))) bad.push(key);
for (const key of right.keys()) if (!left.has(key)) bad.push(key);
return { count: left.size, bad };
}
function readSources(dir, names) {
const sources = [];
const problems = [];
for (const name of names) {
const text = readFileSync(resolve(dir, name), 'utf8');
try { sources.push({ name, text, data: JSON.parse(text) }); } catch (error) { problems.push(`${name}:不是合法的 JSON(${error.message})`); }
}
return { sources, problems };
}
// mode: 'import'(預設)|'dry-run'|'verify'。回傳 { ok, files, imported, unchanged, conflicts, records, problems }。
export function importJson({ dir, db, mode = 'import', force = false, now = () => new Date().toISOString() }) {
const startedAt = now();
const names = discover(dir);
const { sources, problems } = readSources(dir, names);
const select = db.prepare('SELECT body, sha256, bytes FROM documents WHERE name = ?');
const files = [];
let imported = 0, unchanged = 0, conflicts = 0, checked = 0;
const writes = [];
for (const source of sources) {
const row = select.get(source.name);
const file = { name: source.name, bytes: Buffer.byteLength(source.text, 'utf8'), records: records(source.data).length, status: '' };
if (!row) file.status = mode === 'verify' ? '資料庫沒有' : '新增';
else if (row.body === source.text) file.status = '相同';
else file.status = mode !== 'verify' && force ? '覆蓋' : '內容不同';
if (file.status === '新增' || file.status === '覆蓋') writes.push(source);
if (file.status === '內容不同') conflicts += 1;
if (file.status === '資料庫沒有') conflicts += 1;
if (file.status === '相同') unchanged += 1;
files.push(file);
}
if (mode === 'import' && !problems.length && writes.length) {
const upsert = db.prepare(`INSERT INTO documents (name, body, sha256, bytes, updated_at) VALUES (?, ?, ?, ?, ?)
ON CONFLICT(name) DO UPDATE SET body = excluded.body, sha256 = excluded.sha256, bytes = excluded.bytes, updated_at = excluded.updated_at`);
db.exec('BEGIN IMMEDIATE');
try {
for (const source of writes) upsert.run(source.name, source.text, sha256(source.text), Buffer.byteLength(source.text, 'utf8'), now());
db.exec('COMMIT');
} catch (error) { db.exec('ROLLBACK'); throw error; }
imported = writes.length;
}
// 核對:把剛剛(或先前)存進資料庫的內容讀回來,跟檔案逐筆比。
if (mode !== 'dry-run' && !problems.length) {
for (const file of files) {
const source = sources.find(item => item.name === file.name);
const row = select.get(file.name);
if (!row) continue;
if (row.body !== source.text) continue; // 內容不同/未覆蓋:已列為衝突,不是搬運錯誤
let stored;
try { stored = JSON.parse(row.body); } catch { stored = undefined; }
const compared = compareRecords(source.data, stored);
checked += compared.count;
file.checked = compared.count;
if (compared.bad.length || row.sha256 !== sha256(source.text) || row.bytes !== file.bytes) {
file.status = '核對失敗';
file.bad = compared.bad.slice(0, 20);
conflicts += 1;
}
}
}
const ok = !problems.length && !conflicts;
const summary = { ok, mode, dir, files, imported, unchanged, conflicts, records: checked, problems };
if (mode !== 'dry-run') {
db.prepare(`INSERT INTO import_log (started_at, finished_at, source_dir, mode, imported, unchanged, conflicts, records_checked, ok, detail)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(startedAt, now(), dir, force ? `${mode}+force` : mode, imported, unchanged, conflicts, checked, ok ? 1 : 0,
JSON.stringify({ files: files.map(({ name, status, records: count }) => ({ name, status, records: count })), problems }));
}
return summary;
}
export function formatReport(result) {
const lines = [`資料夾:${result.dir}(模式:${result.mode})`];
for (const file of result.files) {
lines.push(` ${file.status.padEnd(6, ' ')} ${file.name}(${file.bytes} bytes,${file.records} 筆${file.checked !== undefined ? `,已核對 ${file.checked} 筆` : ''})${file.bad ? ` 不一致:${file.bad.join(', ')}` : ''}`);
}
for (const problem of result.problems) lines.push(` 錯誤 ${problem}`);
lines.push(`新增或覆蓋 ${result.imported}、相同 ${result.unchanged}、衝突 ${result.conflicts}、核對 ${result.records} 筆 → ${result.ok ? '全部一致' : '有問題,請看上面'}`);
return lines.join('\n');
}
function main(argv) {
const args = new Map();
for (let index = 0; index < argv.length; index += 1) {
if (!argv[index].startsWith('--')) continue;
const key = argv[index].slice(2);
args.set(key, ['dir', 'db'].includes(key) ? argv[++index] : true);
}
const dir = resolve(args.get('dir') || process.env.COST_MODEL_DATA_DIR || '/app/data');
const dbPath = resolve(args.get('db') || resolve(dir, 'leadboard.db'));
const mode = args.get('dry-run') ? 'dry-run' : args.get('verify-only') ? 'verify' : 'import';
const db = openDatabase(dbPath);
try {
const result = importJson({ dir, db, mode, force: Boolean(args.get('force')) });
console.log(formatReport(result));
process.exitCode = result.ok ? 0 : 1;
} finally { db.close(); }
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main(process.argv.slice(2));
+600 -21
View File
@@ -4,7 +4,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MoonShine PM Board</title>
<title>MoonShine LeadBoard</title>
<script>
// Day / night: the viewer's saved choice, else the system setting. Stored per browser only.
(function () {
@@ -1808,8 +1808,67 @@
.nav-item svg { width: 15px; height: 15px; }
.sidebar-account .user-sub, .sidebar-account small { display: none; }
}
/* 權限管理:版面沿用原本獨立頁的設計,顏色改吃看板的變數;選擇器全部鎖在 #permissions 底下,不影響其他區塊。 */
#permissions {
--card: var(--surface); --raised: var(--wash-2); --text: var(--text-main);
--muted: var(--text-muted); --dim: var(--text-dim); --bg: var(--surface);
--accent: var(--accent-primary-text); --accent-soft: color-mix(in srgb, var(--accent-primary-text) 16%, transparent);
--warn: var(--accent-warning); --warn-soft: color-mix(in srgb, var(--accent-warning) 16%, transparent);
--good: var(--accent-success); --good-soft: color-mix(in srgb, var(--accent-success) 16%, transparent);
}
#permissions .lead { color:var(--muted); font-size:.88rem; margin:0 0 20px; max-width:760px; }
#permissions .rules { display:grid; grid-template-columns:repeat(auto-fit, minmax(220px, 1fr)); gap:10px; margin-bottom:22px; }
#permissions .rule { background:var(--card); border:1px solid var(--line); border-radius:12px; padding:12px 14px; font-size:.82rem; color:var(--muted); }
#permissions .rule b { display:block; color:var(--text); font-size:.9rem; margin-bottom:2px; }
#permissions .toolbar { display:flex; gap:10px; flex-wrap:wrap; align-items:center; margin-bottom:12px; }
#permissions .search { flex:1; min-width:220px; font:inherit; padding:9px 12px; border:1px solid var(--line); border-radius:10px; background:var(--card); color:var(--text); }
#permissions .tabs { display:flex; gap:6px; flex-wrap:wrap; }
#permissions .tab { font:inherit; font-size:.82rem; border:1px solid var(--line); background:var(--card); color:var(--muted); border-radius:99px; padding:5px 12px; cursor:pointer; }
#permissions .tab[aria-pressed="true"] { background:var(--text); color:var(--bg); border-color:var(--text); }
#permissions .tab .n { opacity:.7; margin-left:4px; font-variant-numeric:tabular-nums; }
#permissions .list { background:var(--card); border:1px solid var(--line); border-radius:14px; overflow:hidden; }
#permissions .row { display:grid; grid-template-columns: minmax(170px, 1.1fr) minmax(130px, .8fr) minmax(220px, 1.6fr) 72px; gap:14px; align-items:center; padding:12px 16px; border-top:1px solid var(--line); }
#permissions .row:first-child { border-top:0; }
#permissions .who b { display:block; font-size:.95rem; }
#permissions .who span, #permissions .where span { color:var(--dim); font-size:.78rem; }
#permissions .where { font-size:.86rem; }
#permissions .chips { display:flex; flex-wrap:wrap; gap:5px; }
#permissions .chip { font-size:.75rem; padding:2px 9px; border-radius:99px; background:var(--raised); border:1px solid var(--line); color:var(--muted); white-space:nowrap; }
#permissions .chip.hr { background:var(--accent-soft); border-color:transparent; color:var(--accent); }
#permissions .chip.manual { background:var(--good-soft); border-color:transparent; color:var(--good); }
#permissions .chip.warn { background:var(--warn-soft); border-color:transparent; color:var(--warn); }
#permissions .chip.admin { background:var(--text); color:var(--bg); border-color:transparent; }
#permissions .chip.old { opacity:.55; text-decoration:line-through; }
#permissions .none { color:var(--dim); font-size:.78rem; }
#permissions .act { text-align:right; }
#permissions .btn { font:inherit; font-size:.82rem; border:1px solid var(--line); background:var(--card); color:var(--text); border-radius:10px; padding:6px 12px; cursor:pointer; }
#permissions .btn:hover { background:var(--raised); }
#permissions .btn.primary { background:var(--accent); border-color:var(--accent); color:var(--surface); }
#permissions .editor { grid-column:1 / -1; display:grid; gap:14px; padding:14px; margin-top:4px; background:var(--raised); border:1px solid var(--line); border-radius:12px; }
#permissions .editor h4 { margin:0 0 8px; font-size:.85rem; color:var(--muted); font-weight:600; }
#permissions .toggles { display:grid; grid-template-columns:repeat(auto-fit, minmax(210px, 1fr)); gap:8px; }
#permissions .toggle { display:flex; gap:8px; align-items:flex-start; font-size:.85rem; cursor:pointer; }
#permissions .toggle small { display:block; color:var(--dim); font-size:.75rem; }
#permissions .pick { display:flex; flex-wrap:wrap; gap:6px 14px; font-size:.82rem; }
#permissions .pick label { display:inline-flex; gap:5px; align-items:center; white-space:nowrap; }
#permissions .actions { display:flex; gap:8px; justify-content:flex-end; align-items:center; }
#permissions .status { color:var(--good); font-size:.8rem; margin-right:auto; }
#permissions .empty { padding:28px 16px; text-align:center; color:var(--dim); font-size:.85rem; }
#permissions .log { background:var(--card); border:1px solid var(--line); border-radius:14px; overflow:hidden; }
#permissions .log-row { display:grid; grid-template-columns:150px minmax(130px,1fr) minmax(220px,2fr) minmax(130px,1fr); gap:12px; align-items:center; padding:10px 16px; border-top:1px solid var(--line); font-size:.82rem; }
#permissions .log-row:first-child { border-top:0; }
#permissions .log-row time, #permissions .log-row .by { color:var(--dim); font-variant-numeric:tabular-nums; }
#permissions .change { display:flex; flex-wrap:wrap; gap:5px; align-items:center; }
#permissions .arrow { color:var(--dim); }
@media (max-width: 820px) {
#permissions .row, #permissions .log-row { grid-template-columns:1fr 1fr; }
#permissions .row > .chips, #permissions .log-row > .change { grid-column:1 / -1; }
#permissions .where br { display:none; }
#permissions .where span:not(:empty)::before { content:' · '; }
}
</style>
<link rel="stylesheet" href="/buttons.css">
</head>
<body class="mode-admin">
@@ -1818,7 +1877,7 @@
<header>
<div class="logo">
<span class="wordmark">MOONSHINE</span>
<span class="wordmark-sub" id="wordmark-year">PM Board · 2027 試算</span>
<span class="wordmark-sub" id="wordmark-year">LeadBoard · 2027 試算</span>
</div>
<nav class="nav-group sidebar-navigation" aria-label="主選單">
@@ -1826,6 +1885,7 @@
<button type="button" class="nav-item" id="nav-invoice" onclick="showView('invoice')"><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M6 3h12v18l-3-2-3 2-3-2-3 2z"></path><path d="M9 8h6M9 12h6M9 16h3"></path></svg>年度發票額</button>
<button type="button" class="nav-item" id="nav-preview-personnel" onclick="showPersonnelView('all', 'internal')"><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="3" width="16" height="18" rx="2"></rect><path d="M8 7h8M8 11h2M12 11h2M8 15h2M12 15h2M8 18h2M12 18h4"></path></svg>人員資料</button>
<button type="button" class="nav-item" id="nav-contractors" onclick="showPersonnelView('all', 'contractors')"><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="8" r="3.5"></circle><path d="M3 20c0-3.3 2.7-6 6-6s6 2.7 6 6"></path><path d="M16 4.5a3.5 3.5 0 0 1 0 7M21 20c0-2.6-1.6-4.8-4-5.6"></path></svg>常態型外包</button>
<button type="button" class="nav-item" id="nav-plans" onclick="showView('plans')"><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="3.5" y="5" width="17" height="15.5" rx="2"></rect><path d="M3.5 10h17M8 3v4M16 3v4M8 14h3M8 17h6"></path></svg>預排異動</button>
<button type="button" class="nav-item" id="nav-org" onclick="showView('org-structure')"><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="3" width="6" height="5" rx="1"></rect><rect x="3" y="16" width="6" height="5" rx="1"></rect><rect x="15" y="16" width="6" height="5" rx="1"></rect><path d="M12 8v4M6 16v-2.5h12V16"></path></svg>組織架構</button>
<button type="button" class="nav-item" id="nav-params" onclick="showView('params')"><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 6h9M17 6h3M4 12h3M11 12h9M4 18h11M19 18h1"></path><circle cx="15" cy="6" r="2"></circle><circle cx="9" cy="12" r="2"></circle><circle cx="17" cy="18" r="2"></circle></svg>核心參數</button>
@@ -1834,7 +1894,7 @@
<button type="button" class="nav-item" id="nav-coda" onclick="showView('coda')"><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"></circle><circle cx="12" cy="12" r="5"></circle><circle cx="12" cy="12" r="1"></circle></svg>部門 CODA</button>
<button type="button" class="nav-item" id="nav-group" onclick="showView('group')"><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3l9 5-9 5-9-5z"></path><path d="M3 13l9 5 9-5"></path></svg>組別分析</button>
<button type="button" class="nav-item" id="nav-simulate" onclick="showView('simulate')"><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="3" width="14" height="18" rx="2"></rect><path d="M8 7h8M8 11h2M12 11h2M16 11h0M8 15h2M12 15h2M8 19h0"></path></svg>模擬試算</button>
<a class="nav-item" id="nav-permissions" href="/permissions"><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="11" width="14" height="9" rx="2"></rect><path d="M8 11V8a4 4 0 0 1 8 0v3"></path></svg>權限管理</a>
<button type="button" class="nav-item" id="nav-permissions" onclick="showView('permissions')"><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="11" width="14" height="9" rx="2"></rect><path d="M8 11V8a4 4 0 0 1 8 0v3"></path></svg>權限管理</button>
</nav>
<div class="nav-group sidebar-account" style="gap: 0.5rem;">
@@ -2022,6 +2082,30 @@
</div>
</div>
<!-- PERMISSIONS VIEW -->
<div id="permissions" class="view">
<div style="margin-bottom: 2rem;">
<h1 style="margin-bottom: 0.5rem;">權限管理</h1>
<p class="lead">HR 的主管會自動帶入權限;HR 拿掉主管身分,這些權限就自動消失。這裡加的是「手動」權限,要在這裡拿掉。只有最高管理者能改核心參數、按定錨、刪資料、管理權限。</p>
</div>
<div class="rules">
<div class="rule"><b>部主管(HR)</b>看部門、個人明細(含薪資)、部門模擬試算</div>
<div class="rule"><b>組主管(HR)</b>看自己組的實際 CODA、平均日 CODA、定錨 CODA</div>
<div class="rule"><b>手動加權限</b>全公司檢視、其他部門或組、個人明細、模擬</div>
</div>
<div class="toolbar">
<input class="search" id="perm-q" type="search" placeholder="搜尋姓名、工號、部門、組" oninput="permDraw()" aria-label="搜尋">
<div class="tabs" id="perm-tabs" role="group" aria-label="篩選"></div>
</div>
<div class="list" id="perm-rows"><div class="empty">讀取中…</div></div>
<details style="margin-top:1.5rem;">
<summary style="cursor:pointer; font-size:.9rem; color:var(--text-muted);">修改紀錄</summary>
<p class="lead" style="margin-top:.75rem;">權限每次儲存都會留下紀錄:什麼時候、誰改的、改了誰、改前改後。紀錄不能刪除(最多保留最近 2000 筆,這裡顯示最近 200 筆)。</p>
<div class="log" id="perm-log"></div>
</details>
</div>
<!-- PARAMETERS VIEW -->
<div id="params" class="view">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
@@ -2047,9 +2131,15 @@
<p style="color: var(--text-muted); font-size: 0.9rem; margin-top: 0.5rem;">P 系列預算 + A/O
藝術家預算 = 各部門最終 CODA。成本=年薪 × 人薪倍率,不除以產出率。</p>
</div>
<div class="card" style="padding: 1rem 2rem;">
<div class="card-label">全公司總 CODA</div>
<div class="card-value" id="coda-grand-total">NT$ 0</div>
<div style="display: flex; gap: 1rem; align-items: stretch;">
<div class="card" id="coda-avg-card" style="padding: 1rem 2rem;" title="夢想創造與夢境現實各部門「部門平均日工作 CODA」的簡單平均(不依人數加權)">
<div class="card-label">各部門平均日工作 CODA</div>
<div class="card-value" id="coda-avg-daily">NT$ 0</div>
</div>
<div class="card" style="padding: 1rem 2rem;">
<div class="card-label">全公司總 CODA</div>
<div class="card-value" id="coda-grand-total">NT$ 0</div>
</div>
</div>
</div>
<div id="coda-content">
@@ -2064,6 +2154,13 @@
<div id="simulate-content" style="margin-top: 1.5rem;"></div>
</div>
<!-- PLANNED CHANGES VIEW -->
<div id="plans" class="view">
<h1>預排異動</h1>
<p style="color: var(--text-muted); font-size: 0.9rem; margin-top: 0.5rem;">HR 還沒同步之前,先把已知的離職、新進排進試算。定錨時會照這份算;HR 一有結果就自動移除那一筆、改用 HR 的資料;時間過了 HR 還沒改,寬限 1 個月後也會自動移除。只有你看得到這一頁和備註;部長看到的是套用後的數字,看不到原因。</p>
<div id="plans-content" style="margin-top: 1.5rem;"></div>
</div>
<!-- ORG STRUCTURE VIEW -->
<div id="org-structure" class="view">
<div id="org-structure-content">
@@ -2165,7 +2262,7 @@
if (apPill) apPill.innerHTML = `整體 A:P 成本比 <b>${formatAPRatio(overallRatio)}</b>`;
const yearPill = document.getElementById('dash-year-pill');
const wordmarkYear = document.getElementById('wordmark-year');
if (wordmarkYear) wordmarkYear.textContent = `PM Board · ${globalParams.reportYear || 2027} 試算`;
if (wordmarkYear) wordmarkYear.textContent = `LeadBoard · ${globalParams.reportYear || 2027} 試算`;
if (yearPill) yearPill.innerHTML = `<a href="/archive" title="切換年份(查看已封存的年度)" style="color:inherit;text-decoration:none;"><b>${globalParams.reportYear || 2027}</b> ▾</a>`;
let diffHtml = '';
@@ -2739,6 +2836,59 @@
renderInvoiceRoles();
}
// ---- CODA 分配規則(核心參數):來源部門的整包 CODA 依各接收部門的 CODA 比例分下去 ----
// 沒設定過時用 calc-core 的內建預設;第一次編輯就把內建預設一起寫成明確設定,才不會被默默換掉。
function effectiveCodaShareRules() {
return Array.isArray(globalParams.codaShareRules) ? globalParams.codaShareRules : codaShareRules();
}
function saveCodaShareRules(rules) {
globalParams.codaShareRules = rules;
saveAndRefresh();
renderInvoiceRoles();
}
function removeCodaShareRule(index) {
saveCodaShareRules(effectiveCodaShareRules().filter((rule, i) => i !== index));
}
function addCodaShareRule() {
const from = document.getElementById('coda-share-from').value;
const to = [...document.querySelectorAll('.coda-share-to:checked')].map(input => input.value).filter(name => name !== from);
if (!from || !to.length) { alert('請選擇來源部門,並勾選至少一個接收部門。'); return; }
const map = deptCompanyMap(isSimMode ? simData : baseData);
const rules = effectiveCodaShareRules().filter(rule => !(rule.from || []).includes(from));
rules.push({ company: shortCompanyName(map.get(from) || ''), from: [from], to,
noDeptP: document.getElementById('coda-share-nodeptp').checked });
saveCodaShareRules(rules);
}
function codaShareCard() {
const depts = Object.keys(globalParams.orgStructure || {});
const known = new Set(depts);
const warn = name => known.has(name) ? escapeHtml(name)
: `<span style="color:var(--accent-warning);" title="目前名單上沒有這個部門">${escapeHtml(name)}</span>`;
const rules = effectiveCodaShareRules();
const rows = rules.map((rule, index) => `
<div class="ir-row">
<span class="ir-name">${(rule.from || []).map(warn).join('、')}</span>
<span class="ir-cost" style="white-space:normal;">分給 ${(rule.to || []).map(warn).join('、')}${rule.noDeptP ? ',並含該公司沒有部門的 P' : ''}</span>
<span class="ir-src"><button type="button" class="link-button" style="color:var(--accent-danger);" onclick="removeCodaShareRule(${index})">刪除</button></span>
</div>`).join('') || '<div class="ir-empty">目前沒有分配規則,每個部門的 CODA 都算自己的。</div>';
const options = depts.map(d => `<option value="${escapeHtml(d)}">${escapeHtml(d)}</option>`).join('');
const boxes = depts.map(d => `<label style="font-size:.8rem;display:inline-flex;align-items:center;gap:4px;margin-right:10px;white-space:nowrap;"><input type="checkbox" class="coda-share-to" value="${escapeHtml(d)}">${escapeHtml(d)}</label>`).join('');
return `
<div class="card ir-card" style="margin-top:1.5rem;">
<div class="card-head"><h2><span class="dot" style="background:var(--dot-amber)"></span>CODA 分配規則</h2></div>
<p style="font-size:.8rem;color:var(--text-dim);margin:.25rem 0 .75rem;">把來源部門的整包 CODA,依各接收部門自己的 CODA 比例分下去。來源部門的 CODA 會歸零,也不顯示部門倍率,等於只算成本、不談指標。這裡不影響發票分配,發票看的是上面的「發票承擔設定」。</p>
<div class="ir-grid"><section class="ir-company">${rows}</section></div>
<div style="display:grid;grid-template-columns:minmax(160px,1fr) minmax(260px,3fr) auto;gap:.5rem;align-items:start;margin-top:.75rem;">
<select id="coda-share-from" aria-label="來源部門"><option value="">來源部門…</option>${options}</select>
<div><div style="font-size:.75rem;color:var(--text-dim);margin-bottom:.25rem;">分給(可複選)</div>${boxes}
<label style="font-size:.8rem;display:inline-flex;align-items:center;gap:4px;margin-top:.35rem;"><input type="checkbox" id="coda-share-nodeptp">含該公司沒有部門的 P</label>
</div>
<button type="button" class="btn-primary" onclick="addCodaShareRule()">+ 加入</button>
</div>
<div class="card-foot"><span>同一個來源部門只會有一條規則,重複加入會覆蓋舊的。</span></div>
</div>`;
}
function renderInvoiceRoles() {
const container = document.getElementById('invoice-roles');
if (!container) return;
@@ -2808,7 +2958,7 @@
${bearDepts.length ? '' : '<div style="color:var(--accent-danger); font-weight:600; margin:0.25rem 0 0.5rem;">目前沒有任何「承擔發票」的部門,發票無法分配。</div>'}
<div class="ir-grid">${companyBlocks}</div>
<div class="card-foot"><span>新部門自動套用所屬公司的預設;部門可以個別改。</span>${stale.length ? `<span style="color:var(--accent-warning);">已失效的部門設定:${stale.map(d => `${escapeHtml(d)} <button type="button" class="link-button" onclick='setInvoiceRole("dept", ${escapeHtml(JSON.stringify(d))}, "")'>移除</button>`).join('、')}</span>` : ''}</div>
</div>`;
</div>${codaShareCard()}`;
}
// --- 定錨(發票+定錨 CODA)。數字全部由伺服器算,這裡只顯示。 ---
@@ -2840,6 +2990,7 @@
<button type="button" class="btn-primary" onclick="confirmAnchor('${st.nextHalf}')">確定 ${st.year} ${st.nextHalf} 定錨</button>
<button type="button" onclick="anchorConfirming=false;renderAnchors()">取消</button>
<div style="width:100%;font-size:.75rem;color:var(--text-dim);">定錨後這半年的發票與定錨 CODA 只增不減,快照不能修改,只能由下一次定錨取代。</div>
${planSummaryLine()}
</div>`
: `<button type="button" class="btn-primary" style="margin-top:.75rem;" onclick="anchorConfirming=true;renderAnchors()">確認 ${st.year} ${st.nextHalf} 定錨…</button>`;
}
@@ -3991,8 +4142,12 @@
const salaryShownPrefix = (isOutsource ? '日 ' : isHourly ? '時 ' : '') + PMI18n.sym() + ' ';
const salaryVal = isOutsource ? p.dayrate : isHourly ? p.hourlyRate : p.salary;
const isHrPerson = p.source === 'hr-sync';
const isPlanned = p.source === 'planned';
const safeName = escapeHtml(p.name);
const safeTitle = escapeHtml(p.title || '');
const planNote = isPlanned
? `<div style="font-size:0.75rem;color:var(--accent-secondary-text);margin-top:.35rem;white-space:nowrap;">預排新進:${escapeHtml(p.plannedHire)} 開始</div>`
: p.plannedLeave ? `<div style="font-size:0.75rem;color:var(--accent-warning);margin-top:.35rem;white-space:nowrap;">預排離職:最後 ${escapeHtml(p.plannedLeave)}</div>` : '';
const classification = p.transferSplit
? `<div style="font-size:0.75rem;color:var(--text-dim);margin-top:.35rem;white-space:nowrap;">${p.transferSplit === 'before' ? `調動前:${p.transferMonth} 月起算新部門` : `調動後:${p.transferMonth} 月起`}</div>`
: isHrPerson && p.partTime
@@ -4011,7 +4166,7 @@
</select>` : `<span class="role-pill ${roleClass}">${escapeHtml((p.role || '').split(' - ')[0])}</span>`;
const salaryControl = salaryHidden
? salaryMask()
: isHrPerson
: isHrPerson || isPlanned
? `<span title="由 HR Sync 提供,目前不可在試算頁覆寫">${salaryShownPrefix}${PMI18n.amt(parseFloat(salaryVal) || 0)}</span>`
: `<div style="display:flex; align-items:center; justify-content: flex-end;"><span style="font-size:0.75rem; color:var(--text-dim); margin-right:2px;">${salaryPrefix}</span><input type="number" style="text-align:right; width: 85px;" value="${salaryVal}" onchange="updatePerson(${origIdx}, '${salaryField}', this.value)"></div>`;
const weeklyDays = isHrPerson && isHourly
@@ -4023,21 +4178,21 @@
tbody.innerHTML += `
<tr>
<td style="white-space:nowrap;" title="${escapeHtml(p.company || '')}">${escapeHtml(shortCompanyName(p.company)) || '<span style="color:var(--text-dim);">未指定</span>'}</td>
<td>${isHrPerson ? safeName : `<input value="${safeName}" onchange="updatePerson(${origIdx}, 'name', this.value)" style="width: 75px;">`}</td>
<td>${isHrPerson ? safeTitle : `<input value="${safeTitle}" onchange="updatePerson(${origIdx}, 'title', this.value)" style="width: 85px;">`}</td>
<td>${placementCell(p, origIdx, 'dept')}</td>
<td>${placementCell(p, origIdx, 'group')}</td>
<td>${roleInput}${classification}</td>
<td>${isHrPerson || isPlanned ? safeName : `<input value="${safeName}" onchange="updatePerson(${origIdx}, 'name', this.value)" style="width: 75px;">`}</td>
<td>${isHrPerson || isPlanned ? safeTitle : `<input value="${safeTitle}" onchange="updatePerson(${origIdx}, 'title', this.value)" style="width: 85px;">`}</td>
<td>${isPlanned ? escapeHtml(p.dept || '') : placementCell(p, origIdx, 'dept')}</td>
<td>${isPlanned ? escapeHtml(shortGroupName(p.dept, p.group || '')) : placementCell(p, origIdx, 'group')}</td>
<td>${roleInput}${classification}${planNote}</td>
<td style="text-align:center;">${managerCell(p, origIdx, isHrPerson)}</td>
<td class="num">${salaryControl}</td>
<td class="num">${weeklyDays}</td>
<td class="num"><input type="number" min="1" max="6" value="${p.h1Start || ''}" placeholder="-" onchange="updatePerson(${origIdx}, 'h1Start', this.value)" class="input-mini" style="width: 38px;"></td>
<td class="num"><input type="number" min="1" max="6" value="${p.h1End || ''}" placeholder="-" onchange="updatePerson(${origIdx}, 'h1End', this.value)" class="input-mini" style="width: 38px;"></td>
<td class="num"><input type="number" min="7" max="12" value="${p.h2Start || ''}" placeholder="-" onchange="updatePerson(${origIdx}, 'h2Start', this.value)" class="input-mini" style="width: 38px;"></td>
<td class="num"><input type="number" min="7" max="12" value="${p.h2End || ''}" placeholder="-" onchange="updatePerson(${origIdx}, 'h2End', this.value)" class="input-mini" style="width: 38px;"></td>
<td class="num"><input type="number" min="1" max="6" value="${p.h1Start || ''}" placeholder="-" onchange="updatePerson(${origIdx}, 'h1Start', this.value)" class="input-mini" style="width: 38px;" ${isPlanned ? 'disabled title="在「預排異動」修改"' : ''}></td>
<td class="num"><input type="number" min="1" max="6" value="${p.h1End || ''}" placeholder="-" onchange="updatePerson(${origIdx}, 'h1End', this.value)" class="input-mini" style="width: 38px;" ${isPlanned ? 'disabled title="在「預排異動」修改"' : ''}></td>
<td class="num"><input type="number" min="7" max="12" value="${p.h2Start || ''}" placeholder="-" onchange="updatePerson(${origIdx}, 'h2Start', this.value)" class="input-mini" style="width: 38px;" ${isPlanned ? 'disabled title="在「預排異動」修改"' : ''}></td>
<td class="num"><input type="number" min="7" max="12" value="${p.h2End || ''}" placeholder="-" onchange="updatePerson(${origIdx}, 'h2End', this.value)" class="input-mini" style="width: 38px;" ${isPlanned ? 'disabled title="在「預排異動」修改"' : ''}></td>
<td class="num" style="text-align:center;">${isHrPerson && !p.calculationReady ? '<span class="status-pill status-temp">待確認</span>' : statusHtml}</td>
<td class="num" style="color: var(--text-main); font-weight:500;">${salaryHidden ? salaryMask() : `${PMI18n.cur(p.totalCost || 0)}`}</td>
<td>${isHrPerson ? '<span style="color:var(--text-dim);font-size:.8rem;">HR 同步</span>' : `<button onclick="removePerson(${origIdx})" style="background:none; border:none; color:var(--accent-danger); cursor:pointer;">刪除</button>`}</td>
<td>${isHrPerson ? '<span style="color:var(--text-dim);font-size:.8rem;">HR 同步</span>' : isPlanned ? '<button type="button" onclick="showView(\'plans\')" style="background:none;border:none;color:var(--accent-secondary-text);cursor:pointer;font-size:.8rem;">預排異動</button>' : `<button onclick="removePerson(${origIdx})" style="background:none; border:none; color:var(--accent-danger); cursor:pointer;">刪除</button>`}</td>
</tr>
`;
});
@@ -4576,6 +4731,8 @@
if (viewId === 'coda') renderCoda();
if (viewId === 'group') renderGroup();
if (viewId === 'org-structure') renderOrgStructure();
if (viewId === 'plans') loadPlans().then(renderPlans);
if (viewId === 'permissions') permLoad();
if (viewId === 'simulate') { if (window.__simulateView) window.__simulateView.reload(); else window.__simulateView = PMScope.mount(document.getElementById('simulate-content'), { mode: 'simulate' }); }
document.querySelector('main').scrollTo({ top: 0, left: 0, behavior: 'instant' });
}
@@ -4750,6 +4907,25 @@
return { dept: d, pBudget, aBudget, oBudget, sharedIn, sharedOut, rawA: deptData[d].rawA, rawO: deptData[d].rawO, totalCoda, groups: deptData[d].groups };
});
// --- 5b. 各部門平均日工作 CODA(夢想創造+夢境現實;簡單平均;只給最高管理者看) ---
{
const avgCard = document.getElementById('coda-avg-card');
const avgUser = typeof getCurrentUser === 'function' ? getCurrentUser() : null;
const avgIsAdmin = !avgUser || avgUser.role === 'admin';
if (avgCard) avgCard.style.display = avgIsAdmin ? '' : 'none';
const avgEl = document.getElementById('coda-avg-daily');
if (avgEl && avgIsAdmin) {
const avgCompanyOf = deptCompanyMap(current);
const avgDays = globalParams.annualWorkDays || 255;
const avgVals = codaRows
.filter(r => ['夢想創造', '夢境現實'].includes(shortCompanyName(avgCompanyOf.get(r.dept) || '')) && r.totalCoda > 0)
.map(r => { const fte = extractDeptFTE(r.groups); return fte ? (r.totalCoda / avgDays) / fte : 0; })
.filter(v => v > 0);
const avgMean = avgVals.length ? avgVals.reduce((s, v) => s + v, 0) / avgVals.length : 0;
avgEl.innerHTML = `<div class='currency-wrap' style='--symbol-width: 50px; --symbol-gap: 1.5rem; min-width: 180px; width: 100%;'><span>${PMI18n.sym()}</span><span>${PMI18n.amt(avgMean)}</span></div>`;
}
}
// --- 6. Update grand total ---
document.getElementById('coda-grand-total').innerHTML = `<div class='currency-wrap' style='--symbol-width: 50px; --symbol-gap: 1.5rem; min-width: 220px; width: 100%;'><span>${PMI18n.sym()}</span><span>${PMI18n.amt(grandCoda)}</span></div>`;
@@ -5047,6 +5223,397 @@
let contractorSignature = null;
let contractorSaveTimer = null;
// ---- 權限管理:原本是獨立的 /permissions 頁,搬進來變成一個區塊 ----
// 整包包在函式裡,只對外露出 perm 開頭的幾個名字,避免和看板既有的 state、filter、draw 撞名。
(function () {
let state = { people: [], grants: {}, denied: [], log: [] };
let filter = 'scoped';
let editing = null;
let message = {};
let logShown = 20;
const kindOf = (p) => {
const x = p.permission;
if (x.admin) return 'admin';
if (x.denied || state.denied.includes(p.employeeNumber)) return 'denied';
if (x.company) return 'company';
if (x.hr?.depts?.length) return 'dept';
if (x.hr?.groups?.length) return 'group';
if (state.grants[p.employeeNumber]) return 'manual';
return 'none';
};
const FILTERS = [
['scoped', '有權限', p => kindOf(p) !== 'none'],
['dept', '部長', p => kindOf(p) === 'dept'],
['group', '組長', p => kindOf(p) === 'group'],
['company', '全公司檢視', p => kindOf(p) === 'company'],
['manual', '有手動權限', p => Boolean(state.grants[p.employeeNumber])],
['denied', '暫不開放', p => kindOf(p) === 'denied'],
['all', '全部', () => true],
];
function chips(p) {
const x = p.permission;
if (x.admin) return '<span class="chip admin">最高管理者</span>';
if (x.denied) return '<span class="chip warn">暫不開放</span>';
const g = state.grants[p.employeeNumber] || {};
const out = [];
if (x.company) out.push(['manual', '全公司檢視']);
(x.hr?.depts || []).forEach(d => out.push(['hr', `部門 ${d}`]));
(x.hr?.groups || []).forEach(k => out.push(['hr', `組 ${k.split('|')[1]}`]));
(g.depts || []).forEach(d => out.push(['manual', `部門 ${d}`]));
(g.groups || []).forEach(k => out.push(['manual', `組 ${k.split('|')[1]}`]));
if (x.personDetail) out.push([x.hr?.depts?.length ? 'hr' : 'manual', '個人明細']);
if (x.simulate) out.push([x.hr?.depts?.length ? 'hr' : 'manual', '模擬']);
return out.length ? out.map(([c, t]) => `<span class="chip ${c}">${escapeHtml(t)}</span>`).join('') : '<span class="none">沒有權限</span>';
}
function options() {
const depts = [...new Set(state.people.map(p => p.dept).filter(Boolean))].sort((a, b) => a.localeCompare(b, 'zh-Hant'));
const groups = [...new Set(state.people.filter(p => p.dept && p.group).map(p => `${p.dept}|${p.group}`))].sort((a, b) => a.localeCompare(b, 'zh-Hant'));
return { depts, groups };
}
function editor(p) {
const g = state.grants[p.employeeNumber] || {};
const { depts, groups } = options();
const toggle = (name, label, hint, checked) => `<label class="toggle"><input type="checkbox" name="${name}" ${checked ? 'checked' : ''}><span>${label}<small>${hint}</small></span></label>`;
return `<div class="editor" id="perm-editor">
<div><h4>手動權限</h4><div class="toggles">
${toggle('company', '全公司檢視', '各部門、各組數字,不含個人薪資', g.company)}
${toggle('personDetail', '個人明細', '可看範圍內每個人的薪資與成本', g.personDetail)}
${toggle('simulate', '部門模擬', '可在看得到的部門做模擬試算', g.simulate)}
${toggle('denied', '暫不開放', '先不讓他看任何東西', state.denied.includes(p.employeeNumber))}
</div></div>
<div><h4>另外可以看的部門</h4><div class="pick">${depts.map(d => `<label><input type="checkbox" name="depts" value="${escapeHtml(d)}" ${(g.depts || []).includes(d) ? 'checked' : ''}>${escapeHtml(d)}</label>`).join('') || '<span class="none">沒有部門資料</span>'}</div></div>
<div><h4>另外可以看的組</h4><div class="pick">${groups.map(k => `<label><input type="checkbox" name="groups" value="${escapeHtml(k)}" ${(g.groups || []).includes(k) ? 'checked' : ''}>${escapeHtml(k.replace('|', ' · '))}</label>`).join('') || '<span class="none">沒有組資料</span>'}</div></div>
<div class="actions"><span class="status" role="status">${escapeHtml(message[p.employeeNumber] || '')}</span>
<button type="button" class="btn" onclick="permCancel()">取消</button>
<button type="button" class="btn primary" onclick="permSave('${escapeHtml(p.employeeNumber)}')">儲存</button></div>
</div>`;
}
function draw() {
const box = document.getElementById('perm-rows');
if (!box) return;
const q = (document.getElementById('perm-q').value || '').trim();
document.getElementById('perm-tabs').innerHTML = FILTERS.map(([key, label, test]) =>
`<button type="button" class="tab" aria-pressed="${filter === key}" onclick="permFilter('${key}')">${label}<span class="n">${state.people.filter(test).length}</span></button>`).join('');
const test = FILTERS.find(f => f[0] === filter)[2];
const rows = state.people.filter(test).filter(p => !q || [p.employeeNumber, p.name, p.dept, p.group].some(v => String(v || '').includes(q)));
box.innerHTML = rows.map(p => `<div class="row">
<div class="who"><b>${escapeHtml(p.name)}</b><span>${escapeHtml(p.employeeNumber)} ${escapeHtml(p.title)}</span></div>
<div class="where">${escapeHtml(p.dept || '—')}<br><span>${escapeHtml(p.group || '')}</span></div>
<div class="chips">${chips(p)}</div>
<div class="act">${p.permission.admin ? '' : `<button type="button" class="btn" onclick="permEdit('${escapeHtml(p.employeeNumber)}')" aria-expanded="${editing === p.employeeNumber}">${editing === p.employeeNumber ? '收起' : '調整'}</button>`}</div>
${editing === p.employeeNumber ? editor(p) : ''}
</div>`).join('') || '<div class="empty">沒有符合的人</div>';
}
function grantChips(entry) {
if (!entry) return [];
const out = [];
if (entry.denied) out.push(['warn', '暫不開放']);
const g = entry.grant || {};
if (g.company) out.push(['manual', '全公司檢視']);
(g.depts || []).forEach(d => out.push(['manual', `部門 ${d}`]));
(g.groups || []).forEach(k => out.push(['manual', `組 ${String(k).split('|')[1] || k}`]));
if (g.personDetail) out.push(['manual', '個人明細']);
if (g.simulate) out.push(['manual', '模擬']);
return out;
}
function drawLog() {
const box = document.getElementById('perm-log');
if (!box) return;
const log = state.log || [];
if (!log.length) { box.innerHTML = '<div class="empty">還沒有修改紀錄。</div>'; return; }
const names = new Map(state.people.map(p => [String(p.employeeNumber), p.name]));
const who = id => names.get(String(id)) ? `${escapeHtml(names.get(String(id)))}(${escapeHtml(id)})` : escapeHtml(id);
const chipHtml = (list, cls = '') => list.length ? list.map(([c, t]) => `<span class="chip ${c} ${cls}">${escapeHtml(t)}</span>`).join('') : '<span class="none">沒有手動權限</span>';
box.innerHTML = log.slice(0, logShown).map(e => {
const before = grantChips(e.before);
const after = grantChips(e.after);
const keys = list => new Set(list.map(([, t]) => t));
const a = keys(after);
const b = keys(before);
const removed = before.filter(([, t]) => !a.has(t));
const added = after.filter(([, t]) => !b.has(t));
const kept = after.filter(([, t]) => b.has(t));
const change = !removed.length && !added.length ? '<span class="none">沒有變更(重新儲存)</span>'
: `${removed.length ? `${chipHtml(removed, 'old')}<span class="arrow">→</span>` : ''}${added.length ? chipHtml(added) : '<span class="none">移除</span>'}${kept.length ? `<span class="none">(保留:${kept.map(([, t]) => escapeHtml(t)).join('、')})</span>` : ''}`;
return `<div class="log-row"><time datetime="${escapeHtml(e.at)}">${escapeHtml(new Date(e.at).toLocaleString('zh-TW', { hour12: false }))}</time>
<div><b>${who(e.employeeNumber)}</b></div>
<div class="change">${change}</div>
<div class="by">由 ${who(e.by)}</div></div>`;
}).join('') + (log.length > logShown ? `<div class="log-row" style="display:block;"><button type="button" class="btn" onclick="permMoreLog()">再顯示 ${Math.min(50, log.length - logShown)} 筆</button></div>` : '');
}
window.permFilter = (key) => { filter = key; draw(); };
window.permEdit = (id) => { editing = editing === id ? null : id; draw(); };
window.permCancel = () => { editing = null; draw(); };
window.permMoreLog = () => { logShown += 50; drawLog(); };
window.permDraw = draw;
window.permSave = async (id) => {
const box = document.getElementById('perm-editor');
const on = name => box.querySelector(`[name=${name}]`).checked;
const picked = name => [...box.querySelectorAll(`[name=${name}]:checked`)].map(i => i.value);
const grant = { company: on('company'), personDetail: on('personDetail'), simulate: on('simulate'), depts: picked('depts'), groups: picked('groups'), note: '權限頁設定' };
const empty = !grant.company && !grant.personDetail && !grant.simulate && !grant.depts.length && !grant.groups.length;
const response = await fetch('/api/permissions', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ employeeNumber: id, grant: empty ? null : grant, denied: on('denied') }) });
message[id] = response.ok ? '已儲存' : `儲存失敗(${response.status})`;
await window.permLoad();
};
window.permLoad = async () => {
const box = document.getElementById('perm-rows');
if (!box) return;
const response = await fetch('/api/permissions', { cache: 'no-store' });
if (!response.ok) { box.innerHTML = '<div class="empty">只有最高管理者可以管理權限。</div>'; return; }
state = await response.json();
drawLog();
if (state.preview && !state.people.length) { box.innerHTML = '<div class="empty">本機預覽沒有 HR 名單。</div>'; return; }
draw();
};
})();
// ---- 預排異動(預計離職、預計新進、預計轉調):只有最高管理者 ----
let planState = null;
const PLAN_STATUS = {
pending: ['等待 HR', 'var(--text-muted)'],
overdue: ['時間到了 HR 還沒改', 'var(--accent-danger)'],
conflict: ['HR 調到別的單位,請確認', 'var(--accent-warning)'],
manager_pending: ['部門已調,主管職還沒處理', 'var(--accent-warning)'],
};
const PLAN_REASON = {
hr_left: 'HR 名單上已經沒有這個人',
hr_leave_date: 'HR 已填離職日',
hr_joined: 'HR 名單已出現',
expired: '時間過了 HR 一直沒改,自動移除',
hr_transferred: 'HR 已經調到目標單位',
};
async function loadPlans() {
try {
const response = await fetch('/api/plans', { cache: 'no-store' });
if (!response.ok) { planState = null; return null; }
planState = await response.json();
} catch (error) { planState = null; }
updatePlanBanner();
return planState;
}
function updatePlanBanner() {
const overdue = planState?.status?.overdue || 0;
const conflicts = planState?.status?.conflicts || 0;
const managerPending = planState?.status?.managerPending || 0;
let note = document.getElementById('plan-overdue-banner');
if (!overdue && !conflicts && !managerPending) { if (note) note.remove(); return; }
if (!note) {
note = document.createElement('button');
note.id = 'plan-overdue-banner';
note.type = 'button';
note.onclick = () => showView('plans');
note.style.cssText = 'display:block;margin:.5rem 0;padding:.5rem .75rem;border-radius:10px;border:1px solid var(--accent-danger);background:none;color:var(--accent-danger);cursor:pointer;font-size:.85rem;text-align:left;';
document.getElementById('data-source-banner').after(note);
}
note.textContent = [overdue ? `有 ${overdue} 筆時間到了 HR 還沒更新,寬限期過後會自動移除` : '',
conflicts ? `有 ${conflicts} 筆 HR 調到別的單位,要你確認` : '',
managerPending ? `有 ${managerPending} 筆部門已經調了但主管職還沒處理` : ''].filter(Boolean).join(';');
note.textContent = `預排異動:${note.textContent} →`;
}
function planSummaryLine() {
const st = planState?.status;
const transfers = st?.transfers?.length || 0;
if (!st || (!st.departures.length && !st.hires.length && !transfers)) return '';
return `<div style="width:100%;font-size:.75rem;color:var(--accent-warning);">這次定錨包含預排異動:預計離職 ${st.departures.length} 位、預計新進 ${st.hires.length} 位、預計轉調 ${transfers} 位(在「預排異動」頁可以檢查)。</div>`;
}
function planStatusPill(status, autoRemoveAfter) {
const [label, color] = PLAN_STATUS[status] || [status, 'var(--text-muted)'];
const after = status === 'overdue' && autoRemoveAfter ? `<div style="font-size:.75rem;color:var(--text-dim);">${escapeHtml(autoRemoveAfter)} 之後自動移除</div>` : '';
return `<span style="font-size:.8rem;color:${color};">${escapeHtml(label)}</span>${after}`;
}
function planHistory(history) {
if (!history?.length) return '';
const cell = 'padding:.35rem .5rem;border-bottom:1px solid var(--border-color);text-align:left;';
return `<section class="card" style="padding:1.25rem;margin-top:1.5rem;">
<h2 style="font-size:1.1rem;margin:0 0 .25rem;">自動移除紀錄</h2>
<p style="font-size:.8rem;color:var(--text-dim);margin:0 0 .75rem;">HR 名單有結果之後,系統自動把預排移除,改用 HR 的資料(最近 30 筆)。</p>
<table style="width:100%;border-collapse:collapse;font-size:.85rem;">
<thead><tr><th style="${cell}">時間</th><th style="${cell}">類型</th><th style="${cell}">名稱</th><th style="${cell}">月份</th><th style="${cell}">原因</th></tr></thead>
<tbody>${history.map(h => `<tr>
<td style="${cell}">${escapeHtml(String(h.at || '').slice(0, 10))}</td>
<td style="${cell}">${h.kind === 'hire' ? '預計新進' : h.kind === 'transfer' ? '預計轉調' : '預計離職'}</td>
<td style="${cell}">${escapeHtml(h.label)}${h.matched ? `<div style="font-size:.75rem;color:var(--text-dim);">對到 ${escapeHtml(h.matched)}</div>` : ''}</td>
<td style="${cell}">${escapeHtml(h.month)}</td>
<td style="${cell}">${escapeHtml(PLAN_REASON[h.reason] || h.reason)}</td>
</tr>`).join('')}</tbody>
</table>
</section>`;
}
function renderPlans() {
const box = document.getElementById('plans-content');
if (!box) return;
if (!planState) { box.innerHTML = '<p style="color:var(--accent-danger);">預排異動讀取失敗,請重新整理。</p>'; return; }
const st = planState.status;
const hrPeople = baseData.filter(p => p.source === 'hr-sync').sort((a, b) => (a.dept || '').localeCompare(b.dept || '', 'zh-Hant') || (a.name || '').localeCompare(b.name || '', 'zh-Hant'));
const planned = new Set(planState.plans.departures.map(d => d.employeeNumber));
const moving = new Set((planState.plans.transfers || []).map(t => String(t.employeeNumber)));
const depts = [...new Set(baseData.filter(p => p.source !== 'planned' && p.dept).map(p => p.dept))].sort((a, b) => a.localeCompare(b, 'zh-Hant'));
const groups = [...new Set(baseData.filter(p => p.group).map(p => p.group))].sort();
const year = globalParams.reportYear || 2027;
const cell = 'padding:.45rem .5rem;border-bottom:1px solid var(--border-color);text-align:left;';
box.innerHTML = `
<section class="card" style="padding:1.25rem;margin-bottom:1.5rem;">
<h2 style="font-size:1.1rem;margin:0 0 .25rem;">預計離職</h2>
<p style="font-size:.8rem;color:var(--text-dim);margin:0 0 .75rem;">填「最後工作月份」。HR 名單上這個人不見了或填了離職日,系統會自動移除這一筆。在職月份會算到那個月為止;${year} 年 1 月前就走的,填 ${year - 1}-12(整年不算)。</p>
<table style="width:100%;border-collapse:collapse;font-size:.9rem;">
<thead><tr><th style="${cell}">姓名</th><th style="${cell}">部門/組</th><th style="${cell}">最後工作月份</th><th style="${cell}">備註</th><th style="${cell}">狀態</th><th style="${cell}"></th></tr></thead>
<tbody>${st.departures.length ? st.departures.map(d => `<tr>
<td style="${cell}">${escapeHtml(d.name || '(不在 HR 名單)')} <span style="color:var(--text-dim);font-size:.8rem;">${escapeHtml(d.employeeNumber)}</span></td>
<td style="${cell}">${escapeHtml([d.dept, shortGroupName(d.dept, d.group || '')].filter(Boolean).join(' / '))}</td>
<td style="${cell}">${escapeHtml(d.lastMonth)}</td>
<td style="${cell}">${escapeHtml(d.note)}</td>
<td style="${cell}">${planStatusPill(d.status, d.autoRemoveAfter)}</td>
<td style="${cell}"><button type="button" onclick="removePlan('departures','${escapeHtml(d.employeeNumber)}')" style="background:none;border:none;color:var(--accent-danger);cursor:pointer;">刪除</button></td>
</tr>`).join('') : `<tr><td colspan="6" style="${cell}color:var(--text-dim);">目前沒有預計離職。</td></tr>`}</tbody>
</table>
<div style="display:grid;grid-template-columns:minmax(220px,2fr) minmax(150px,1fr) minmax(200px,3fr) auto;gap:.5rem;align-items:center;margin-top:.75rem;">
<select id="plan-dep-person" aria-label="選擇人員">
<option value="">選擇人員…</option>
${hrPeople.filter(p => !planned.has(String(p.employeeNumber))).map(p => `<option value="${escapeHtml(p.employeeNumber)}">${escapeHtml(p.dept || '未歸部門')}|${escapeHtml(p.name)}(${escapeHtml(p.employeeNumber)})</option>`).join('')}
</select>
<input id="plan-dep-month" type="month" aria-label="最後工作月份" min="${year - 1}-12" max="${year}-12">
<input id="plan-dep-note" type="text" maxlength="200" placeholder="備註(只有你看得到)">
<button type="button" class="btn-primary" onclick="addDeparture()">+ 加入</button>
</div>
</section>
<section class="card" style="padding:1.25rem;">
<h2 style="font-size:1.1rem;margin:0 0 .25rem;">預計新進</h2>
<p style="font-size:.8rem;color:var(--text-dim);margin:0 0 .75rem;">名稱可以先寫職缺(例如「動畫師(2 月)」)。人到職、HR 名單出現同名或同部門、到職月份差不多的新人時,系統會自動移除這一筆,改用 HR 的資料。${year <= 2027 ? '2027 年的下半年(H2)跟其他人一樣先空白,下半年才開始的新進要等 H2 開放才會算進去。' : ''}</p>
<table style="width:100%;border-collapse:collapse;font-size:.9rem;">
<thead><tr><th style="${cell}">名稱</th><th style="${cell}">部門/組</th><th style="${cell}">職能</th><th style="${cell}">預估薪資</th><th style="${cell}">期間</th><th style="${cell}">備註</th><th style="${cell}">狀態</th><th style="${cell}"></th></tr></thead>
<tbody>${st.hires.length ? st.hires.map(h => `<tr>
<td style="${cell}">${escapeHtml(h.name)}${h.title ? `<div style="font-size:.75rem;color:var(--text-dim);">${escapeHtml(h.title)}</div>` : ''}</td>
<td style="${cell}">${escapeHtml([h.dept, shortGroupName(h.dept, h.group || '')].filter(Boolean).join(' / '))}</td>
<td style="${cell}">${escapeHtml(h.role.split(' - ')[0])}</td>
<td style="${cell}">${h.salaryType === 'hourly' ? '時薪 ' : '月薪 '}NT$ ${Number(h.amount).toLocaleString()}</td>
<td style="${cell}">${escapeHtml(h.startMonth)} 起${h.endMonth ? `,到 ${escapeHtml(h.endMonth)}` : ''}</td>
<td style="${cell}">${escapeHtml(h.note)}</td>
<td style="${cell}">${planStatusPill(h.status, h.autoRemoveAfter)}</td>
<td style="${cell}"><button type="button" onclick="removePlan('hires','${escapeHtml(h.id)}')" style="background:none;border:none;color:var(--accent-danger);cursor:pointer;">刪除</button></td>
</tr>`).join('') : `<tr><td colspan="8" style="${cell}color:var(--text-dim);">目前沒有預計新進。</td></tr>`}</tbody>
</table>
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(170px,1fr));gap:.5rem;margin-top:.75rem;">
<input id="plan-hire-name" type="text" maxlength="40" placeholder="名稱(例:動畫師 2 月)">
<input id="plan-hire-title" type="text" maxlength="80" placeholder="職稱(可不填)">
<select id="plan-hire-dept" aria-label="部門"><option value="">選擇部門…</option>${depts.map(d => `<option value="${escapeHtml(d)}">${escapeHtml(d)}</option>`).join('')}</select>
<input id="plan-hire-group" type="text" list="plan-group-list" maxlength="80" placeholder="組別(可不填)">
<datalist id="plan-group-list">${groups.map(g => `<option value="${escapeHtml(g)}">`).join('')}</datalist>
<select id="plan-hire-role" aria-label="職能"><option value="A - 藝術家">A 藝術家</option><option value="P - 製作">P 製作</option><option value="G - 營運支援">G 營運支援</option></select>
<select id="plan-hire-type" aria-label="薪資類型"><option value="monthly">月薪</option><option value="hourly">時薪</option></select>
<input id="plan-hire-amount" type="number" min="1" placeholder="預估薪資(NT$)">
<label style="font-size:.8rem;color:var(--text-dim);">開始月份<input id="plan-hire-start" type="month" min="${year}-01" max="${year}-12" style="width:100%;"></label>
<label style="font-size:.8rem;color:var(--text-dim);">結束月份(可不填)<input id="plan-hire-end" type="month" min="${year}-01" max="${year}-12" style="width:100%;"></label>
<input id="plan-hire-note" type="text" maxlength="200" placeholder="備註(只有你看得到)">
<button type="button" class="btn-primary" onclick="addHire()">+ 加入</button>
</div>
</section>
<section class="card" style="padding:1.25rem;margin-top:1.5rem;">
<h2 style="font-size:1.1rem;margin:0 0 .25rem;">預計轉調</h2>
<p style="font-size:.8rem;color:var(--text-dim);margin:0 0 .75rem;">填「生效月份」。${year} 年 1 月起就整年算新單位;生效月份在年度中間,成本會按月拆成兩段(前段原單位、後段新單位)。目標部門可以填 HR 還沒有的新部門。主管職預設轉調後卸任,可以指定原單位由誰接任,模擬就會照你設定的組織算。HR 把人調到目標單位、主管職也處理好之後,系統才會自動移除這一筆;只調了部門沒處理主管,會一直留著提醒;HR 要是調到別的地方,會標成「請確認」。主管職的設定只影響數字和模擬,不影響任何人在看板上看得到什麼,權限一律以 HR 為準。</p>
<table style="width:100%;border-collapse:collapse;font-size:.9rem;">
<thead><tr><th style="${cell}">姓名</th><th style="${cell}">HR 目前部門/組</th><th style="${cell}">調到</th><th style="${cell}">生效月份</th><th style="${cell}">主管職</th><th style="${cell}">備註</th><th style="${cell}">狀態</th><th style="${cell}"></th></tr></thead>
<tbody>${(st.transfers || []).length ? st.transfers.map(t => `<tr>
<td style="${cell}">${escapeHtml(t.name || '(不在 HR 名單)')} <span style="color:var(--text-dim);font-size:.8rem;">${escapeHtml(t.employeeNumber)}</span></td>
<td style="${cell}">${escapeHtml([t.dept, shortGroupName(t.dept, t.group || '')].filter(Boolean).join(' / ')) || '—'}</td>
<td style="${cell}">${escapeHtml([t.toDept, t.toGroup].filter(Boolean).join(' / '))}</td>
<td style="${cell}">${escapeHtml(t.effectiveMonth)}</td>
<td style="${cell}">${t.leads.length ? `${t.keepManager ? '保留' : '卸任'}(HR 目前:${escapeHtml(t.leads.join('、'))})` : t.keepManager ? '保留' : '—'}${t.successorEmployeeNumber ? `<div style="font-size:.75rem;color:var(--text-dim);">接任:${escapeHtml(t.successorName || t.successorEmployeeNumber)}${t.successorIsManager ? '' : '(HR 還沒設定)'}</div>` : ''}</td>
<td style="${cell}">${escapeHtml(t.note)}</td>
<td style="${cell}">${planStatusPill(t.status, t.autoRemoveAfter)}</td>
<td style="${cell}"><button type="button" onclick="removePlan('transfers','${escapeHtml(t.employeeNumber)}')" style="background:none;border:none;color:var(--accent-danger);cursor:pointer;">刪除</button></td>
</tr>`).join('') : `<tr><td colspan="8" style="${cell}color:var(--text-dim);">目前沒有預計轉調。</td></tr>`}</tbody>
</table>
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(170px,1fr));gap:.5rem;margin-top:.75rem;">
<select id="plan-tr-person" aria-label="選擇人員">
<option value="">選擇人員…</option>
${hrPeople.filter(p => !moving.has(String(p.employeeNumber))).map(p => `<option value="${escapeHtml(p.employeeNumber)}">${escapeHtml(p.dept || '未歸部門')}|${escapeHtml(p.name)}(${escapeHtml(p.employeeNumber)})</option>`).join('')}
</select>
<input id="plan-tr-dept" type="text" list="plan-dept-list" maxlength="80" placeholder="調到哪個部門">
<datalist id="plan-dept-list">${depts.map(d => `<option value="${escapeHtml(d)}">`).join('')}</datalist>
<input id="plan-tr-group" type="text" list="plan-group-list" maxlength="80" placeholder="組別(可不填)">
<label style="font-size:.8rem;color:var(--text-dim);">生效月份<input id="plan-tr-month" type="month" min="${year - 1}-01" max="${year + 1}-12" style="width:100%;"></label>
<select id="plan-tr-manager" aria-label="主管職"><option value="drop">轉調後卸任主管職</option><option value="keep">保留主管職</option></select>
<select id="plan-tr-successor" aria-label="原單位接任主管"><option value="">原單位接任主管…(可不填)</option>${hrPeople.map(p => `<option value="${escapeHtml(p.employeeNumber)}">${escapeHtml(p.dept || '未歸部門')}|${escapeHtml(p.name)}</option>`).join('')}</select>
<input id="plan-tr-note" type="text" maxlength="200" placeholder="備註(只有你看得到)">
<button type="button" class="btn-primary" onclick="addTransfer()">+ 加入</button>
</div>
</section>${planHistory(st.history)}`;
}
async function savePlans(next) {
try {
const response = await fetch('/api/plans', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(next) });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
planState = await response.json();
updatePlanBanner();
await loadBootstrapData();
saveAndRefresh();
renderPlans();
showSaved();
} catch (error) {
console.error('Unable to save plans', error);
alert('預排異動儲存失敗,請檢查欄位後再試。');
}
}
function addDeparture() {
const employeeNumber = document.getElementById('plan-dep-person').value;
const lastMonth = document.getElementById('plan-dep-month').value;
if (!employeeNumber || !lastMonth) { alert('請選擇人員和最後工作月份。'); return; }
const plans = planState.plans;
savePlans({ ...plans, departures: [...plans.departures, { employeeNumber, lastMonth, note: document.getElementById('plan-dep-note').value }] });
}
function addHire() {
const value = id => document.getElementById(id).value;
const hire = {
id: 'h' + Date.now().toString(36), name: value('plan-hire-name').trim(), title: value('plan-hire-title'),
dept: value('plan-hire-dept'), group: value('plan-hire-group'), role: value('plan-hire-role'),
salaryType: value('plan-hire-type'), amount: Number(value('plan-hire-amount')),
startMonth: value('plan-hire-start'), endMonth: value('plan-hire-end'), note: value('plan-hire-note'),
};
if (!hire.name || !hire.dept || !(hire.amount > 0) || !hire.startMonth) { alert('請填名稱、部門、預估薪資和開始月份。'); return; }
if (hire.endMonth && hire.endMonth < hire.startMonth) { alert('結束月份不能早於開始月份。'); return; }
const plans = planState.plans;
savePlans({ ...plans, hires: [...plans.hires, hire] });
}
function addTransfer() {
const value = id => document.getElementById(id).value;
const employeeNumber = value('plan-tr-person');
const toDept = value('plan-tr-dept').trim();
const effectiveMonth = value('plan-tr-month');
if (!employeeNumber || !toDept || !effectiveMonth) { alert('請選擇人員,並填目標部門和生效月份。'); return; }
const person = baseData.find(p => String(p.employeeNumber) === employeeNumber);
const toGroup = value('plan-tr-group').trim();
if (person && person.dept === toDept && (person.group || '') === toGroup) { alert('這個人已經在目標單位了。'); return; }
const keepManager = value('plan-tr-manager') === 'keep';
const successorEmployeeNumber = value('plan-tr-successor');
const leads = (person?.supervisorOf || []).map(unit => unit.deptName).filter(Boolean);
if (leads.length && !keepManager && !successorEmployeeNumber
&& !confirm(`${person.name} 目前是 ${leads.join('、')} 的主管。轉調後這些單位會沒有主管,而且你還沒指定接任者。要繼續嗎?`)) return;
const plans = planState.plans;
savePlans({ ...plans, transfers: [...(plans.transfers || []),
{ employeeNumber, toDept, toGroup, fromDept: person?.dept || '', effectiveMonth,
keepManager, successorEmployeeNumber, note: value('plan-tr-note') }] });
}
function removePlan(kind, key) {
const plans = planState.plans;
const next = { ...plans, [kind]: (plans[kind] || []).filter(item => (kind === 'hires' ? item.id : item.employeeNumber) !== key) };
savePlans(next);
}
function contractorPayload() {
// 只存看板維護的常態型外包;HR 的工讀生(也算 O)不寫進外包清單。
return baseData.filter(p => (p.role || '').startsWith('O') && p.source !== 'hr-sync').map(p => ({
@@ -5097,7 +5664,9 @@
});
const roles = globalParams.invoiceRoles || {};
return { rdGroups: [...(globalParams.rdGroups || [])], cgLeadGroups: [...(globalParams.cgLeadGroups || [])], params,
invoiceRoles: { companies: { ...(roles.companies || {}) }, depts: { ...(roles.depts || {}) } } };
invoiceRoles: { companies: { ...(roles.companies || {}) }, depts: { ...(roles.depts || {}) } },
// 還沒有編輯介面,原樣送回去,才不會被其他設定的存檔洗掉。
...(Array.isArray(globalParams.codaShareRules) ? { codaShareRules: globalParams.codaShareRules } : {}) };
}
function scheduleSettingsSave() {
@@ -5214,7 +5783,7 @@
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
const labels = {
access_denied: '目前登入的公司帳號不在 PM Board 的允許名單內。',
access_denied: '目前登入的公司帳號不在 LeadBoard 的允許名單內。',
hr_not_configured: '本站尚未收到平台提供的 HR Sync 執行期設定;因此沒有使用合成資料替代。',
hr_exchange_denied: '公司登入成功,但 HR Sync 未核准這個帳號的資料交換權限。',
hr_endpoint_forbidden: 'HR Sync 已連線,但拒絕目前要求的資料範圍。',
@@ -5258,12 +5827,22 @@
saveAndRefresh();
}
// 從網址帶進來的區塊(例如舊的 /permissions 會導成 /?view=permissions)。
function openViewFromUrl() {
const wanted = new URLSearchParams(location.search).get('view');
if (!wanted) return;
const target = document.getElementById(wanted);
if (target && target.classList.contains('view')) showView(wanted);
}
window.onload = async () => {
applyPreviewUI();
try {
if (!await applyLoginUI()) return;
if (!await loadBootstrapData()) return;
bootApp();
loadPlans();
openViewFromUrl();
} catch (error) {
console.error(error);
const banner = document.getElementById('data-source-banner');
+2 -1
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MoonShine PM Board · 我的範圍</title>
<title>MoonShine LeadBoard · 我的範圍</title>
<link rel="icon" href="/2022_Moonshine_Logo_MS_logo_w_EN.png">
<script>
// 日間/夜間:和主看板共用同一個設定(pmb-theme);沒選過就跟著系統。
@@ -40,6 +40,7 @@ h1 { font-size:1.5rem; margin:0; }
button:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }
@media (max-width: 600px) { .bar { justify-content:flex-start; } #year { text-align:left !important; } }
</style>
<link rel="stylesheet" href="/buttons.css">
</head>
<body>
<main>
-252
View File
@@ -1,252 +0,0 @@
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MoonShine PM Board · 權限管理</title>
<link rel="icon" href="/2022_Moonshine_Logo_MS_logo_w_EN.png">
<style>
:root {
--bg:#f5f4f0; --card:#ffffff; --raised:#fbfaf7; --text:#1d2025; --muted:#646b75; --dim:#8a9099; --line:#e6e2da;
--accent:#4a63e0; --accent-soft:rgba(74,99,224,.1); --warn:#b4540a; --warn-soft:rgba(180,84,10,.1); --good:#2f7d4f; --good-soft:rgba(47,125,79,.1); --on-accent:#fff;
}
@media (prefers-color-scheme: dark) {
:root { --bg:#141619; --card:#1c1f24; --raised:#22262c; --text:#eceef1; --muted:#a6acb5; --dim:#7d848d; --line:#2e333a;
--accent:#8fa2ff; --accent-soft:rgba(143,162,255,.14); --warn:#f0a35a; --warn-soft:rgba(240,163,90,.14); --good:#6fcf97; --good-soft:rgba(111,207,151,.14); --on-accent:#141619; }
}
* { box-sizing:border-box; }
body { margin:0; background:var(--bg); color:var(--text); font:15px/1.55 -apple-system, "PingFang TC", "Noto Sans TC", "Microsoft JhengHei", sans-serif; }
main { max-width:1080px; margin:0 auto; padding:28px 20px 80px; }
a.back { color:var(--muted); text-decoration:none; font-size:.85rem; }
a.back:hover { color:var(--text); }
h1 { font-size:1.6rem; margin:6px 0 6px; letter-spacing:.01em; }
.lead { color:var(--muted); font-size:.88rem; margin:0 0 20px; max-width:760px; }
.rules { display:grid; grid-template-columns:repeat(auto-fit, minmax(220px, 1fr)); gap:10px; margin-bottom:22px; }
.rule { background:var(--card); border:1px solid var(--line); border-radius:12px; padding:12px 14px; font-size:.82rem; color:var(--muted); }
.rule b { display:block; color:var(--text); font-size:.9rem; margin-bottom:2px; }
.toolbar { display:flex; gap:10px; flex-wrap:wrap; align-items:center; margin-bottom:12px; }
.search { flex:1; min-width:220px; font:inherit; padding:9px 12px; border:1px solid var(--line); border-radius:10px; background:var(--card); color:var(--text); }
.tabs { display:flex; gap:6px; flex-wrap:wrap; }
.tab { font:inherit; font-size:.82rem; border:1px solid var(--line); background:var(--card); color:var(--muted); border-radius:99px; padding:5px 12px; cursor:pointer; }
.tab[aria-pressed="true"] { background:var(--text); color:var(--bg); border-color:var(--text); }
.tab .n { opacity:.7; margin-left:4px; font-variant-numeric:tabular-nums; }
.list { background:var(--card); border:1px solid var(--line); border-radius:14px; overflow:hidden; }
.row { display:grid; grid-template-columns: minmax(170px, 1.1fr) minmax(130px, .8fr) minmax(220px, 1.6fr) 72px; gap:14px; align-items:center; padding:12px 16px; border-top:1px solid var(--line); }
.row:first-child { border-top:0; }
.who b { display:block; font-size:.95rem; }
.who span, .where span { color:var(--dim); font-size:.78rem; }
.where { font-size:.86rem; }
.chips { display:flex; flex-wrap:wrap; gap:5px; }
.chip { font-size:.75rem; padding:2px 9px; border-radius:99px; background:var(--raised); border:1px solid var(--line); color:var(--muted); white-space:nowrap; }
.chip.hr { background:var(--accent-soft); border-color:transparent; color:var(--accent); }
.chip.manual { background:var(--good-soft); border-color:transparent; color:var(--good); }
.chip.warn { background:var(--warn-soft); border-color:transparent; color:var(--warn); }
.chip.admin { background:var(--text); color:var(--bg); border-color:transparent; }
.none { color:var(--dim); font-size:.8rem; }
.btn { font:inherit; font-size:.82rem; border:1px solid var(--line); background:var(--card); color:var(--text); border-radius:8px; padding:6px 14px; cursor:pointer; white-space:nowrap; }
.btn:hover { background:var(--raised); }
.btn.primary { background:var(--accent); border-color:var(--accent); color:var(--on-accent); }
button:focus-visible, input:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }
.editor { grid-column:1 / -1; background:var(--raised); border:1px solid var(--line); border-radius:12px; padding:14px 16px; display:grid; gap:14px; }
.editor h4 { margin:0 0 6px; font-size:.8rem; color:var(--muted); font-weight:500; }
.toggles { display:flex; flex-wrap:wrap; gap:8px; }
.toggle { display:flex; gap:8px; align-items:flex-start; border:1px solid var(--line); background:var(--card); border-radius:10px; padding:8px 12px; cursor:pointer; font-size:.86rem; min-width:180px; }
.toggle small { display:block; color:var(--dim); font-size:.74rem; }
.toggle input { margin-top:3px; }
.pick { display:flex; flex-wrap:wrap; gap:6px; max-height:180px; overflow:auto; }
.pick label { font-size:.8rem; border:1px solid var(--line); background:var(--card); border-radius:99px; padding:3px 10px; cursor:pointer; display:flex; gap:5px; align-items:center; }
.pick label:has(input:checked) { background:var(--accent-soft); border-color:var(--accent); color:var(--accent); }
.pick input { margin:0; }
.actions { display:flex; gap:8px; justify-content:flex-end; align-items:center; }
.status { font-size:.8rem; color:var(--muted); margin-right:auto; }
.empty { padding:28px; text-align:center; color:var(--dim); }
.history { margin-top:28px; }
.history h2 { font-size:1.05rem; margin:0 0 4px; }
.history .lead { margin-bottom:10px; }
.log { background:var(--card); border:1px solid var(--line); border-radius:14px; overflow:hidden; }
.log-row { display:grid; grid-template-columns: 150px minmax(140px, .9fr) minmax(220px, 2fr) minmax(170px, .7fr); gap:12px; padding:10px 16px; border-top:1px solid var(--line); font-size:.85rem; align-items:start; }
.log-row:first-child { border-top:0; }
.log-row time { color:var(--dim); font-variant-numeric:tabular-nums; }
.log-row .by { color:var(--muted); }
.change { display:flex; flex-wrap:wrap; gap:4px; align-items:center; }
.change .arrow { color:var(--dim); margin:0 2px; }
.chip.old { text-decoration:line-through; opacity:.7; }
.more { display:block; margin:10px auto 0; }
@media (max-width: 760px) { .log-row { grid-template-columns: 1fr; gap:4px; } }
@media (max-width: 760px) {
.row { grid-template-columns: 1fr auto; gap:8px 12px; }
.row > .who { grid-column:1; grid-row:1; }
.row > .act { grid-column:2; grid-row:1; }
.row > .where, .row > .chips { grid-column:1 / -1; }
.where br { display:none; } .where span:not(:empty)::before { content:' · '; }
}
</style>
</head>
<body>
<main>
<a href="/" class="back">← 回到 PM Board</a>
<h1>權限管理</h1>
<p class="lead">HR 的主管會自動帶入權限;HR 拿掉主管身分,這些權限就自動消失。這裡加的是「手動」權限,要在這裡拿掉。只有最高管理者能改核心參數、按定錨、刪資料、管理權限。</p>
<div class="rules">
<div class="rule"><b>部主管(HR)</b>看部門、個人明細(含薪資)、部門模擬試算</div>
<div class="rule"><b>組主管(HR)</b>看自己組的實際 CODA、平均日 CODA、定錨 CODA</div>
<div class="rule"><b>手動加權限</b>全公司檢視、其他部門或組、個人明細、模擬</div>
</div>
<div class="toolbar">
<input class="search" id="q" type="search" placeholder="搜尋姓名、工號、部門、組" oninput="draw()" aria-label="搜尋">
<div class="tabs" id="tabs" role="group" aria-label="篩選"></div>
</div>
<div class="list" id="rows"><div class="empty">讀取中…</div></div>
<section class="history" aria-labelledby="history-title">
<h2 id="history-title">修改紀錄</h2>
<p class="lead">權限頁每次儲存都會留下紀錄:什麼時候、誰改的、改了誰、改前改後。紀錄不能刪除(最多保留最近 2000 筆,這裡顯示最近 200 筆)。</p>
<div class="log" id="log"><div class="empty">讀取中…</div></div>
</section>
</main>
<script>
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
let state = { people: [], grants: {}, denied: [] };
let filter = 'scoped';
let editing = null;
let message = {};
const kindOf = p => {
const x = p.permission;
if (x.admin) return 'admin';
if (x.denied || state.denied.includes(p.employeeNumber)) return 'denied';
if (x.company) return 'company';
if (x.hr?.depts?.length) return 'dept';
if (x.hr?.groups?.length) return 'group';
if (state.grants[p.employeeNumber]) return 'manual';
return 'none';
};
const FILTERS = [
['scoped', '有權限', p => kindOf(p) !== 'none'],
['dept', '部長', p => kindOf(p) === 'dept'],
['group', '組長', p => kindOf(p) === 'group'],
['company', '全公司檢視', p => kindOf(p) === 'company'],
['manual', '有手動權限', p => Boolean(state.grants[p.employeeNumber])],
['denied', '暫不開放', p => kindOf(p) === 'denied'],
['all', '全部', () => true],
];
function chips(p) {
const x = p.permission;
if (x.admin) return '<span class="chip admin">最高管理者</span>';
if (x.denied) return '<span class="chip warn">暫不開放</span>';
const g = state.grants[p.employeeNumber] || {};
const out = [];
if (x.company) out.push(['manual', '全公司檢視']);
(x.hr?.depts || []).forEach(d => out.push(['hr', `部門 ${d}`]));
(x.hr?.groups || []).forEach(k => out.push(['hr', `組 ${k.split('|')[1]}`]));
(g.depts || []).forEach(d => out.push(['manual', `部門 ${d}`]));
(g.groups || []).forEach(k => out.push(['manual', `組 ${k.split('|')[1]}`]));
if (x.personDetail) out.push([x.hr?.depts?.length ? 'hr' : 'manual', '個人明細']);
if (x.simulate) out.push([x.hr?.depts?.length ? 'hr' : 'manual', '模擬']);
return out.length ? out.map(([c, t]) => `<span class="chip ${c}">${esc(t)}</span>`).join('') : '<span class="none">沒有權限</span>';
}
function options() {
const depts = [...new Set(state.people.map(p => p.dept).filter(Boolean))].sort((a, b) => a.localeCompare(b, 'zh-Hant'));
const groups = [...new Set(state.people.filter(p => p.dept && p.group).map(p => `${p.dept}|${p.group}`))].sort((a, b) => a.localeCompare(b, 'zh-Hant'));
return { depts, groups };
}
function editor(p) {
const g = state.grants[p.employeeNumber] || {};
const { depts, groups } = options();
const toggle = (name, label, hint, checked) => `<label class="toggle"><input type="checkbox" name="${name}" ${checked ? 'checked' : ''}><span>${label}<small>${hint}</small></span></label>`;
return `<div class="editor" id="editor">
<div><h4>手動權限</h4><div class="toggles">
${toggle('company', '全公司檢視', '各部門、各組數字,不含個人薪資', g.company)}
${toggle('personDetail', '個人明細', '可看範圍內每個人的薪資與成本', g.personDetail)}
${toggle('simulate', '部門模擬', '可在看得到的部門做模擬試算', g.simulate)}
${toggle('denied', '暫不開放', '先不讓他看任何東西', state.denied.includes(p.employeeNumber))}
</div></div>
<div><h4>另外可以看的部門</h4><div class="pick">${depts.map(d => `<label><input type="checkbox" name="depts" value="${esc(d)}" ${(g.depts || []).includes(d) ? 'checked' : ''}>${esc(d)}</label>`).join('') || '<span class="none">沒有部門資料</span>'}</div></div>
<div><h4>另外可以看的組</h4><div class="pick">${groups.map(k => `<label><input type="checkbox" name="groups" value="${esc(k)}" ${(g.groups || []).includes(k) ? 'checked' : ''}>${esc(k.replace('|', ' · '))}</label>`).join('') || '<span class="none">沒有組資料</span>'}</div></div>
<div class="actions"><span class="status" role="status">${esc(message[p.employeeNumber] || '')}</span>
<button type="button" class="btn" onclick="editing=null;draw()">取消</button>
<button type="button" class="btn primary" onclick="save('${esc(p.employeeNumber)}')">儲存</button></div>
</div>`;
}
function draw() {
const q = document.getElementById('q').value.trim();
document.getElementById('tabs').innerHTML = FILTERS.map(([key, label, test]) =>
`<button type="button" class="tab" aria-pressed="${filter === key}" onclick="filter='${key}';draw()">${label}<span class="n">${state.people.filter(test).length}</span></button>`).join('');
const test = FILTERS.find(f => f[0] === filter)[2];
const rows = state.people.filter(test).filter(p => !q || [p.employeeNumber, p.name, p.dept, p.group].some(v => String(v || '').includes(q)));
document.getElementById('rows').innerHTML = rows.map(p => `<div class="row">
<div class="who"><b>${esc(p.name)}</b><span>${esc(p.employeeNumber)} ${esc(p.title)}</span></div>
<div class="where">${esc(p.dept || '—')}<br><span>${esc(p.group || '')}</span></div>
<div class="chips">${chips(p)}</div>
<div class="act">${p.permission.admin ? '' : `<button type="button" class="btn" onclick="editing=editing==='${esc(p.employeeNumber)}'?null:'${esc(p.employeeNumber)}';draw()" aria-expanded="${editing === p.employeeNumber}">${editing === p.employeeNumber ? '收起' : '調整'}</button>`}</div>
${editing === p.employeeNumber ? editor(p) : ''}
</div>`).join('') || '<div class="empty">沒有符合的人</div>';
}
async function save(id) {
const box = document.getElementById('editor');
const on = name => box.querySelector(`[name=${name}]`).checked;
const picked = name => [...box.querySelectorAll(`[name=${name}]:checked`)].map(i => i.value);
const grant = { company: on('company'), personDetail: on('personDetail'), simulate: on('simulate'), depts: picked('depts'), groups: picked('groups'), note: '權限頁設定' };
const empty = !grant.company && !grant.personDetail && !grant.simulate && !grant.depts.length && !grant.groups.length;
const response = await fetch('/api/permissions', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ employeeNumber: id, grant: empty ? null : grant, denied: on('denied') }) });
message[id] = response.ok ? '已儲存' : `儲存失敗(${response.status})`;
await load();
}
// 修改紀錄:每一筆的改前、改後轉成標籤。
let logShown = 20;
function grantChips(entry) {
if (!entry) return [];
const out = [];
if (entry.denied) out.push(['warn', '暫不開放']);
const g = entry.grant || {};
if (g.company) out.push(['manual', '全公司檢視']);
(g.depts || []).forEach(d => out.push(['manual', `部門 ${d}`]));
(g.groups || []).forEach(k => out.push(['manual', `組 ${String(k).split('|')[1] || k}`]));
if (g.personDetail) out.push(['manual', '個人明細']);
if (g.simulate) out.push(['manual', '模擬']);
return out;
}
function drawLog() {
const log = state.log || [];
const box = document.getElementById('log');
if (!log.length) { box.innerHTML = '<div class="empty">還沒有修改紀錄。</div>'; return; }
const names = new Map(state.people.map(p => [String(p.employeeNumber), p.name]));
const who = id => names.get(String(id)) ? `${esc(names.get(String(id)))}(${esc(id)})` : esc(id);
const chipHtml = (list, cls = '') => list.length ? list.map(([c, t]) => `<span class="chip ${c} ${cls}">${esc(t)}</span>`).join('') : '<span class="none">沒有手動權限</span>';
box.innerHTML = log.slice(0, logShown).map(e => {
const before = grantChips(e.before);
const after = grantChips(e.after);
const keys = list => new Set(list.map(([, t]) => t));
const a = keys(after);
const b = keys(before);
const removed = before.filter(([, t]) => !a.has(t));
const added = after.filter(([, t]) => !b.has(t));
const kept = after.filter(([, t]) => b.has(t));
const change = !removed.length && !added.length ? '<span class="none">沒有變更(重新儲存)</span>'
: `${removed.length ? `${chipHtml(removed, 'old')}<span class="arrow">→</span>` : ''}${added.length ? chipHtml(added) : '<span class="none">移除</span>'}${kept.length ? `<span class="none">(保留:${kept.map(([, t]) => esc(t)).join('、')})</span>` : ''}`;
return `<div class="log-row"><time datetime="${esc(e.at)}">${esc(new Date(e.at).toLocaleString('zh-TW', { hour12: false }))}</time>
<div><b>${who(e.employeeNumber)}</b></div>
<div class="change">${change}</div>
<div class="by">由 ${who(e.by)}</div></div>`;
}).join('') + (log.length > logShown ? `<div class="log-row" style="display:block;"><button type="button" class="btn more" onclick="logShown+=50;drawLog()">再顯示 ${Math.min(50, log.length - logShown)} 筆</button></div>` : '');
}
async function load() {
const response = await fetch('/api/permissions', { cache: 'no-store' });
if (response.status === 401) { location.href = '/api/auth/login'; return; }
if (!response.ok) { document.getElementById('rows').innerHTML = '<div class="empty">只有最高管理者可以管理權限。</div>'; return; }
state = await response.json();
drawLog();
if (state.preview && !state.people.length) { document.getElementById('rows').innerHTML = '<div class="empty">本機預覽沒有 HR 名單。</div>'; return; }
draw();
}
load();
</script>
</body>
</html>
+8 -10
View File
@@ -5,8 +5,7 @@
// HR 拿掉主管身分,這些權限就自動消失。
// - 權限頁手動設定(COST_MODEL_DATA_DIR/permissions.json,新檔案):要手動拿掉。
// 最高管理者(20150906)看得到全部,也是唯一能改核心參數、按定錨、刪資料、管理權限的人。
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
import { bindFile } from './storage.js';
import { splitOrganization } from './hr-org.js';
export const TOP_ADMIN = '20150906';
@@ -77,14 +76,16 @@ export function hasAnyScope(permission) {
return Boolean(permission && !permission.denied && (permission.admin || permission.company || permission.depts.length || permission.groups.length));
}
export function createPermissionStore(path) {
export function createPermissionStore(source) {
const file = bindFile(source);
let state = null;
let queue = Promise.resolve();
async function load() {
if (state) return state;
let saved = null;
if (path) {
try { saved = JSON.parse(await readFile(path, 'utf8')); } catch (error) { if (error.code !== 'ENOENT') throw error; }
if (file) {
const text = file.read();
if (text !== null) saved = JSON.parse(text);
}
state = saved && typeof saved === 'object'
? { grants: saved.grants || {}, denied: Array.isArray(saved.denied) ? saved.denied : [], log: saved.log || [] }
@@ -92,11 +93,8 @@ export function createPermissionStore(path) {
return state;
}
async function save() {
if (!path) return;
await mkdir(dirname(path), { recursive: true });
const temporary = `${path}.${process.pid}.tmp`;
await writeFile(temporary, `${JSON.stringify(state)}\n`, { mode: 0o600 });
await rename(temporary, path);
if (!file) return;
file.write(`${JSON.stringify(state)}\n`);
}
function serial(task) {
const run = queue.then(task, task);
+269
View File
@@ -0,0 +1,269 @@
// 預排異動(預計離職、預計新進、預計轉調)。存在 COST_MODEL_DATA_DIR/planned-changes.json(不進 Git),
// 只有最高管理者能看、能改。HR 還沒同步之前,先把已知的離職、新進排進試算,定錨時就會照這份算。
// - 預計離職:最後工作月份。在職月份以「HR 的在職期間」和「預排」較短的為準;HR 一有離職日就以 HR 為準。
// - 預計新進:先用一個名稱(不一定是真名)、部門、組、職能、預估薪資、開始月份加進名單。
// - 預計轉調:生效月份起算新部門/組。生效月份在報表年度中間就按月拆成兩段(前段原單位、後段新單位),
// 在報表年度之前就整年算新單位,在之後則先不套用。目標部門可以是 HR 還沒有的新部門。
// 主管職:預設轉調後卸任(keepManager 可保留);原單位可以指定接任者,模擬時就當成主管。
// 這只影響數字與模擬,不影響看板權限(權限一律以 HR 的主管關係為準)。
// 部長在 /my 看到的是套用預排之後的數字(不顯示原因);所有計算都用同一份資料,定錨的最高點才不會被墊高。
// 自動核對(reconcilePlans):HR 名單一出現結果(離職的人不在名單上或有離職日、新人出現在名單上)就自動移除那一筆;
// 時間過了 HR 還沒改,寬限 1 個月後也自動移除。移除紀錄留在 history 給最高管理者看。
import { bindFile } from './storage.js';
import { personKey, splitTransfers } from './anchor-calc.js';
import { boundMonths, toCostPerson } from './cost-model.js';
const MONTH = /^(\d{4})-(0[1-9]|1[0-2])$/;
const ROLES = ['A - 藝術家', 'P - 製作', 'G - 營運支援'];
const MAX = 300;
const text = (value, max = 80) => (typeof value === 'string' ? value.replace(/\s+/g, ' ').trim().slice(0, max) : '');
const monthOf = (value) => (MONTH.test(text(value)) ? text(value) : '');
export function normalizePlans(input = {}) {
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new TypeError('plans must be an object');
const array = (value) => {
if (value === undefined) return [];
if (!Array.isArray(value)) throw new TypeError('plans list must be an array');
return value.slice(0, MAX);
};
const seen = new Set();
const departures = [];
for (const item of array(input.departures)) {
const employeeNumber = text(String(item?.employeeNumber ?? ''), 40);
const lastMonth = monthOf(item?.lastMonth);
if (!/^[A-Za-z0-9_-]{1,40}$/.test(employeeNumber) || !lastMonth || seen.has(employeeNumber)) throw new RangeError('invalid departure');
seen.add(employeeNumber);
departures.push({ employeeNumber, lastMonth, note: text(item.note, 200), createdAt: text(item.createdAt, 40) || new Date().toISOString() });
}
const ids = new Set();
const hires = [];
for (const item of array(input.hires)) {
const id = text(String(item?.id ?? ''), 40);
const name = text(item?.name, 40);
const dept = text(item?.dept);
const startMonth = monthOf(item?.startMonth);
const endMonth = item?.endMonth ? monthOf(item.endMonth) : '';
const amount = Number(item?.amount);
const salaryType = item?.salaryType === 'hourly' ? 'hourly' : 'monthly';
if (!/^[A-Za-z0-9_-]{1,40}$/.test(id) || ids.has(id) || !name || !dept || !startMonth || !ROLES.includes(item?.role)
|| !(Number.isFinite(amount) && amount > 0 && amount < 10_000_000) || (item?.endMonth && (!endMonth || endMonth < startMonth))) {
throw new RangeError('invalid hire');
}
ids.add(id);
hires.push({ id, name, title: text(item.title), dept, group: text(item.group), role: item.role, salaryType, amount: Math.round(amount),
startMonth, endMonth, note: text(item.note, 200), createdAt: text(item.createdAt, 40) || new Date().toISOString() });
}
const moved = new Set();
const transfers = [];
for (const item of array(input.transfers)) {
const employeeNumber = text(String(item?.employeeNumber ?? ''), 40);
const toDept = text(item?.toDept);
const effectiveMonth = monthOf(item?.effectiveMonth);
if (!/^[A-Za-z0-9_-]{1,40}$/.test(employeeNumber) || !toDept || !effectiveMonth || moved.has(employeeNumber)) throw new RangeError('invalid transfer');
moved.add(employeeNumber);
const successor = text(String(item?.successorEmployeeNumber ?? ''), 40);
if (successor && (!/^[A-Za-z0-9_-]{1,40}$/.test(successor) || successor === employeeNumber)) throw new RangeError('invalid transfer');
transfers.push({ employeeNumber, toDept, toGroup: text(item.toGroup), fromDept: text(item.fromDept), effectiveMonth,
keepManager: item?.keepManager === true, successorEmployeeNumber: successor,
note: text(item.note, 200), createdAt: text(item.createdAt, 40) || new Date().toISOString() });
}
const REASONS = ['hr_left', 'hr_leave_date', 'hr_joined', 'hr_transferred', 'expired', 'manual'];
const history = (Array.isArray(input.history) ? input.history : []).slice(-100).flatMap((entry) => {
if (!entry || !['departure', 'hire', 'transfer'].includes(entry.kind) || !REASONS.includes(entry.reason)) return [];
return [{ kind: entry.kind, reason: entry.reason, label: text(entry.label, 80), month: monthOf(entry.month),
matched: text(entry.matched, 80), at: text(entry.at, 40) }];
});
return { departures, hires, transfers, history };
}
const addMonths = (month, n) => {
const [y, m] = month.split('-').map(Number);
const total = y * 12 + (m - 1) + n;
return `${Math.floor(total / 12)}-${String((total % 12) + 1).padStart(2, '0')}`;
};
const monthNow = (now) => `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
export const GRACE_MONTHS = 1;
// 新人比對:同名,或同部門、HR 到職月份在預排開始月份前後 1 個月內。一個 HR 的人只配一筆預排。
function matchHires(hires, hrPeople) {
const used = new Set();
const matches = new Map();
const pick = (hire, test) => {
const person = hrPeople.find(p => !used.has(String(p.employeeNumber)) && test(p));
if (person) { used.add(String(person.employeeNumber)); matches.set(hire.id, person); }
};
for (const hire of hires) pick(hire, p => p.name === hire.name && (!p.dept || p.dept === hire.dept));
for (const hire of hires) {
if (matches.has(hire.id)) continue;
// 預排建立之前就到職的人不算(他們本來就在名單上)。
const created = monthOf(String(hire.createdAt || '').slice(0, 7));
const lo = [addMonths(hire.startMonth, -1), created].filter(Boolean).sort().pop();
const hi = addMonths(hire.startMonth, 1);
pick(hire, p => p.dept === hire.dept && p.hireDate && String(p.hireDate).slice(0, 7) >= lo && String(p.hireDate).slice(0, 7) <= hi);
}
return matches;
}
// 主管職是否已經照預排處理:本人的主管身分符合預排,指定的接任者在 HR 也已經是主管。
function managerSettled(plan, person, hr) {
if (Boolean(person?.isManager) !== Boolean(plan.keepManager)) return false;
if (!plan.successorEmployeeNumber) return true;
return Boolean(hr.get(String(plan.successorEmployeeNumber))?.isManager);
}
// 拿目前 HR 名單核對預排,回傳要留下的預排和這次自動移除的紀錄。HR 名單是空的(例如 HR 暫時連不上)就不動。
export function reconcilePlans(plans, people, now = new Date()) {
const hrPeople = (people || []).filter(p => p.source === 'hr-sync');
if (!hrPeople.length) return { plans, removed: [] };
const thisMonth = monthNow(now);
const at = now.toISOString();
const hr = new Map(hrPeople.map(p => [String(p.employeeNumber), p]));
const removed = [];
const departures = (plans.departures || []).filter((plan) => {
const person = hr.get(plan.employeeNumber);
const reason = !person ? 'hr_left' : person.leaveDate ? 'hr_leave_date'
: thisMonth > addMonths(plan.lastMonth, GRACE_MONTHS) ? 'expired' : null;
if (reason) removed.push({ kind: 'departure', reason, label: person?.name || plan.employeeNumber, month: plan.lastMonth, matched: '', at });
return !reason;
});
const matches = matchHires(plans.hires || [], hrPeople);
const hires = (plans.hires || []).filter((plan) => {
const person = matches.get(plan.id);
const reason = person ? 'hr_joined' : thisMonth > addMonths(plan.startMonth, GRACE_MONTHS) ? 'expired' : null;
if (reason) removed.push({ kind: 'hire', reason, label: plan.name, month: plan.startMonth, matched: person ? `${person.name}(${person.employeeNumber})` : '', at });
return !reason;
});
// 轉調:HR 的部門(有填組就連組)變成目標單位就算完成;人不在名單上或過了寬限期也移除。
const transfers = (plans.transfers || []).filter((plan) => {
const person = hr.get(plan.employeeNumber);
const movedDept = Boolean(person) && String(person.dept || '').trim() === plan.toDept
&& (!plan.toGroup || String(person.group || '').trim() === plan.toGroup);
const arrived = movedDept && managerSettled(plan, person, hr);
// 部門對了但主管還沒處理:留著提醒,不讓它過期被默默移除。
const reason = !person ? 'hr_left' : arrived ? 'hr_transferred'
: movedDept ? null
: thisMonth > addMonths(plan.effectiveMonth, GRACE_MONTHS) ? 'expired' : null;
if (reason) {
removed.push({ kind: 'transfer', reason, label: person?.name || plan.employeeNumber, month: plan.effectiveMonth,
matched: person ? `${person.dept || ''}${person.group ? ' / ' + person.group : ''}` : '', at });
}
return !reason;
});
if (!removed.length) return { plans, removed };
return { plans: { departures, hires, transfers, history: [...(plans.history || []), ...removed].slice(-100) }, removed };
}
// 把預排套到看板名單上(只套在名單層,不改 HR 資料)。
export function applyPlans(people, plans, { year, fullYearDefault = false } = {}) {
if (!plans || (!plans.departures?.length && !plans.hires?.length && !plans.transfers?.length)) return people;
const leaving = new Map((plans.departures || []).map(d => [String(d.employeeNumber), d]));
const out = people.map((person) => {
const plan = person.source === 'hr-sync' ? leaving.get(String(person.employeeNumber)) : null;
if (!plan) return person;
const months = boundMonths({ h1Start: person.h1Start, h1End: person.h1End, h2Start: person.h2Start, h2End: person.h2End }, null, `${plan.lastMonth}-01`, year);
return { ...person, h1Start: months.h1Start, h1End: months.h1End, h2Start: months.h2Start, h2End: months.h2End,
employmentBounded: person.employmentBounded || months.bounded, plannedLeave: plan.lastMonth };
});
for (const hire of plans.hires || []) {
const company = people.find(p => p.dept === hire.dept && p.company)?.company || '';
const person = toCostPerson({
employeeNumber: `PLAN-${hire.id}`, name: hire.name, positionName: hire.title, corporationName: company,
departmentName: hire.dept, groupName: hire.group, hireDate: `${hire.startMonth}-01`,
leaveDate: hire.endMonth ? `${hire.endMonth}-01` : '', status: 'PLANNED', supervisorOf: [],
}, { amount: hire.amount, salaryType: hire.salaryType }, { role: hire.role }, { year, fullYearDefault });
out.push({ ...person, row: `PLAN-${hire.id}`, source: 'planned', plannedHire: hire.startMonth, planId: hire.id });
}
// 預計轉調:生效月份在報表年度之後先不套用;在之前就整年算新單位;年度中間則按月拆成兩段。
if (!plans.transfers?.length) return out;
const moving = new Map(plans.transfers.map(plan => [String(plan.employeeNumber), plan]));
const splits = [];
// 接任者:原單位由誰接主管(簡化為整年都算主管,一月生效的轉調本來就一致)。
const successors = new Map(plans.transfers.filter(plan => plan.successorEmployeeNumber)
.map(plan => [String(plan.successorEmployeeNumber), plan]));
const managerBefore = new Map();
const moved = out.map((person) => {
if (person.source === 'hr-sync' && successors.has(String(person.employeeNumber))) {
return { ...person, isManager: true, plannedManager: true };
}
const plan = person.source === 'hr-sync' ? moving.get(String(person.employeeNumber)) : null;
if (!plan) return person;
const [planYear, planMonth] = plan.effectiveMonth.split('-').map(Number);
if (Number.isFinite(year) && planYear > year) return person;
const month = !Number.isFinite(year) || planYear < year ? 1 : planMonth;
if (month > 1) {
splits.push({ key: personKey(person), from: { dept: person.dept, group: person.group }, month });
managerBefore.set(personKey(person), { isManager: person.isManager, supervisorOf: person.supervisorOf });
}
const manager = plan.keepManager
? { isManager: person.isManager, supervisorOf: person.supervisorOf }
: { isManager: false, supervisorOf: [] };
return { ...person, dept: plan.toDept, group: plan.toGroup, plannedTransfer: plan.effectiveMonth, ...manager };
});
// 拆成兩段時,生效月份之前還是原單位的主管。
return splitTransfers(moved, splits).map((person) => {
if (person.transferSplit !== 'before') return person;
const before = managerBefore.get(personKey(person));
return before ? { ...person, ...before } : person;
});
}
// 每一筆預排目前的狀態(給你看:等待中/HR 已完成/過期未完成)。
export function planStatus(plans, people, now = new Date()) {
const thisMonth = monthNow(now);
const hr = new Map(people.filter(p => p.source === 'hr-sync').map(p => [String(p.employeeNumber), p]));
const departures = (plans.departures || []).map((plan) => {
const person = hr.get(plan.employeeNumber);
const status = thisMonth > plan.lastMonth ? 'overdue' : 'pending';
return { ...plan, name: person?.name || '', dept: person?.dept || '', group: person?.group || '', status,
autoRemoveAfter: addMonths(plan.lastMonth, GRACE_MONTHS) };
});
const hires = (plans.hires || []).map((plan) => ({ ...plan, status: thisMonth > plan.startMonth ? 'overdue' : 'pending',
autoRemoveAfter: addMonths(plan.startMonth, GRACE_MONTHS) }));
// HR 把人調到「原單位和目標單位以外」的地方=衝突,留著讓最高管理者自己判斷,不自動移除。
const transfers = (plans.transfers || []).map((plan) => {
const person = hr.get(plan.employeeNumber);
const current = String(person?.dept || '').trim();
const conflict = Boolean(person) && Boolean(plan.fromDept) && Boolean(current)
&& current !== plan.fromDept && current !== plan.toDept;
const movedDept = Boolean(person) && current === plan.toDept
&& (!plan.toGroup || String(person.group || '').trim() === plan.toGroup);
const status = conflict ? 'conflict'
: movedDept && !managerSettled(plan, person, hr) ? 'manager_pending'
: thisMonth > plan.effectiveMonth ? 'overdue' : 'pending';
const successor = plan.successorEmployeeNumber ? hr.get(String(plan.successorEmployeeNumber)) : null;
return { ...plan, name: person?.name || '', dept: current, group: person?.group || '', status,
isManager: Boolean(person?.isManager), leads: (person?.supervisorOf || []).map(unit => unit.deptName).filter(Boolean),
successorName: successor?.name || '', successorIsManager: Boolean(successor?.isManager),
autoRemoveAfter: addMonths(plan.effectiveMonth, GRACE_MONTHS) };
});
return { departures, hires, transfers, history: [...(plans.history || [])].reverse().slice(0, 30),
overdue: [...departures, ...hires, ...transfers].filter(p => p.status === 'overdue').length,
conflicts: transfers.filter(p => p.status === 'conflict').length,
managerPending: transfers.filter(p => p.status === 'manager_pending').length };
}
export function createPlanStore(source) {
const file = bindFile(source);
let state = null;
let queue = Promise.resolve();
return {
async load() {
if (state) return state;
state = { departures: [], hires: [], transfers: [], history: [] };
const text = file ? file.read() : null;
if (text !== null) state = normalizePlans(JSON.parse(text));
return state;
},
save(input) {
let next;
try { next = normalizePlans(input); } catch (error) { return Promise.reject(error); }
const run = queue.then(async () => {
file?.write(JSON.stringify(next, null, 2));
state = next;
return next;
});
queue = run.catch(() => {});
return run;
},
};
}
+13 -2
View File
@@ -161,6 +161,14 @@
// 區塊:沿用主看板的底色(CODA 藍、發票琥珀、組別綠灰),前後深淺交錯。
const block = (kind, title, body) => `<div class="sx-block b-${kind}"><div class="sx-bh"><span class="sx-dot"></span>${title}</div>${body}</div>`;
// 人員異動:只給姓名和生效月份。不分離職或轉調,也不說轉調去哪,部長只需要知道編制什麼時候變。
function changesTable(list) {
const rows = list.map(c => `<tr><td>${esc(c.name)}</td><td>${c.kind === 'leave' ? '離開本部門' : '加入本部門'}</td><td class="num">${esc(c.month)}</td></tr>`).join('');
return `<div class="sx-scroll"><table><thead><tr><th>姓名</th><th>異動</th><th class="num">生效月份</th></tr></thead><tbody>${rows}</tbody></table></div>
<div class="sx-sub" style="margin-top:4px;">已經排定、HR 還沒更新的異動。上面的數字已經照這些算了。</div>`;
}
function deptCard(d, data, simOpen) {
const showCost = d.groups.some(g => typeof g.totalCost === 'number');
const groupsRows = d.groups.map(g => g.missing ? `<tr><td>${esc(g.group)}</td><td colspan="${showCost ? 5 : 4}" class="sx-sub">目前沒有資料</td></tr>` :
@@ -177,6 +185,7 @@
${kpi(d.multiplier?.company ? `倍率(${esc(d.multiplier.company)}全公司)` : '部門倍率', times(d.multiplier?.value), '部門內部成本(P+A+G,不含外包)÷ A 成本 × 人薪倍率')}
</div>`)}
${d.invoice?.indicators ? block('inv2', '發票佔比怎麼來的', indicatorsBlock(d)) : ''}
${d.changes && d.changes.length ? block('chg', '人員異動', changesTable(d.changes)) : ''}
${block('people', '人力', `<div class="sx-kpis">
${d.headcount ? kpi('人數', `${d.headcount.total} 人`, headcountText(d.headcount)) : ''}
${typeof d.totalCost === 'number' ? kpi('部門總人力成本(年)', money(d.totalCost), '正職年薪 × 人薪倍率 + 外包 × 外包倍率,不含實習生') : ''}
@@ -187,7 +196,7 @@
${block('group', '各組', `<div class="sx-scroll"><table><thead><tr><th>組</th><th class="num">人數</th><th class="num">實際 CODA</th><th class="num">平均日 CODA</th><th class="num">定錨 CODA</th>${showCost ? '<th class="num">總人力成本(年)</th>' : ''}</tr></thead><tbody>${groupsRows}</tbody></table></div>
${showCost ? '<div class="sx-sub" style="margin-top:4px;">人數是算 CODA 的人(A 與外包);總人力成本含組內所有人(含 P、外包,不含實習生)。</div>' : ''}`)}
${data.me.simulate && d.full ? simSection(d, simOpen) : ''}
${d.people && mode === 'page' ? `<details data-key="people|${esc(d.dept)}" ${isOpen(`people|${d.dept}`, false) ? 'open' : ''}><summary>個人明細(${d.people.length} 人)</summary><div style="margin:8px 0;">${salaryButton('顯示薪資', '隱藏薪資')}</div>${peopleTable(d.people)}</details>` : ''}
${d.people && mode === 'page' ? `<details data-key="people|${esc(d.dept)}" ${isOpen(`people|${d.dept}`, false) ? 'open' : ''}><summary>個人明細(${d.people.length} 人)</summary>${peopleTable(d.people)}</details>` : ''}
</section>`;
}
@@ -318,6 +327,8 @@
}
const parts = [];
if (data.company) parts.push(`<div class="sx-card"><h2>全公司</h2>${block('inv', '發票', `<div class="sx-kpis"><div class="sx-kpi"><div class="label">年度發票目標</div><div class="value">${money(data.company.invoiceTotal)}</div></div></div><div class="sx-sub">全公司沒有定錨 CODA 合計(調動時原單位不降、新單位增加,加總會重複)。</div>`)}</div>`);
// 「顯示薪資」放在整頁最上面,部長一進來就找得到(按一下,頁面上所有人的薪資一起顯示)。
if (data.depts.some(d => d.people)) parts.unshift(`<div class="sx-row" style="margin:0 0 8px;">${salaryButton('顯示薪資', '隱藏薪資')}</div>`);
for (const d of data.depts) parts.push(deptCard(d, data, false));
if (!data.depts.length && !data.company) parts.push('<div class="sx-card">目前沒有可以看的部門或組別。</div>');
root.innerHTML = parts.join('');
@@ -415,7 +426,7 @@
const data = await response.json().catch(() => ({}));
if (!response.ok) {
if (onMeta) onMeta(null, data);
root.innerHTML = `<div class="sx-card">${data.error === 'no_permission' ? '你目前沒有 PM Board 的檢視權限。需要的話請找管理者開通。' : '資料讀取失敗,請稍後重新整理。'}</div>`;
root.innerHTML = `<div class="sx-card">${data.error === 'no_permission' ? '你目前沒有 LeadBoard 的檢視權限。需要的話請找管理者開通。' : '資料讀取失敗,請稍後重新整理。'}</div>`;
return;
}
if (window.PMI18n) PMI18n.setRate(data.usdRate);
+24 -1
View File
@@ -66,7 +66,29 @@ function anchoredGroup(anchors, dept, group) {
return g ? { annual: round(g.value), h1: round(g.h1), h2: g.h2 === null ? null : round(g.h2) } : null;
}
export function buildScopedView(model, anchors, permission, { year } = {}) {
// 部長看得到的人員異動:誰離開、誰加入、哪個月生效。
// 刻意不分離職或轉調,也不顯示轉調去哪裡,部長只需要知道編制什麼時候變。
// 只掛在看得到整個部門的人身上;只看單一組別的人不給,免得看到別組的人。
export function changesFor(dept, model, plans) {
const name = (employeeNumber) => (model.people || [])
.find(p => String(p.employeeNumber || '') === String(employeeNumber))?.name || '';
const out = [];
for (const person of model.people || []) {
if (String(person.dept || '').trim() !== dept) continue;
if (person.plannedLeave) out.push({ kind: 'leave', name: person.name || '', month: person.plannedLeave });
// 拆成兩段時,前段掛在原部門,那是「離開」不是「加入」(下面用 fromDept 處理)。
if (person.plannedTransfer && person.transferSplit !== 'before') out.push({ kind: 'join', name: person.name || '', month: person.plannedTransfer });
if (person.plannedHire) out.push({ kind: 'join', name: person.name || '', month: person.plannedHire });
}
for (const plan of plans?.transfers || []) {
if (String(plan.fromDept || '').trim() !== dept) continue;
out.push({ kind: 'leave', name: name(plan.employeeNumber), month: plan.effectiveMonth });
}
return out.filter(change => change.name && change.month)
.sort((a, b) => String(a.month).localeCompare(String(b.month)) || a.name.localeCompare(b.name, 'zh-Hant'));
}
export function buildScopedView(model, anchors, permission, { year, plans } = {}) {
const allDepts = Object.keys(model.codaGroups || {});
const fullDepts = permission.admin || permission.company ? allDepts : allDepts.filter(d => permission.depts.includes(d));
const groupOnly = permission.groups.map(key => key.split('|')).filter(([d]) => !fullDepts.includes(d));
@@ -86,6 +108,7 @@ export function buildScopedView(model, anchors, permission, { year } = {}) {
multiplier: multiplierFor(model, dept),
headcount: headcountByKind(model.people.filter(p => (p.dept || '').trim() === dept)),
totalCost: round(model.staffCost?.depts?.[dept]),
changes: changesFor(dept, model, plans),
anchoredInvoice: anchoredInvoice ? { annual: round(anchoredInvoice.annual), h1: round(anchoredInvoice.h1), h2: anchoredInvoice.h2 === null ? null : round(anchoredInvoice.h2) } : null,
groups: Object.entries(data.groups).map(([group, g]) => ({
group, actualCoda: round(g.coda), avgDailyCoda: round(g.avgDailyCoda), headcount: g.people.length,
+127 -133
View File
@@ -1,6 +1,6 @@
import { createHash, createPublicKey, randomBytes, verify } from 'node:crypto';
import { createServer } from 'node:http';
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import { readFile } from 'node:fs/promises';
import { extname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { canAccess, isTopAdmin } from './access.js';
@@ -9,16 +9,19 @@ import { splitOrganization, supervisorIndex } from './hr-org.js';
import { normalizeOverride, toCostPerson } from './cost-model.js';
import { normalizeContractors } from './contractor-store.js';
import { applySettings, normalizeSettings } from './settings-store.js';
import { englishNameMap, normalizeEnglishNames } from './english-names.js';
import { englishNameMap, normalizeEnglishNames, visiblePeople } from './english-names.js';
import { applyPlans, createPlanStore, planStatus, reconcilePlans } from './plans.js';
import { computeModel } from './calc-engine.js';
import { createAnchorStore } from './anchor-store.js';
import { splitTransfers } from './anchor-calc.js';
import { createPermissionStore, hasAnyScope, resolvePermissions } from './permissions.js';
import { buildScopedView } from './scope-view.js';
import { applySimulation, compareDept } from './simulate.js';
import { ApiError, buildExternal, verifyApiToken } from './external-api.js';
import { API_ISSUER, API_JWKS_URI, ApiError, buildExternal, verifyApiToken } from './external-api.js';
import { buildArchive, createArchiveStore } from './archive-store.js';
import { createSessionStore } from './session-store.js';
import { openDataStorage } from './data-store.js';
import { bind, prefixed } from './storage.js';
const root = fileURLToPath(new URL('.', import.meta.url));
const port = Number(process.env.PORT || 8080);
@@ -30,62 +33,47 @@ const demoPath = resolve(root, 'seed/demo.json');
// Local preview only: DEMO_DATA_FILE swaps in a fake roster. Production always reads the seed.
const previewDataPath = !isProduction && process.env.DEMO_DATA_FILE ? resolve(root, process.env.DEMO_DATA_FILE) : demoPath;
const costModelDataDir = process.env.COST_MODEL_DATA_DIR;
const costOverridesPath = costModelDataDir ? resolve(costModelDataDir, 'cost-overrides.json') : null;
const contractorsPath = costModelDataDir ? resolve(costModelDataDir, 'contractors.json') : null;
const settingsPath = costModelDataDir ? resolve(costModelDataDir, 'board-settings.json') : null;
const englishNamesPath = costModelDataDir ? resolve(costModelDataDir, 'english-names.json') : null;
// 目前年度(新檔案)。預設 2027;年底封存後由最高管理者按「開始下一年」。
// 所有存檔(成本覆寫、外包、設定、權限、定錨、封存、預排、登入狀態…)都存在 COST_MODEL_DATA_DIR/leadboard.db(SQLite)。
// 第一次啟動會把資料夾裡原有的 JSON 搬進去並逐筆核對(JSON 不會被刪);STORAGE_BACKEND=json 可以退回舊的 JSON 檔存法。
const storage = openDataStorage(costModelDataDir);
// 目前年度(current-year.json)。預設 2027;年底封存後由最高管理者按「開始下一年」。
const FIRST_YEAR = 2027;
const currentYearPath = costModelDataDir ? resolve(costModelDataDir, 'current-year.json') : null;
let currentYearState;
async function getCurrentYear() {
if (currentYearState === undefined) {
currentYearState = { year: FIRST_YEAR, log: [] };
if (currentYearPath) {
try { currentYearState = JSON.parse(await readFile(currentYearPath, 'utf8')); } catch (error) { if (error.code !== 'ENOENT') throw error; }
}
const text = storage?.read('current-year.json');
if (text != null) currentYearState = JSON.parse(text);
}
return Number(currentYearState.year) || FIRST_YEAR;
}
async function startYear(year, by) {
await getCurrentYear();
currentYearState = { year, log: [...(currentYearState.log || []), { year, by, at: new Date().toISOString() }] };
if (!currentYearPath) return;
await mkdir(costModelDataDir, { recursive: true });
const temporaryPath = `${currentYearPath}.${process.pid}.tmp`;
await writeFile(temporaryPath, JSON.stringify(currentYearState), { mode: 0o600 });
await rename(temporaryPath, currentYearPath);
storage?.write('current-year.json', JSON.stringify(currentYearState));
}
// 2028 起:在職月份每年各自設定(month-overrides-<年>.json,新檔案),預設全年再依 HR 到職/離職限縮;
// 2028 起:在職月份每年各自設定(month-overrides-<年>.json),預設全年再依 HR 到職/離職限縮;
// 職能等其他設定沿用 cost-overrides.json。
const monthFields = new Set(['h1Start', 'h1End', 'h2Start', 'h2End']);
const yearMonthCache = new Map();
const yearMonthPath = (year) => (costModelDataDir ? resolve(costModelDataDir, `month-overrides-${year}.json`) : null);
const yearMonthName = (year) => `month-overrides-${year}.json`;
async function getYearMonths(year) {
if (yearMonthCache.has(year)) return yearMonthCache.get(year);
let raw = {};
const path = yearMonthPath(year);
if (path) { try { raw = JSON.parse(await readFile(path, 'utf8')); } catch (error) { if (error.code !== 'ENOENT') throw error; } }
const text = storage?.read(yearMonthName(year));
const raw = text != null ? JSON.parse(text) : {};
yearMonthCache.set(year, raw);
return raw;
}
async function saveYearMonths(year) {
const path = yearMonthPath(year);
if (!path) return;
await mkdir(costModelDataDir, { recursive: true });
const temporaryPath = `${path}.${process.pid}.tmp`;
await writeFile(temporaryPath, JSON.stringify(yearMonthCache.get(year), null, 2), { mode: 0o600 });
await rename(temporaryPath, path);
storage?.write(yearMonthName(year), JSON.stringify(yearMonthCache.get(year), null, 2));
}
// 定錨後修改的核心參數:先存成「下一次定錨才生效」(新檔案),定錨時才套用。
const pendingSettingsPath = costModelDataDir ? resolve(costModelDataDir, 'pending-settings.json') : null;
// 定錨快照(新檔案)。沒有資料夾時(本機預覽)只存在記憶體。
const anchorStore = createAnchorStore(costModelDataDir ? resolve(costModelDataDir, 'anchors.json') : null);
// 手動權限(新檔案)。
// 年度封存(新資料夾 archives/)。
const archiveStore = createArchiveStore(costModelDataDir ? resolve(costModelDataDir, 'archives') : null);
const permissionStore = createPermissionStore(costModelDataDir ? resolve(costModelDataDir, 'permissions.json') : null);
// 定錨後修改的核心參數:先存成「下一次定錨才生效」(pending-settings.json),定錨時才套用。
// 定錨快照、手動權限、年度封存(archives/)、預排異動:都接在同一個 storage 上。
const anchorStore = createAnchorStore(storage ? bind(storage, 'anchors.json') : null);
const archiveStore = createArchiveStore(storage ? prefixed(storage, 'archives/') : null);
const permissionStore = createPermissionStore(storage ? bind(storage, 'permissions.json') : null);
const planStore = createPlanStore(storage ? bind(storage, 'planned-changes.json') : null);
const oidc = {
issuer: process.env.OIDC_ISSUER?.replace(/\/+$/, ''),
clientId: process.env.OIDC_CLIENT_ID,
@@ -94,8 +82,9 @@ const oidc = {
const oidcConfigured = Boolean(oidc.issuer && oidc.clientId && oidc.clientSecret);
const hr = hrConfig(process.env.RESOURCE_SERVERS);
const pendingLogins = new Map();
// 登入狀態存在資料夾裡,部署重新啟動後不用重新登入(本機預覽沒有資料夾就只放記憶體)。
const sessions = createSessionStore(costModelDataDir ? resolve(costModelDataDir, 'sessions.json') : null);
// 登入狀態跟其他資料一起存在資料庫裡,部署重新啟動後不用重新登入(本機預覽沒有資料夾就只放記憶體)。
// 加密金鑰由執行期密鑰導出(SESSION_SECRET;沒有就用 OIDC client secret),不寫進檔案或 Git。
const sessions = createSessionStore(storage ? bind(storage, 'sessions.json') : null, { secret: process.env.SESSION_SECRET || oidc.clientSecret });
const restoredSessions = sessions.load();
sessions.startAutosave();
let discoveryCache;
@@ -132,6 +121,7 @@ const allowedStaticFiles = new Map([
['/calc-core.js', ['calc-core.js', 'text/javascript; charset=utf-8']],
['/scope-ui.js', ['scope-ui.js', 'text/javascript; charset=utf-8']],
['/i18n.js', ['i18n.js', 'text/javascript; charset=utf-8']],
['/buttons.css', ['buttons.css', 'text/css; charset=utf-8']],
// Poppins (SIL OFL 1.1), subset to Latin and digits for numerals; see fonts/OFL-NOTICE.txt.
['/fonts/poppins-light.woff', ['fonts/poppins-light.woff', 'font/woff']],
['/fonts/poppins-regular.woff', ['fonts/poppins-regular.woff', 'font/woff']],
@@ -151,7 +141,23 @@ async function loadBoard(session, options) {
return { payload: { ...board.payload, baseData: splitTransfers(board.payload.baseData, splits) } };
}
async function loadBoardInput(session, { scoped = false } = {}) {
// 看板資料一律套用預排異動(主看板、/my、模擬、定錨、對外接口都用同一份),定錨的最高點才不會被不同版本墊高。
async function loadBoardInput(session, options = {}) {
const board = await loadBoardRaw(session, options);
if (board.status) return board;
// 自動核對只用最高管理者(看得到完整 HR 名單)的資料做,避免用不完整的名單誤刪。
if (!isProduction || isTopAdmin(session?.claims)) {
const result = reconcilePlans(await planStore.load(), board.payload.baseData);
if (result.removed.length) await planStore.save(result.plans);
}
if (options.plans === false) return board;
const plans = await planStore.load();
if (!plans.departures.length && !plans.hires.length && !plans.transfers.length) return board;
const year = Number(board.payload.reportYear || board.payload.globalParams?.reportYear || await getCurrentYear());
return { payload: { ...board.payload, baseData: applyPlans(board.payload.baseData, plans, { year, fullYearDefault: year > FIRST_YEAR }) } };
}
async function loadBoardRaw(session, { scoped = false } = {}) {
if (isProduction) {
// scoped:呼叫端已確認過權限,回傳的資料會先依權限裁切才送出。
if (!session || (!scoped && !canAccess(session.claims))) return { status: 403, error: 'access_denied' };
@@ -238,7 +244,7 @@ function pruneExpired() {
function getSession(request) {
pruneExpired();
const sessionId = parseCookies(request).pm_board_session;
const sessionId = parseCookies(request).leadboard_session;
return sessionId ? sessions.get(sessionId) : undefined;
}
@@ -260,6 +266,16 @@ function decodeSegment(segment) {
return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));
}
let apiJwksCache;
async function getApiJwks(force = false) {
if (force || !apiJwksCache) {
const response = await fetch(API_JWKS_URI, { signal: AbortSignal.timeout(8000) });
if (!response.ok) throw new Error(`API keys failed (${response.status})`);
apiJwksCache = await response.json();
}
return apiJwksCache;
}
async function getJwks(force = false) {
if (force || !jwksCache) {
const discovery = await getDiscovery();
@@ -329,7 +345,7 @@ async function beginLogin(request, response) {
pendingLogins.set(state, { nonce, verifier, expiresAt: Date.now() + 10 * 60 * 1000 });
// Several tabs may start a login at once (e.g. after a redeploy ends every session);
// keep the few newest pending states so finishing any of them still matches.
const earlier = (parseCookies(request).pm_board_login || '').split(' ').filter(s => pendingLogins.has(s));
const earlier = (parseCookies(request).leadboard_login || '').split(' ').filter(s => pendingLogins.has(s));
const loginCookie = [...earlier.slice(-4), state].join(' ');
const callback = `${externalOrigin(request)}/api/auth/callback/authentik`;
const url = new URL(discovery.authorization_endpoint);
@@ -344,7 +360,7 @@ async function beginLogin(request, response) {
code_challenge_method: 'S256',
prompt: 'login',
});
redirect(response, url.toString(), [cookie('pm_board_login', loginCookie, 600)]);
redirect(response, url.toString(), [cookie('leadboard_login', loginCookie, 600)]);
}
async function finishLogin(request, response, url) {
@@ -353,21 +369,21 @@ async function finishLogin(request, response, url) {
const cookies = parseCookies(request);
const pending = state ? pendingLogins.get(state) : undefined;
pendingLogins.delete(state);
const browserStates = (cookies.pm_board_login || '').split(' ');
const browserStates = (cookies.leadboard_login || '').split(' ');
if (!state || !code || !browserStates.includes(state) || !pending || pending.expiresAt <= Date.now()) {
// A stale or interrupted attempt (old tab, refreshed callback, server restarted mid-login):
// start one fresh login automatically before showing an error.
if (cookies.pm_board_login_retry !== '1') {
return redirect(response, '/api/auth/login', [cookie('pm_board_login_retry', '1', 120)]);
if (cookies.leadboard_login_retry !== '1') {
return redirect(response, '/api/auth/login', [cookie('leadboard_login_retry', '1', 120)]);
}
response.writeHead(400, {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff',
'Set-Cookie': [cookie('pm_board_login_retry', '', 0), cookie('pm_board_login', '', 0)],
'Set-Cookie': [cookie('leadboard_login_retry', '', 0), cookie('leadboard_login', '', 0)],
'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'",
});
return response.end('<!doctype html><html lang="zh-Hant"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>登入未完成|MoonShine</title><style>body{min-height:100vh;margin:0;display:grid;place-items:center;background:#111211;color:#f2f2ee;font:16px system-ui,sans-serif}.card{max-width:420px;padding:40px;border:1px solid #2c2e2b;border-radius:18px;background:#1a1b19;text-align:center}a{display:inline-block;margin-top:18px;padding:12px 22px;border-radius:999px;background:#D9EE5C;color:#111211;text-decoration:none}</style><main class="card"><h1>登入未完成</h1><p>登入驗證已失效。請關閉其他 PM Board 分頁後再登入一次。</p><a href="/api/auth/login">重新登入</a></main></html>');
return response.end('<!doctype html><html lang="zh-Hant"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>登入未完成|MoonShine</title><style>body{min-height:100vh;margin:0;display:grid;place-items:center;background:#111211;color:#f2f2ee;font:16px system-ui,sans-serif}.card{max-width:420px;padding:40px;border:1px solid #2c2e2b;border-radius:18px;background:#1a1b19;text-align:center}a{display:inline-block;margin-top:18px;padding:12px 22px;border-radius:999px;background:#D9EE5C;color:#111211;text-decoration:none}</style><main class="card"><h1>登入未完成</h1><p>登入驗證已失效。請關閉其他 LeadBoard 分頁後再登入一次。</p><a href="/api/auth/login">重新登入</a></main></html>');
}
const discovery = await getDiscovery();
@@ -394,7 +410,7 @@ async function finishLogin(request, response, url) {
idToken: tokens.id_token,
accessToken: tokens.access_token, refreshToken: tokens.refresh_token,
accessExpiresAt: Date.now() + Math.max(1, Number(tokens.expires_in) || 3600) * 1000 });
redirect(response, canAccess(claims) ? '/' : '/my', [cookie('pm_board_session', sessionId, 8 * 60 * 60), cookie('pm_board_login', '', 0), cookie('pm_board_login_retry', '', 0)]);
redirect(response, canAccess(claims) ? '/' : '/my', [cookie('leadboard_session', sessionId, 8 * 60 * 60), cookie('leadboard_login', '', 0), cookie('leadboard_login_retry', '', 0)]);
}
function requireAuth(request, response, api = false) {
@@ -467,27 +483,21 @@ async function mapWithConcurrency(items, limit, task) {
async function getCostOverrides() {
if (persistedOverrides) return persistedOverrides;
persistedOverrides = new Map();
if (!costOverridesPath) return persistedOverrides;
try {
const raw = JSON.parse(await readFile(costOverridesPath, 'utf8'));
const text = storage?.read('cost-overrides.json');
if (text != null) {
const raw = JSON.parse(text);
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
for (const [employeeNumber, override] of Object.entries(raw)) {
if (/^[a-zA-Z0-9_-]{1,40}$/.test(employeeNumber)) persistedOverrides.set(employeeNumber, normalizeOverride(override));
}
}
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
}
return persistedOverrides;
}
async function saveCostOverrides() {
if (!costOverridesPath || !persistedOverrides) return;
const serialized = Object.fromEntries(persistedOverrides);
await mkdir(costModelDataDir, { recursive: true });
const temporaryPath = `${costOverridesPath}.${process.pid}.tmp`;
await writeFile(temporaryPath, JSON.stringify(serialized, null, 2), { mode: 0o600 });
await rename(temporaryPath, costOverridesPath);
if (!storage || !persistedOverrides) return;
storage.write('cost-overrides.json', JSON.stringify(Object.fromEntries(persistedOverrides), null, 2));
}
const costOverrideFields = new Set(['role', 'isManager', 'dept', 'group', 'weeklyWorkDays', 'h1Start', 'h1End', 'h2Start', 'h2End']);
@@ -532,13 +542,10 @@ async function clearCostOverrideField(employeeNumber, field) {
// presenting synthetic people as real ones.
async function getContractors(demo) {
if (persistedContractors) return persistedContractors;
if (contractorsPath) {
try {
persistedContractors = normalizeContractors(JSON.parse(await readFile(contractorsPath, 'utf8')));
return persistedContractors;
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
}
const text = storage?.read('contractors.json');
if (text != null) {
persistedContractors = normalizeContractors(JSON.parse(text));
return persistedContractors;
}
if (isProduction) return [];
return normalizeContractors((demo?.baseData || []).filter(person => String(person.role || '').startsWith('O')));
@@ -546,73 +553,39 @@ async function getContractors(demo) {
async function saveContractors(list) {
persistedContractors = normalizeContractors(list);
if (!contractorsPath) return persistedContractors;
const write = async () => {
await mkdir(costModelDataDir, { recursive: true });
const temporaryPath = `${contractorsPath}.${process.pid}.tmp`;
await writeFile(temporaryPath, JSON.stringify(persistedContractors, null, 2), { mode: 0o600 });
await rename(temporaryPath, contractorsPath);
};
contractorWrite = contractorWrite.then(write, write);
await contractorWrite;
storage?.write('contractors.json', JSON.stringify(persistedContractors, null, 2));
return persistedContractors;
}
async function getSettings() {
if (persistedSettings) return persistedSettings;
persistedSettings = {};
if (!settingsPath) return persistedSettings;
try {
persistedSettings = normalizeSettings(JSON.parse(await readFile(settingsPath, 'utf8')));
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
}
const text = storage?.read('board-settings.json');
if (text != null) persistedSettings = normalizeSettings(JSON.parse(text));
return persistedSettings;
}
async function saveSettings(input) {
const next = normalizeSettings(input);
persistedSettings = { ...(await getSettings()), ...next };
if (!settingsPath) return persistedSettings;
const snapshot = persistedSettings;
const write = async () => {
await mkdir(costModelDataDir, { recursive: true });
const temporaryPath = `${settingsPath}.${process.pid}.tmp`;
await writeFile(temporaryPath, JSON.stringify(snapshot, null, 2), { mode: 0o600 });
await rename(temporaryPath, settingsPath);
};
settingsWrite = settingsWrite.then(write, write);
await settingsWrite;
storage?.write('board-settings.json', JSON.stringify(persistedSettings, null, 2));
return persistedSettings;
}
// 英文名對照(English 介面用;不進 Git)。
let englishNames;
let englishNamesWrite = Promise.resolve();
async function getEnglishNames() {
if (englishNames) return englishNames;
englishNames = { byEmployee: {}, byName: {} };
if (!englishNamesPath) return englishNames;
try {
englishNames = normalizeEnglishNames(JSON.parse(await readFile(englishNamesPath, 'utf8')));
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
}
const text = storage?.read('english-names.json');
if (text != null) englishNames = normalizeEnglishNames(JSON.parse(text));
return englishNames;
}
async function saveEnglishNames(input) {
const next = normalizeEnglishNames(input);
englishNames = next;
if (!englishNamesPath) return next;
const write = async () => {
await mkdir(costModelDataDir, { recursive: true });
const temporaryPath = `${englishNamesPath}.${process.pid}.tmp`;
await writeFile(temporaryPath, JSON.stringify(next, null, 2), { mode: 0o600 });
await rename(temporaryPath, englishNamesPath);
};
englishNamesWrite = englishNamesWrite.then(write, write);
await englishNamesWrite;
storage?.write('english-names.json', JSON.stringify(next, null, 2));
return next;
}
@@ -620,19 +593,14 @@ let pendingSettings;
async function getPendingSettings() {
if (pendingSettings !== undefined) return pendingSettings;
pendingSettings = null;
if (pendingSettingsPath) {
try { pendingSettings = JSON.parse(await readFile(pendingSettingsPath, 'utf8')); } catch (error) { if (error.code !== 'ENOENT') throw error; }
}
const text = storage?.read('pending-settings.json');
if (text != null) pendingSettings = JSON.parse(text);
return pendingSettings;
}
async function setPendingSettings(value) {
pendingSettings = value;
if (!pendingSettingsPath) return;
await mkdir(costModelDataDir, { recursive: true });
const temporaryPath = `${pendingSettingsPath}.${process.pid}.tmp`;
await writeFile(temporaryPath, JSON.stringify(value), { mode: 0o600 });
await rename(temporaryPath, pendingSettingsPath);
storage?.write('pending-settings.json', JSON.stringify(value));
}
// 待生效的設定和目前設定差在哪裡(給畫面顯示)。
@@ -694,7 +662,7 @@ async function getCostModel(session) {
needsReview: people.filter(person => !person.calculationReady).length,
hourlyEmployees: people.filter(person => person.salaryType === 'hourly').length,
legacyContractors: contractors.length,
contractorsSaved: Boolean(persistedContractors && contractorsPath),
contractorsSaved: Boolean(persistedContractors && storage),
},
};
session.costModelCache = { payload, expiresAt: Date.now() + 60_000 };
@@ -715,7 +683,7 @@ const server = createServer(async (request, response) => {
try {
if (request.method === 'GET' && url.pathname === '/api/health') {
return sendJson(response, 200, { status: 'ok', release: 'hr-service-v54', hr: { mode: hrMode, serviceError: hrServiceError } });
return sendJson(response, 200, { status: 'ok', release: 'hr-service-v54', storage: storage?.kind || 'memory', hr: { mode: hrMode, serviceError: hrServiceError } });
}
if (request.method === 'GET' && url.pathname === '/api/auth/login') {
@@ -731,19 +699,19 @@ const server = createServer(async (request, response) => {
if (request.method === 'POST' && url.pathname === '/api/auth/logout') {
const origin = request.headers.origin;
if (origin && origin !== externalOrigin(request)) return sendText(response, 403, '無法驗證登出請求。');
const sessionId = parseCookies(request).pm_board_session;
const sessionId = parseCookies(request).leadboard_session;
if (sessionId) sessions.delete(sessionId);
redirect(response, '/logged-out', [cookie('pm_board_session', '', 0), cookie('pm_board_login', '', 0)]);
redirect(response, '/logged-out', [cookie('leadboard_session', '', 0), cookie('leadboard_login', '', 0)]);
return;
}
if (request.method === 'POST' && url.pathname === '/api/auth/company-logout') {
const origin = request.headers.origin;
if (origin && origin !== externalOrigin(request)) return sendText(response, 403, '無法驗證登出請求。');
const sessionId = parseCookies(request).pm_board_session;
const sessionId = parseCookies(request).leadboard_session;
const session = sessionId ? sessions.get(sessionId) : undefined;
if (sessionId) sessions.delete(sessionId);
const cleared = [cookie('pm_board_session', '', 0), cookie('pm_board_login', '', 0)];
const cleared = [cookie('leadboard_session', '', 0), cookie('leadboard_login', '', 0)];
let endSession;
if (session?.idToken && oidcConfigured) {
try { endSession = (await getDiscovery()).end_session_endpoint; } catch {}
@@ -752,16 +720,16 @@ const server = createServer(async (request, response) => {
const destination = new URL(endSession);
destination.searchParams.set('id_token_hint', session.idToken);
destination.searchParams.set('post_logout_redirect_uri', `${externalOrigin(request)}/logged-out`);
return redirect(response, destination.toString(), [...cleared, cookie('pm_board_company_logout', 'returned', 120)]);
return redirect(response, destination.toString(), [...cleared, cookie('leadboard_company_logout', 'returned', 120)]);
}
if (request.method === 'GET' && url.pathname === '/logged-out') {
const companyReturned = parseCookies(request).pm_board_company_logout === 'returned';
const companyReturned = parseCookies(request).leadboard_company_logout === 'returned';
response.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff',
'Set-Cookie': cookie('pm_board_company_logout', '', 0),
'Set-Cookie': cookie('leadboard_company_logout', '', 0),
'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'",
});
return response.end('<!doctype html><html lang="zh-Hant"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>已登出|MoonShine</title><style>body{min-height:100vh;margin:0;display:grid;place-items:center;background:#0c1329;color:#f5f7ff;font:16px system-ui,sans-serif}.card{max-width:420px;padding:40px;border:1px solid #34446b;border-radius:18px;background:#151e38;text-align:center}a{display:inline-block;margin-top:18px;padding:12px 22px;border-radius:9px;background:#3978ed;color:white;text-decoration:none}</style><main class="card"><h1>已登出</h1><p>' + (companyReturned ? '已從 MoonShine 公司帳號登出。其他已開啟的公司系統可能仍保有自己的登入狀態。' : '這個網站的登入狀態已結束。公司帳號可能仍保持登入。') + '</p><a href="/api/auth/login">重新登入</a></main></html>');
@@ -964,12 +932,19 @@ const server = createServer(async (request, response) => {
}
}
// 依權限的頁面:主管、全公司檢視看 /my;權限管理頁只有最高管理者。
if (request.method === 'GET' && (url.pathname === '/my' || url.pathname === '/permissions' || url.pathname === '/archive')) {
// 權限管理已經搬進主看板,舊網址導回看板並直接打開那個區塊(別人存的連結不會壞)。
if (request.method === 'GET' && url.pathname === '/permissions') {
const session = requireAuth(request, response);
if (!session) return;
return redirect(response, isProduction && !isTopAdmin(session.claims) ? '/my' : '/?view=permissions');
}
// 依權限的頁面:主管、全公司檢視看 /my;年度封存只有最高管理者。
if (request.method === 'GET' && (url.pathname === '/my' || url.pathname === '/archive')) {
const session = requireAuth(request, response);
if (!session) return;
if (url.pathname !== '/my' && isProduction && !isTopAdmin(session.claims)) return redirect(response, '/my');
const content = await readFile(resolve(root, { '/my': 'my.html', '/permissions': 'permissions.html', '/archive': 'archive.html' }[url.pathname]));
const content = await readFile(resolve(root, { '/my': 'my.html', '/archive': 'archive.html' }[url.pathname]));
// 登出(含公司帳號)會轉到公司登入伺服器,form-action 要允許它。
const authOrigin = (() => { try { return oidc.issuer ? new URL(oidc.issuer).origin : ''; } catch { return ''; } })();
response.writeHead(200, {
@@ -981,7 +956,25 @@ const server = createServer(async (request, response) => {
return response.end(content);
}
// 英文名:English 介面顯示「中文+英文」。只給看得到 PM Board 的人,只含目前名單上的人。
// 預排異動:只有最高管理者能看、能改。
if (url.pathname === '/api/plans') {
const session = requireAuth(request, response, true);
if (!session) return;
if (isProduction && !isTopAdmin(session.claims)) return sendJson(response, 403, { error: 'top_admin_only' });
if (request.method === 'PUT') {
try {
await planStore.save(await readJson(request, 200_000));
} catch (error) {
if (error instanceof TypeError || error instanceof RangeError) return sendJson(response, 400, { error: 'invalid_plans' });
throw error;
}
} else if (request.method !== 'GET') return sendJson(response, 405, { error: 'method_not_allowed' });
const board = await loadBoard(session, { plans: false });
if (board.status) return sendJson(response, board.status, { error: board.error });
return sendJson(response, 200, { plans: await planStore.load(), status: planStatus(await planStore.load(), board.payload.baseData) });
}
// 英文名:English 介面顯示「中文+英文」。只含這個人權限範圍內、目前名單上的人(不洩漏其他部門的名單)。
if (request.method === 'GET' && url.pathname === '/api/names') {
const session = requireAuth(request, response, true);
if (!session) return;
@@ -989,7 +982,7 @@ const server = createServer(async (request, response) => {
if (!hasAnyScope(permission)) return sendJson(response, 403, { error: 'no_permission' });
const board = await loadBoard(session, { scoped: true });
if (board.status) return sendJson(response, board.status, { error: board.error });
return sendJson(response, 200, { names: englishNameMap(board.payload.baseData, await getEnglishNames()) });
return sendJson(response, 200, { names: englishNameMap(visiblePeople(board.payload.baseData, permission), await getEnglishNames()) });
}
// 匯入英文名對照(整份取代):只有最高管理者。
@@ -1017,7 +1010,8 @@ const server = createServer(async (request, response) => {
const model = computeModel(board.payload);
const year = Number(board.payload.reportYear || board.payload.globalParams?.reportYear || await getCurrentYear());
const anchors = await anchorStore.evaluate(model, year);
return sendJson(response, 200, { ...buildScopedView(model, anchors, permission, { year }), usdRate: Number(board.payload.globalParams?.usdRate) || 30 });
// 預排傳進去只為了「誰離開」那份清單(轉調後的人已經不在原部門,要靠 fromDept 才找得到)。
return sendJson(response, 200, { ...buildScopedView(model, anchors, permission, { year, plans: await planStore.load() }), usdRate: Number(board.payload.globalParams?.usdRate) || 30 });
}
// 對外接口:只接受 Bearer token(不用登入 session、不套工號白名單),只讀。
@@ -1026,7 +1020,7 @@ const server = createServer(async (request, response) => {
if (!oidcConfigured) return sendJson(response, 503, { error: 'auth_not_configured' });
let caller;
try {
caller = await verifyApiToken(request.headers.authorization, { issuer: oidc.issuer, getKeys: getJwks });
caller = await verifyApiToken(request.headers.authorization, { issuer: API_ISSUER, getKeys: getApiJwks });
} catch (error) {
if (error instanceof ApiError) return sendJson(response, error.status, { error: error.code });
throw error;
@@ -1183,9 +1177,9 @@ const server = createServer(async (request, response) => {
} catch (error) {
if (error instanceof HrError) {
if (error.code === 'reauthentication_required') {
const sessionId = parseCookies(request).pm_board_session;
const sessionId = parseCookies(request).leadboard_session;
if (sessionId) sessions.delete(sessionId);
response.setHeader('Set-Cookie', cookie('pm_board_session', '', 0));
response.setHeader('Set-Cookie', cookie('leadboard_session', '', 0));
}
return sendJson(response, error.status, { error: error.code, ...(error.status === 401 ? { login: '/api/auth/login' } : {}) });
}
+66 -24
View File
@@ -1,60 +1,102 @@
// 登入狀態存檔:COST_MODEL_DATA_DIR/sessions.json(新檔案,不進 Git)。部署重新啟動後,大家不用重新登入。
// 登入狀態存檔:sessions.json(存在 COST_MODEL_DATA_DIR/leadboard.db 的 documents 表;STORAGE_BACKEND=json 時是同名檔案,不進 Git)。部署重新啟動後,大家不用重新登入。
// - 檔案裡只存 session id 的 SHA-256,不存瀏覽器 cookie 的原始值;檔案權限 600。
// - 只存登入需要的欄位;HR 名單、權限、成本等暫存(*Cache)不存。
// - 過期的不載入、不存。
import { createHash } from 'node:crypto';
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { dirname } from 'node:path';
// - 每一筆登入資料(含 refresh token 等)用 AES-256-GCM 加密;金鑰由執行期密鑰(環境變數)導出,
// 不寫進檔案、程式碼或 Git。沒有密鑰時不存檔(只放記憶體,重新部署要重新登入)。
// - 密鑰換掉或檔案被改過:解不開的那筆直接略過(該使用者重新登入即可)。
import { createCipheriv, createDecipheriv, createHash, hkdfSync, randomBytes } from 'node:crypto';
import { bindFile } from './storage.js';
const KEPT = ['claims', 'expiresAt', 'idToken', 'accessToken', 'refreshToken', 'accessExpiresAt'];
const hash = (id) => createHash('sha256').update(String(id)).digest('hex');
export function createSessionStore(path, { now = () => Date.now(), saveDelay = 500 } = {}) {
export function sessionKey(secret) {
if (typeof secret !== 'string' || secret.length < 8) return null;
return Buffer.from(hkdfSync('sha256', secret, 'pm-board', 'pm-board session store v2', 32));
}
// 加密一筆(每筆隨機 IV;用這筆的 key 當 AAD,搬到別筆就解不開)。
function seal(key, aad, value) {
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', key, iv);
cipher.setAAD(Buffer.from(aad));
const data = Buffer.concat([cipher.update(JSON.stringify(value), 'utf8'), cipher.final()]);
return Buffer.concat([iv, cipher.getAuthTag(), data]).toString('base64');
}
function open(key, aad, sealed) {
const raw = Buffer.from(String(sealed || ''), 'base64');
if (raw.length < 29) throw new Error('sealed value too short');
const decipher = createDecipheriv('aes-256-gcm', key, raw.subarray(0, 12));
decipher.setAAD(Buffer.from(aad));
decipher.setAuthTag(raw.subarray(12, 28));
return JSON.parse(Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString('utf8'));
}
export function createSessionStore(source, { now = () => Date.now(), saveDelay = 500, secret } = {}) {
const key = sessionKey(secret);
let file = bindFile(source);
if (file && !key) {
console.error('session store: no runtime secret, sessions are kept in memory only');
file = null;
}
const map = new Map();
let timer = null;
let lastWritten = '';
function snapshot() {
// 目前要存的內容(明文,只在記憶體裡用來判斷有沒有變)。
function current() {
const time = now();
const out = {};
for (const [key, session] of map) {
for (const [id, session] of map) {
if (!(session.expiresAt > time)) continue;
out[key] = Object.fromEntries(KEPT.filter(field => session[field] !== undefined).map(field => [field, session[field]]));
out[id] = Object.fromEntries(KEPT.filter(field => session[field] !== undefined).map(field => [field, session[field]]));
}
return JSON.stringify({ version: 1, sessions: out });
return out;
}
// 同步寫檔:關機時也能寫完。內容沒變就不寫。
function flush() {
if (timer) { clearTimeout(timer); timer = null; }
if (!path) return;
const body = snapshot();
if (body === lastWritten) return;
mkdirSync(dirname(path), { recursive: true });
const temporary = `${path}.${process.pid}.tmp`;
writeFileSync(temporary, `${body}\n`, { mode: 0o600 });
renameSync(temporary, path);
lastWritten = body;
if (!file) return;
const records = current();
const signature = createHash('sha256').update(JSON.stringify(records)).digest('hex');
if (signature === lastWritten) return;
const sessions = Object.fromEntries(Object.entries(records).map(([id, record]) => [id, { expiresAt: record.expiresAt, data: seal(key, id, record) }]));
file.write(`${JSON.stringify({ version: 2, sessions })}\n`);
lastWritten = signature;
}
function schedule() {
if (!path || timer) return;
if (!file || timer) return;
timer = setTimeout(() => { timer = null; try { flush(); } catch (error) { console.error('session save failed', error.message); } }, saveDelay);
timer.unref?.();
}
function load() {
if (!path) return 0;
if (!file) return 0;
let data;
try { data = JSON.parse(readFileSync(path, 'utf8')); } catch (error) {
if (error.code !== 'ENOENT') console.error('session load failed', error.message);
try {
const text = file.read();
if (text === null) return 0;
data = JSON.parse(text);
} catch (error) {
console.error('session load failed', error.message);
return 0;
}
const time = now();
for (const [key, session] of Object.entries(data?.sessions || {})) {
if (/^[0-9a-f]{64}$/.test(key) && session && session.expiresAt > time && session.claims) map.set(key, { ...session });
const legacy = data?.version === 1;
for (const [id, entry] of Object.entries(data?.sessions || {})) {
if (!/^[0-9a-f]{64}$/.test(id) || !entry || !(entry.expiresAt > time)) continue;
let session = null;
if (legacy) session = entry; // 舊版(未加密):載入一次,馬上改寫成加密版。
else { try { session = open(key, id, entry.data); } catch { session = null; } }
if (session && session.expiresAt > time && session.claims) map.set(id, { ...session });
}
lastWritten = snapshot();
lastWritten = '';
if (legacy) flush();
else lastWritten = createHash('sha256').update(JSON.stringify(current())).digest('hex');
return map.size;
}
+24
View File
@@ -9,6 +9,7 @@ export const PARAM_KEYS = Object.freeze([
'contractorMultiplier', 'usdRate',
]);
const MAX_GROUPS = 300;
const MAX_SHARE_RULES = 20;
// Invoice role per company (default for its departments) and per department:
// bear = carries invoice, share = cost goes into the invoice pool but gets no allocation,
// exclude = outside the invoice (shown as cost × 人薪倍率).
@@ -35,6 +36,26 @@ function groupKeys(list) {
return [...new Set(keys)].slice(0, MAX_GROUPS);
}
// CODA 分配規則:from 的部門整包 CODA 分給 to 的部門(依各自 CODA 比例)。
// 格式不對的整條跳過;已經在 from 的部門不會再被當成 to。
function shareRules(list) {
if (list === undefined) return undefined;
if (!Array.isArray(list)) throw new TypeError('codaShareRules must be an array');
const names = value => [...new Set((Array.isArray(value) ? value : [])
.filter(item => typeof item === 'string')
.map(item => item.trim().slice(0, 80))
.filter(Boolean))].slice(0, MAX_GROUPS);
const rules = [];
for (const rule of list.slice(0, MAX_SHARE_RULES)) {
if (!rule || typeof rule !== 'object' || Array.isArray(rule)) continue;
const from = names(rule.from);
const to = names(rule.to).filter(name => !from.includes(name));
if (!from.length || !to.length) continue;
rules.push({ company: String(rule.company || '').trim().slice(0, 80), from, to, noDeptP: Boolean(rule.noDeptP) });
}
return rules;
}
export function normalizeSettings(input = {}) {
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new TypeError('settings must be an object');
const output = {};
@@ -46,6 +67,8 @@ export function normalizeSettings(input = {}) {
output.invoiceRoles = { companies: roleMap(input.invoiceRoles.companies) || {}, depts: roleMap(input.invoiceRoles.depts) || {} };
}
if (cgLeadGroups) output.cgLeadGroups = cgLeadGroups;
const codaShareRules = shareRules(input.codaShareRules);
if (codaShareRules) output.codaShareRules = codaShareRules;
if (input.params !== undefined) {
if (!input.params || typeof input.params !== 'object' || Array.isArray(input.params)) throw new TypeError('params must be an object');
output.params = {};
@@ -67,5 +90,6 @@ export function applySettings(globalParams, settings) {
...(settings.rdGroups ? { rdGroups: settings.rdGroups } : {}),
...(settings.cgLeadGroups ? { cgLeadGroups: settings.cgLeadGroups } : {}),
...(settings.invoiceRoles ? { invoiceRoles: settings.invoiceRoles } : {}),
...(settings.codaShareRules ? { codaShareRules: settings.codaShareRules } : {}),
};
}
@@ -1,11 +1,12 @@
---
name: pm-board-external-api
description: 讀取 MoonShine PM Board 對外接口的年度發票(含 H1/H2 半年定錨)與 CODA(實際 CODA、定錨 CODA;夢想創造、夢境現實)彙整數字,並正確解讀欄位、版本與算法。當使用者要查部門發票目標、H1/H2 目標、部門或組別的實際/定錨 CODA、平均日 CODA、研發部成本,或要串接 PM Board 數字時使用。
name: leadboard-external-api
description: 讀取 MoonShine LeadBoard 對外接口的年度發票(含 H1/H2 半年定錨)與 CODA(實際 CODA、定錨 CODA;夢想創造、夢境現實)彙整數字,並正確解讀欄位、版本與算法。當使用者要查部門發票目標、H1/H2 目標、部門或組別的實際/定錨 CODA、平均日 CODA、研發部成本,或要串接 LeadBoard 數字時使用。
---
# PM Board 對外接口
# LeadBoard 對外接口
PM Board(https://pm-board-vibe.moonshine-studio.net/)是 MoonShine 的人力成本與目標系統。
LeadBoard(https://leadboard-vibe.moonshine-studio.net/)是 MoonShine 的人力成本與目標系統。
(原名 PM Board,2026-11 改名;對外接口的代號也已同步改為 leadboard。)
這個接口提供**彙整後**的年度發票與 CODA 數字,給公司內部其他系統讀取。
> **狀態(2026-11-12)**:接口程式已上線(網址見第 2 節),但**第一次定錨前一律回 503「尚未定錨」**。第一次正式定錨預計在 2027 年 1 月,之後才有數字。
@@ -23,19 +24,19 @@ PM Board(https://pm-board-vibe.moonshine-studio.net/)是 MoonShine 的人力
## 2. 存取
- 只有讀取(GET),兩支網址:
- `GET https://pm-board-vibe.moonshine-studio.net/api/external/v1/invoice`:年度發票
- `GET https://pm-board-vibe.moonshine-studio.net/api/external/v1/coda`:CODA
- `GET https://leadboard-vibe.moonshine-studio.net/api/external/v1/invoice`:年度發票
- `GET https://leadboard-vibe.moonshine-studio.net/api/external/v1/coda`:CODA
- 其他方法回 405。
- 認證:`Authorization: Bearer <token>`,token 由 Authentik 的 `PM Board` provider 簽發(RS256)。
- `iss`:Authentik 的 PM Board provider
- `aud`(audience):`pm-board-api`
- `scope`:要含 `pm-board:read`
- 認證:`Authorization: Bearer <token>`,token 由 Authentik 的 `leadboard` provider 簽發(RS256)。
- `iss`:Authentik 的 leadboard provider
- `aud`(audience):`leadboard-api`
- `scope`:要含 `leadboard:read`
- 效期 300 秒,過期要重新換發。
- 誰能拿到 token:Authentik 只把 `pm-board:read` 發給群組 `pm-board-read`。
vibe 站台(例如 morning)在自己的 `vibe.yaml` 宣告 `auth.resource_servers.pm-board`,
平台負責換 token;因為是代表登入者呼叫,**實際操作的使用者**要在 `pm-board-read` 群組,
- 誰能拿到 token:Authentik 只把 `leadboard:read` 發給群組 `leadboard-read`。
vibe 站台(例如 morning)在自己的 `vibe.yaml` 宣告 `auth.resource_servers.leadboard`,
平台負責換 token;因為是代表登入者呼叫,**實際操作的使用者**要在 `leadboard-read` 群組,
不在群組的人整張 token 會被拒。非 vibe 的系統要接,由 RD 個別建立服務帳號。
- 這兩支網址不看 PM Board 的工號白名單,只看 token。每次呼叫都會記錄呼叫者(`sub`、工號)。
- 這兩支網址不看 LeadBoard 的工號白名單,只看 token。每次呼叫都會記錄呼叫者(`sub`、工號)。
- 金鑰或 token 不可寫進程式碼、文件或對話,只放在環境變數或密鑰管理工具。
技術細節(JWKS、`iss`、401/403 怎麼判斷、伺服器怎麼讀 HR)見專案內的 `AUTHENTIK-HANDOFF.md`。
@@ -170,16 +171,16 @@ PM Board(https://pm-board-vibe.moonshine-studio.net/)是 MoonShine 的人力
3. **分清楚兩種 CODA**:問「定價」「划不划算」用實際 CODA 的 `avgDailyCoda`;問「半年目標」用 `anchoredCoda`。回答時要講明是哪一種。
4. **暫定值**:`h2.provisional` 或 `anchoredCoda.h2Provisional` 為 true 時,要說明這是 7 月定錨前的暫定數字。
5. **不要自己重算或推測個人數字**:例如不要用部門金額反推個人薪資。
6. **發票變多的原因**:只能說明 `increase` 的金額,不能說明是誰造成的(接口不提供明細);需要明細請洽 PM Board 負責人。
6. **發票變多的原因**:只能說明 `increase` 的金額,不能說明是誰造成的(接口不提供明細);需要明細請洽 LeadBoard 負責人。
7. **錯誤處理**(錯誤回應格式:`{ "error": "<代碼>" }`):
| 狀況 | 回應 | 怎麼處理 |
|---|---|---|
| 尚未定錨 | 503 `not_anchored` | 告知還沒有正式數字(第一次定錨在 2027 年 1 月),不要用其他來源代替 |
| 沒帶 token | 401 `token_required` | 帶上 `Authorization: Bearer <token>` |
| token 無效(簽章、`iss`、`aud` 不對) | 401 `invalid_token` | 確認 token 是 PM Board provider 簽發、`aud` 是 `pm-board-api`;仍失敗找 RD |
| token 無效(簽章、`iss`、`aud` 不對) | 401 `invalid_token` | 確認 token 是 leadboard provider 簽發、`aud` 是 `leadboard-api`;仍失敗找 RD |
| token 過期 | 401 `token_expired` | 重新換發 token |
| token 有效但缺 `pm-board:read` | 403 `insufficient_scope` | 先確認操作者在 `pm-board-read` 群組,否則找 RD 開通 |
| token 有效但缺 `leadboard:read` | 403 `insufficient_scope` | 先確認操作者在 `leadboard-read` 群組,否則找 RD 開通 |
| 不是 GET | 405 `method_not_allowed` | 只用 GET |
| 伺服器暫時算不出來 | 503 `temporarily_unavailable` | 稍後再試 |
| HR 暫時無法連線 | 照常回傳上一份 | 以 `generatedAt` 判斷資料時間 |
@@ -233,5 +234,5 @@ PM Board(https://pm-board-vibe.moonshine-studio.net/)是 MoonShine 的人力
## 7. 聯絡
- 數字、規則、定錨:PM Board 負責人 walkdoggo.yeh
- 數字、規則、定錨:LeadBoard 負責人 walkdoggo.yeh
- 帳號、權限、連線:RD
+96
View File
@@ -0,0 +1,96 @@
// 存檔的共同介面:把「檔名 → 文字內容」存起來,背後可以是資料夾裡的檔案或 SQLite。
// read(name) → 文字,沒有這一筆就回 null
// write(name, text, { exclusive }) → 寫入;exclusive 時已存在會丟 code 'EEXIST'
// list(prefix) → 以 prefix 開頭的名稱(例如 'archives/')
// 全部同步(node:sqlite 本來就是同步的);呼叫端各自負責排隊,不會同時寫。
import { createHash } from 'node:crypto';
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs';
import { basename, dirname, resolve } from 'node:path';
export const sha256 = (text) => createHash('sha256').update(text, 'utf8').digest('hex');
function exists(name) {
const error = new Error(`${name} already exists`);
error.code = 'EEXIST';
return error;
}
// 檔案版:一個名稱就是 dir 底下的一個 .json 檔,先寫暫存檔再改名,權限 600。
export function fileStorage(dir) {
const locate = (name) => resolve(dir, name);
return {
kind: 'file',
read(name) {
try { return readFileSync(locate(name), 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
},
write(name, text, { exclusive = false } = {}) {
const file = locate(name);
if (exclusive && existsSync(file)) throw exists(name);
mkdirSync(dirname(file), { recursive: true });
const temporary = `${file}.${process.pid}.tmp`;
writeFileSync(temporary, text, { mode: 0o600 });
renameSync(temporary, file);
},
list(prefix = '') {
try {
return readdirSync(locate(prefix), { withFileTypes: true }).filter(entry => entry.isFile()).map(entry => `${prefix}${entry.name}`).sort();
} catch (error) { if (error.code === 'ENOENT') return []; throw error; }
},
};
}
// SQLite 版:documents 表,一個名稱一列,內容原樣存成文字。db 是 node:sqlite 的 DatabaseSync。
export function sqliteStorage(db, { now = () => new Date().toISOString() } = {}) {
const select = db.prepare('SELECT body FROM documents WHERE name = ?');
const insert = db.prepare('INSERT INTO documents (name, body, sha256, bytes, updated_at) VALUES (?, ?, ?, ?, ?)');
const upsert = db.prepare(`INSERT INTO documents (name, body, sha256, bytes, updated_at) VALUES (?, ?, ?, ?, ?)
ON CONFLICT(name) DO UPDATE SET body = excluded.body, sha256 = excluded.sha256, bytes = excluded.bytes, updated_at = excluded.updated_at`);
const names = db.prepare('SELECT name FROM documents WHERE substr(name, 1, length(?)) = ? ORDER BY name');
return {
kind: 'sqlite',
db,
read(name) {
const row = select.get(name);
return row ? row.body : null;
},
write(name, text, { exclusive = false } = {}) {
const values = [name, text, sha256(text), Buffer.byteLength(text, 'utf8'), now()];
if (!exclusive) { upsert.run(...values); return; }
try { insert.run(...values); } catch (error) {
if (/UNIQUE|PRIMARY KEY/i.test(String(error?.message))) throw exists(name);
throw error;
}
},
list(prefix = '') { return names.all(prefix, prefix).map(row => row.name); },
};
}
// 單一檔案的把手:{ read(), write(text) }。傳字串路徑=檔案版(測試與本機預覽用);傳把手就直接用。
export function bindFile(source) {
if (!source) return null;
if (typeof source !== 'string') return source;
const storage = fileStorage(dirname(source));
const name = basename(source);
return { read: () => storage.read(name), write: (text) => storage.write(name, text) };
}
export const bind = (storage, name) => ({ read: () => storage.read(name), write: (text) => storage.write(name, text) });
// 把一組名稱放在同一個前綴下(archives/2027.json 對外只叫 2027.json)。
export const prefixed = (storage, prefix) => ({
read: (name) => storage.read(`${prefix}${name}`),
write: (name, text, options) => storage.write(`${prefix}${name}`, text, options),
list: () => storage.list(prefix).map(name => name.slice(prefix.length)),
});
// 資料夾路徑 → 同樣介面(封存用):名稱就是資料夾裡的檔名。傳物件就直接用。
export function bindDirectory(source) {
if (!source) return null;
if (typeof source !== 'string') return source;
const storage = fileStorage(source);
return {
read: (name) => storage.read(name),
write: (name, text, options) => storage.write(name, text, options),
list: () => storage.list('').map(name => name),
};
}
+43
View File
@@ -51,3 +51,46 @@ test('a group that is both 研發 and CG Lead gets both reductions; groups still
assert.ok(Math.abs(groups.R.coda - initial * 0.65 * 0.85) < 1e-6);
assert.ok(Math.abs(groups.R.coda + groups.N.coda - model.codaGroups[dept].coda) < 1e-6);
});
// 業務部這類單位:整包 CODA 分給四個部門,自己只算成本,不談指標。
function shareFixture() {
const base = { company: '夢想創造', h1Start: 1, h1End: 6, h2Start: 7, h2End: 12 };
return {
baseData: [
{ ...base, name: 'a1', title: 'Artist', role: 'A - 藝術家', dept: '甲部', salary: 90000 },
{ ...base, name: 'a2', title: 'Artist', role: 'A - 藝術家', dept: '乙部', salary: 30000 },
{ ...base, name: 'b1', title: 'Artist', role: 'A - 藝術家', dept: '業務部', salary: 40000 },
{ ...base, name: 'b2', title: 'Producer', role: 'P - 製作', dept: '業務部', salary: 20000 },
],
globalParams: { ...seed.globalParams, reportYear: 2027, orgStructure: null },
};
}
test('CODA 分配規則可由核心參數設定:來源部門歸零、不顯示倍率,總額不變', () => {
const fixture = shareFixture();
const before = computeModel(fixture);
assert.ok(before.coda['業務部'] > 0);
assert.ok(before.multiplierUnits.some(unit => unit.label === '業務部'));
const rules = [{ company: '夢想創造', from: ['業務部'], to: ['甲部', '乙部'] }];
const after = computeModel({ ...fixture, globalParams: { ...fixture.globalParams, codaShareRules: rules } });
assert.ok(Math.abs(after.coda['業務部']) < 1e-6);
assert.equal(after.multiplierUnits.some(unit => unit.label === '業務部'), false);
assert.ok(after.multiplierUnits.some(unit => unit.label === '甲部'));
const total = model => Object.values(model.coda).reduce((sum, value) => sum + value, 0);
assert.ok(Math.abs(total(before) - total(after)) < 1e-6);
// 依各自 CODA 比例分配:甲部的 CODA 是乙部的三倍,拿到的也是三倍。
const gained = dept => after.coda[dept] - before.coda[dept];
assert.ok(Math.abs(gained('甲部') / gained('乙部') - 3) < 1e-6);
});
test('格式不對的 CODA 分配規則整條跳過,空陣列代表完全不分配', () => {
const fixture = shareFixture();
const broken = [{ from: [], to: ['甲部'] }, { from: ['業務部'], to: [] }, 'nope', null];
const withBroken = computeModel({ ...fixture, globalParams: { ...fixture.globalParams, codaShareRules: broken } });
const withNone = computeModel({ ...fixture, globalParams: { ...fixture.globalParams, codaShareRules: [] } });
assert.deepEqual(withBroken.coda, withNone.coda);
assert.ok(withNone.coda['業務部'] > 0);
assert.ok(withNone.multiplierUnits.some(unit => unit.label === '業務部'));
});
+2 -2
View File
@@ -8,11 +8,11 @@ import { ApiError, buildExternal, verifyApiToken } from '../external-api.js';
const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
const jwk = { ...publicKey.export({ format: 'jwk' }), kid: 'k1' };
const issuer = 'https://auth.example.test/application/o/pm-board';
const issuer = 'https://auth.example.test/application/o/leadboard';
const token = (claims, kid = 'k1') => {
const enc = (v) => Buffer.from(JSON.stringify(v)).toString('base64url');
const head = enc({ alg: 'RS256', kid });
const body = enc({ iss: `${issuer}/`, aud: 'pm-board-api', exp: Math.floor(Date.now() / 1000) + 300, scope: 'openid pm-board:read', sub: 's1', actor_type: 'service', ...claims });
const body = enc({ iss: `${issuer}/`, aud: 'leadboard-api', exp: Math.floor(Date.now() / 1000) + 300, scope: 'openid leadboard:read', sub: 's1', actor_type: 'service', ...claims });
return `Bearer ${head}.${body}.${sign('RSA-SHA256', Buffer.from(`${head}.${body}`), privateKey).toString('base64url')}`;
};
const getKeys = async () => ({ keys: [jwk] });
+35
View File
@@ -0,0 +1,35 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { Script } from 'node:vm';
// 看板大半的邏輯寫在 index.html 的 inline script 裡(二十幾萬字元),瀏覽器才會執行。
// node --test 不會碰它,所以語法打壞了 CI 照樣綠燈,網站卻整頁空白。
// 這裡把每一段 inline script 和每一支瀏覽器用的 .js 都交給 V8 解析一次(只解析、不執行)。
const PAGES = ['index.html', 'my.html', 'archive.html'];
const BROWSER_SCRIPTS = ['calc-core.js', 'scope-ui.js', 'i18n.js'];
// 只挑沒有 src 的 <script>;有 type 的另外處理(目前沒有,有的話要先確認能不能當一般腳本解析)。
const INLINE = /<script([^>]*)>([\s\S]*?)<\/script>/g;
const read = (name) => readFile(new URL(`../${name}`, import.meta.url), 'utf8');
const parses = (source, filename) => assert.doesNotThrow(
() => new Script(source, { filename }), `${filename} 的 JavaScript 語法有問題`);
for (const page of PAGES) {
test(`${page} 的 inline script 語法正確`, async () => {
const html = await read(page);
const blocks = [...html.matchAll(INLINE)]
.map(([, attrs, body]) => ({ attrs: attrs.trim(), body }))
.filter(block => !/\bsrc=/.test(block.attrs));
assert.ok(blocks.length > 0, `${page} 裡找不到 inline script,選取條件可能要更新`);
for (const [index, block] of blocks.entries()) {
// 有 type 的腳本(module、JSON)不能當一般腳本解析,出現就要先更新這個測試。
assert.equal(block.attrs, '', `${page} 第 ${index + 1} 段 script 有屬性「${block.attrs}」,請確認這個測試還適用`);
parses(block.body, `${page}#script${index + 1}`);
}
});
}
test('瀏覽器用的 .js 檔語法正確', async () => {
for (const name of BROWSER_SCRIPTS) parses(await read(name), name);
});
+18 -1
View File
@@ -2,7 +2,7 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import vm from 'node:vm';
import { englishNameMap, normalizeEnglishNames } from '../english-names.js';
import { englishNameMap, normalizeEnglishNames, visiblePeople } from '../english-names.js';
// 在沒有瀏覽器的環境載入 i18n.js,模擬瀏覽器裡存的語言/幣別設定。
async function loadI18n(saved = {}) {
@@ -65,3 +65,20 @@ test('English names: only valid entries are kept; people not on the roster are l
assert.deepEqual(englishNameMap(people, store), { 葉傳耀: 'Woody Yeh', 詹智翔: 'ChihShiang Jan', 黃思豪: 'Triston Huang' });
assert.throws(() => normalizeEnglishNames([]), TypeError);
});
test('English names only cover people inside the viewer\'s scope', () => {
const people = [
{ name: '甲', dept: '前製部', group: '導演組' },
{ name: '乙', dept: '前製部', group: '設計概念組' },
{ name: '丙', dept: '動畫部', group: '動畫組' },
{ name: '丁', dept: '視效部', group: '' },
];
const names = list => list.map(p => p.name);
assert.deepEqual(names(visiblePeople(people, { admin: true, depts: [], groups: [] })), ['甲', '乙', '丙', '丁']);
assert.deepEqual(names(visiblePeople(people, { company: true, depts: [], groups: [] })), ['甲', '乙', '丙', '丁']);
assert.deepEqual(names(visiblePeople(people, { depts: ['前製部'], groups: [] })), ['甲', '乙']);
assert.deepEqual(names(visiblePeople(people, { depts: [], groups: ['動畫部|動畫組'] })), ['丙']);
assert.deepEqual(names(visiblePeople(people, { depts: [], groups: ['視效部|未分組'] })), ['丁']);
assert.deepEqual(names(visiblePeople(people, { denied: true, admin: false, depts: ['前製部'], groups: [] })), []);
assert.deepEqual(names(visiblePeople(people, { depts: [], groups: [] })), []);
});
+251
View File
@@ -0,0 +1,251 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, readFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { applyPlans, createPlanStore, normalizePlans, planStatus, reconcilePlans } from '../plans.js';
const people = [
{ source: 'hr-sync', employeeNumber: '1001', name: '甲', dept: '動畫部', group: 'AA1', company: '夢想創造', h1Start: 1, h1End: 6, h2Start: 7, h2End: 12, role: 'A - 藝術家', monthlyCost: 50000 },
{ source: 'hr-sync', employeeNumber: '1002', name: '乙', dept: '動畫部', group: 'AA1', company: '夢想創造', h1Start: 1, h1End: 6, h2Start: 7, h2End: 12, role: 'P - 製作', monthlyCost: 40000 },
];
const hire = { id: 'h1', name: '動畫師(3 月)', dept: '動畫部', group: 'AA1', role: 'A - 藝術家', salaryType: 'monthly', amount: 45000, startMonth: '2027-03' };
test('normalizePlans rejects bad input and keeps good input', () => {
assert.deepEqual(normalizePlans({}), { departures: [], hires: [], transfers: [], history: [] });
assert.throws(() => normalizePlans({ departures: [{ employeeNumber: '1001', lastMonth: '2027-13' }] }));
assert.throws(() => normalizePlans({ departures: [{ employeeNumber: '1001', lastMonth: '2027-02' }, { employeeNumber: '1001', lastMonth: '2027-03' }] }));
assert.throws(() => normalizePlans({ hires: [{ ...hire, role: 'O - 外包' }] }));
assert.throws(() => normalizePlans({ hires: [{ ...hire, endMonth: '2027-01' }] }));
const plans = normalizePlans({ departures: [{ employeeNumber: '1001', lastMonth: '2027-04', note: ' 提前 離開 ' }], hires: [hire] });
assert.equal(plans.departures[0].note, '提前 離開');
assert.equal(plans.hires[0].amount, 45000);
});
test('applyPlans with no plans returns the same list (no change)', () => {
assert.equal(applyPlans(people, { departures: [], hires: [] }, { year: 2027 }), people);
});
test('planned departure trims months; leaving before the year removes the whole year', () => {
const plans = normalizePlans({ departures: [{ employeeNumber: '1001', lastMonth: '2027-04' }, { employeeNumber: '1002', lastMonth: '2026-12' }] });
const [a, b] = applyPlans(people, plans, { year: 2027 });
assert.equal(a.h1End, 4); assert.equal(a.plannedLeave, '2027-04');
assert.ok(!a.h2Start || !a.h2End);
assert.ok(!b.h1Start && !b.h2Start);
assert.equal(people[0].h1End, 6, 'original HR rows untouched');
});
test('planned hire is added as a read-only planned row', () => {
const out = applyPlans(people, normalizePlans({ hires: [hire] }), { year: 2027 });
const row = out.find(p => p.source === 'planned');
assert.equal(out.length, 3);
assert.equal(row.plannedHire, '2027-03');
assert.equal(row.h1Start, 3);
assert.equal(row.dept, '動畫部');
});
test('planStatus marks pending and overdue with the auto-removal month', () => {
const plans = normalizePlans({ departures: [{ employeeNumber: '1001', lastMonth: '2027-04' }], hires: [hire] });
const st = planStatus(plans, people, new Date('2027-05-15T00:00:00'));
assert.equal(st.departures[0].status, 'overdue');
assert.equal(st.departures[0].autoRemoveAfter, '2027-05');
assert.equal(st.hires[0].status, 'overdue');
assert.equal(st.overdue, 2);
assert.equal(planStatus(plans, people, new Date('2027-01-10T00:00:00')).departures[0].status, 'pending');
});
test('reconcilePlans removes plans once HR shows the result', () => {
const plans = normalizePlans({
departures: [{ employeeNumber: '1001', lastMonth: '2027-04' }, { employeeNumber: '1002', lastMonth: '2027-05' }, { employeeNumber: '9999', lastMonth: '2027-02' }],
hires: [{ ...hire, createdAt: '2026-11-17T00:00:00Z' }, { ...hire, id: 'h2', name: '王小明', startMonth: '2027-06' }],
});
const hr = [
{ ...people[0], leaveDate: '2027-04-30' },
people[1],
{ source: 'hr-sync', employeeNumber: '2001', name: '新同事', dept: '動畫部', hireDate: '2027-03-16' },
{ source: 'hr-sync', employeeNumber: '2002', name: '王小明', dept: '動畫部', hireDate: '2027-06-01' },
];
const { plans: next, removed } = reconcilePlans(plans, hr, new Date('2027-03-20T00:00:00'));
assert.deepEqual(next.departures.map(d => d.employeeNumber), ['1002']);
assert.deepEqual(next.hires, []);
assert.deepEqual(removed.map(r => r.reason).sort(), ['hr_joined', 'hr_joined', 'hr_leave_date', 'hr_left']);
assert.equal(removed.find(r => r.label === '動畫師(3 月)').matched, '新同事(2001)');
assert.equal(next.history.length, 4);
});
test('reconcilePlans: people hired before the plan was made do not match; expired plans go after a 1-month grace', () => {
const plans = normalizePlans({ departures: [{ employeeNumber: '1001', lastMonth: '2027-04' }], hires: [{ ...hire, createdAt: '2027-03-01T00:00:00Z' }] });
const hr = [...people, { source: 'hr-sync', employeeNumber: '2001', name: '舊同事', dept: '動畫部', hireDate: '2027-02-10' }];
assert.equal(reconcilePlans(plans, hr, new Date('2027-04-20T00:00:00')).removed.length, 0, 'old colleague does not match; hire still inside its grace month');
const late = reconcilePlans(plans, hr, new Date('2027-06-02T00:00:00'));
assert.deepEqual(late.removed.map(r => r.reason), ['expired', 'expired']);
assert.equal(late.plans.departures.length + late.plans.hires.length, 0);
});
test('reconcilePlans does nothing when the HR list is empty (HR unavailable)', () => {
const plans = normalizePlans({ departures: [{ employeeNumber: '1001', lastMonth: '2027-04' }] });
const result = reconcilePlans(plans, [], new Date('2028-01-01T00:00:00'));
assert.equal(result.plans, plans);
assert.equal(result.removed.length, 0);
});
test('plan store saves to a private file and reloads', async () => {
const dir = await mkdtemp(join(tmpdir(), 'plans-'));
const path = join(dir, 'planned-changes.json');
const store = createPlanStore(path);
assert.deepEqual(await store.load(), { departures: [], hires: [], transfers: [], history: [] });
await store.save({ hires: [hire] });
assert.equal(JSON.parse(await readFile(path, 'utf8')).hires[0].id, 'h1');
assert.equal((await createPlanStore(path).load()).hires.length, 1);
await assert.rejects(store.save({ hires: [{ ...hire, amount: -1 }] }));
assert.equal((await store.load()).hires.length, 1);
});
// ---- 預計轉調 ----
const transfer = { employeeNumber: '1001', toDept: '業務部', effectiveMonth: '2027-01', fromDept: '動畫部' };
test('預計轉調:欄位不齊、同一人重複都不收', () => {
assert.equal(normalizePlans({ transfers: [transfer] }).transfers.length, 1);
assert.equal(normalizePlans({}).transfers.length, 0);
assert.throws(() => normalizePlans({ transfers: [{ ...transfer, toDept: '' }] }), RangeError);
assert.throws(() => normalizePlans({ transfers: [{ ...transfer, effectiveMonth: '2027-13' }] }), RangeError);
assert.throws(() => normalizePlans({ transfers: [transfer, { ...transfer, toDept: '前製部' }] }), RangeError);
});
test('一月生效的轉調:整年算新部門,不拆成兩段', () => {
const out = applyPlans(people, normalizePlans({ transfers: [transfer] }), { year: 2027 });
assert.equal(out.length, people.length);
const person = out.find(p => p.employeeNumber === '1001');
assert.equal(person.dept, '業務部');
assert.equal(person.plannedTransfer, '2027-01');
assert.equal(person.h1Start, 1);
assert.equal(person.h2End, 12);
assert.equal(out.find(p => p.employeeNumber === '1002').dept, '動畫部');
});
test('年度中間生效的轉調:拆成前段原部門、後段新部門,月份不重疊', () => {
const plans = normalizePlans({ transfers: [{ ...transfer, toDept: '業務部', toGroup: '業務組', effectiveMonth: '2027-07' }] });
const out = applyPlans(people, plans, { year: 2027 });
const rows = out.filter(p => p.employeeNumber === '1001');
assert.equal(rows.length, 2);
const before = rows.find(p => p.transferSplit === 'before');
const after = rows.find(p => p.transferSplit === 'after');
assert.equal(before.dept, '動畫部');
assert.deepEqual([before.h1Start, before.h1End, before.h2Start, before.h2End], [1, 6, '', '']);
assert.equal(after.dept, '業務部');
assert.equal(after.group, '業務組');
assert.deepEqual([after.h1Start, after.h1End, after.h2Start, after.h2End], ['', '', 7, 12]);
});
test('生效月份在報表年度之後先不套用,在之前則整年算新部門', () => {
const later = applyPlans(people, normalizePlans({ transfers: [{ ...transfer, effectiveMonth: '2028-03' }] }), { year: 2027 });
assert.equal(later.find(p => p.employeeNumber === '1001').dept, '動畫部');
const earlier = applyPlans(people, normalizePlans({ transfers: [{ ...transfer, effectiveMonth: '2026-09' }] }), { year: 2027 });
const rows = earlier.filter(p => p.employeeNumber === '1001');
assert.equal(rows.length, 1);
assert.equal(rows[0].dept, '業務部');
});
test('HR 同步到目標部門後自動移除,紀錄留在 history', () => {
const plans = normalizePlans({ transfers: [transfer] });
const waiting = reconcilePlans(plans, people, new Date('2027-01-15T00:00:00Z'));
assert.equal(waiting.removed.length, 0);
const arrived = people.map(p => (p.employeeNumber === '1001' ? { ...p, dept: '業務部' } : p));
const done = reconcilePlans(plans, arrived, new Date('2027-01-15T00:00:00Z'));
assert.equal(done.plans.transfers.length, 0);
assert.equal(done.removed[0].kind, 'transfer');
assert.equal(done.removed[0].reason, 'hr_transferred');
assert.equal(done.plans.history.at(-1).reason, 'hr_transferred');
});
test('有指定組別時,組也要對上才算完成;過了寬限期會自動移除', () => {
const plans = normalizePlans({ transfers: [{ ...transfer, toGroup: '業務組' }] });
const deptOnly = people.map(p => (p.employeeNumber === '1001' ? { ...p, dept: '業務部', group: '別組' } : p));
assert.equal(reconcilePlans(plans, deptOnly, new Date('2027-01-15T00:00:00Z')).removed.length, 0);
const late = reconcilePlans(plans, people, new Date('2027-03-15T00:00:00Z'));
assert.equal(late.removed[0].reason, 'expired');
assert.equal(late.plans.transfers.length, 0);
});
test('HR 把人調到別的地方=衝突,不自動移除,狀態標成 conflict', () => {
const plans = normalizePlans({ transfers: [transfer] });
const elsewhere = people.map(p => (p.employeeNumber === '1001' ? { ...p, dept: '視效部' } : p));
const kept = reconcilePlans(plans, elsewhere, new Date('2027-01-15T00:00:00Z'));
assert.equal(kept.plans.transfers.length, 1);
const status = planStatus(kept.plans, elsewhere, new Date('2027-01-15T00:00:00Z'));
assert.equal(status.transfers[0].status, 'conflict');
assert.equal(status.transfers[0].dept, '視效部');
assert.equal(status.conflicts, 1);
assert.equal(planStatus(plans, people, new Date('2027-01-15T00:00:00Z')).transfers[0].status, 'pending');
});
// ---- 預計轉調:主管職 ----
const mgrPeople = [
{ source: 'hr-sync', employeeNumber: '2001', name: '組長', dept: '廣告部', group: 'AD組', company: '夢想創造', h1Start: 1, h1End: 6, h2Start: 7, h2End: 12, role: 'A - 藝術家', isManager: true, supervisorOf: [{ deptName: 'AD組' }] },
{ source: 'hr-sync', employeeNumber: '2002', name: '組員', dept: '廣告部', group: 'AD組', company: '夢想創造', h1Start: 1, h1End: 6, h2Start: 7, h2End: 12, role: 'A - 藝術家', isManager: false, supervisorOf: [] },
];
const mgrPlan = { employeeNumber: '2001', toDept: '業務部', effectiveMonth: '2027-01', fromDept: '廣告部' };
test('轉調預設卸任主管職;指定接任者就在模擬裡變成主管', () => {
const plans = normalizePlans({ transfers: [{ ...mgrPlan, successorEmployeeNumber: '2002' }] });
assert.equal(plans.transfers[0].keepManager, false);
const out = applyPlans(mgrPeople, plans, { year: 2027 });
const moverRow = out.find(p => p.employeeNumber === '2001');
assert.equal(moverRow.dept, '業務部');
assert.equal(moverRow.isManager, false);
assert.deepEqual(moverRow.supervisorOf, []);
const successor = out.find(p => p.employeeNumber === '2002');
assert.equal(successor.isManager, true);
assert.equal(successor.plannedManager, true);
assert.equal(successor.dept, '廣告部');
});
test('設定保留主管職時,轉調後主管身分不動', () => {
const plans = normalizePlans({ transfers: [{ ...mgrPlan, keepManager: true }] });
const out = applyPlans(mgrPeople, plans, { year: 2027 });
const moverRow = out.find(p => p.employeeNumber === '2001');
assert.equal(moverRow.isManager, true);
assert.deepEqual(moverRow.supervisorOf, [{ deptName: 'AD組' }]);
});
test('年中生效時,生效月份之前那一段還是原單位的主管', () => {
const plans = normalizePlans({ transfers: [{ ...mgrPlan, effectiveMonth: '2027-07' }] });
const rows = applyPlans(mgrPeople, plans, { year: 2027 }).filter(p => p.employeeNumber === '2001');
assert.equal(rows.length, 2);
const before = rows.find(p => p.transferSplit === 'before');
const after = rows.find(p => p.transferSplit === 'after');
assert.equal(before.dept, '廣告部');
assert.equal(before.isManager, true);
assert.equal(after.dept, '業務部');
assert.equal(after.isManager, false);
});
test('接任者不能是本人;工號格式不對也不收', () => {
assert.throws(() => normalizePlans({ transfers: [{ ...mgrPlan, successorEmployeeNumber: '2001' }] }), RangeError);
assert.throws(() => normalizePlans({ transfers: [{ ...mgrPlan, successorEmployeeNumber: '壞 工號' }] }), RangeError);
});
test('HR 部門對了但主管還沒處理:不移除、不過期,狀態是 manager_pending', () => {
const plans = normalizePlans({ transfers: [mgrPlan] });
// HR 調了部門,但主管身分還掛著
const halfDone = mgrPeople.map(p => (p.employeeNumber === '2001' ? { ...p, dept: '業務部' } : p));
const late = new Date('2027-06-15T00:00:00Z');
const result = reconcilePlans(plans, halfDone, late);
assert.equal(result.removed.length, 0);
assert.equal(result.plans.transfers.length, 1);
const status = planStatus(plans, halfDone, late);
assert.equal(status.transfers[0].status, 'manager_pending');
assert.equal(status.managerPending, 1);
assert.deepEqual(status.transfers[0].leads, ['AD組']);
});
test('HR 連主管也處理好了才自動移除', () => {
const plans = normalizePlans({ transfers: [{ ...mgrPlan, successorEmployeeNumber: '2002' }] });
const deptOnly = mgrPeople.map(p => (p.employeeNumber === '2001' ? { ...p, dept: '業務部', isManager: false, supervisorOf: [] } : p));
// 接任者在 HR 還不是主管
assert.equal(reconcilePlans(plans, deptOnly, new Date('2027-01-15T00:00:00Z')).removed.length, 0);
const allDone = deptOnly.map(p => (p.employeeNumber === '2002' ? { ...p, isManager: true } : p));
const done = reconcilePlans(plans, allDone, new Date('2027-01-15T00:00:00Z'));
assert.equal(done.plans.transfers.length, 0);
assert.equal(done.removed[0].reason, 'hr_transferred');
});
+54
View File
@@ -0,0 +1,54 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { changesFor } from '../scope-view.js';
// 部長看得到的人員異動:只有姓名、離開或加入、生效月份。
// 不分離職或轉調,也不說轉調去哪裡。
const model = {
people: [
{ employeeNumber: '1', name: '走的人', dept: '廣告部', plannedLeave: '2027-04' },
{ employeeNumber: '2', name: '轉走的人', dept: '業務部', plannedTransfer: '2027-01' },
{ employeeNumber: '3', name: '轉來的人', dept: '廣告部', plannedTransfer: '2027-02' },
{ employeeNumber: '4', name: '沒事的人', dept: '廣告部' },
{ name: '新人', dept: '廣告部', source: 'planned', plannedHire: '2027-03' },
],
};
const plans = { transfers: [
{ employeeNumber: '2', fromDept: '廣告部', toDept: '業務部', effectiveMonth: '2027-01' },
{ employeeNumber: '3', fromDept: '視效部', toDept: '廣告部', effectiveMonth: '2027-02' },
] };
test('列出離開與加入,依生效月份排序,沒有異動的人不出現', () => {
assert.deepEqual(changesFor('廣告部', model, plans), [
{ kind: 'leave', name: '轉走的人', month: '2027-01' },
{ kind: 'join', name: '轉來的人', month: '2027-02' },
{ kind: 'join', name: '新人', month: '2027-03' },
{ kind: 'leave', name: '走的人', month: '2027-04' },
]);
});
test('不洩漏轉調去哪裡,也不分離職或轉調', () => {
for (const change of changesFor('廣告部', model, plans)) {
assert.deepEqual(Object.keys(change).sort(), ['kind', 'month', 'name']);
assert.ok(['leave', 'join'].includes(change.kind));
}
});
test('年中轉調拆成兩段時,前段不會在原部門變成「加入」', () => {
const split = { people: [
{ employeeNumber: '5', name: '年中轉的人', dept: '廣告部', plannedTransfer: '2027-07', transferSplit: 'before' },
{ employeeNumber: '5', name: '年中轉的人', dept: '業務部', plannedTransfer: '2027-07', transferSplit: 'after' },
] };
const mid = { transfers: [{ employeeNumber: '5', fromDept: '廣告部', toDept: '業務部', effectiveMonth: '2027-07' }] };
assert.deepEqual(changesFor('廣告部', split, mid), [{ kind: 'leave', name: '年中轉的人', month: '2027-07' }]);
assert.deepEqual(changesFor('業務部', split, mid), [{ kind: 'join', name: '年中轉的人', month: '2027-07' }]);
});
test('轉出的部門也看得到那個人離開', () => {
assert.deepEqual(changesFor('視效部', model, plans), [{ kind: 'leave', name: '轉來的人', month: '2027-02' }]);
});
test('沒有預排、或部門沒人異動時回空陣列', () => {
assert.deepEqual(changesFor('動畫部', model, plans), []);
assert.deepEqual(changesFor('廣告部', { people: [] }, null), []);
});
+69 -19
View File
@@ -6,9 +6,16 @@ import { generateKeyPairSync, sign } from 'node:crypto';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DatabaseSync } from 'node:sqlite';
const node = process.execPath;
// 資料存在 <資料夾>/leadboard.db 的 documents 表;測試直接讀資料庫確認有存進去。
function stored(dataDir, name) {
const db = new DatabaseSync(join(dataDir, 'leadboard.db'), { readOnly: true });
try { return db.prepare('SELECT body FROM documents WHERE name = ?').get(name)?.body ?? null; } finally { db.close(); }
}
async function waitFor(url) {
for (let attempt = 0; attempt < 40; attempt += 1) {
try {
@@ -34,6 +41,19 @@ test('development preview serves synthetic data and health', async (t) => {
assert.equal((await bootstrap.json()).source, 'synthetic-demo');
});
test('the shared button stylesheet is served and every page links it', async (t) => {
const child = start({ PORT: '18095', HOST: '127.0.0.1', NODE_ENV: 'development' });
t.after(() => child.kill());
await waitFor('http://127.0.0.1:18095/api/health');
const css = await fetch('http://127.0.0.1:18095/buttons.css');
assert.equal(css.status, 200);
assert.match(css.headers.get('content-type'), /^text\/css/);
assert.match(await css.text(), /prefers-reduced-motion/);
for (const file of ['index.html', 'my.html', 'archive.html']) {
assert.match(await readFile(file, 'utf8'), /<link rel="stylesheet" href="\/buttons\.css">/, file);
}
});
test('production fails closed when OIDC settings are unavailable', async (t) => {
const child = start({ PORT: '18082', HOST: '127.0.0.1', NODE_ENV: 'production', OIDC_ISSUER: '', OIDC_CLIENT_ID: '', OIDC_CLIENT_SECRET: '' });
t.after(() => child.kill());
@@ -70,15 +90,15 @@ test('configured production redirects pages and protects APIs', async (t) => {
assert.equal((await fetch('http://127.0.0.1:18083/api/bootstrap')).status, 401);
const logout = await fetch('http://127.0.0.1:18083/api/auth/logout', {
method: 'POST', redirect: 'manual',
headers: { cookie: 'pm_board_session=invalid; pm_board_login=pending' },
headers: { cookie: 'leadboard_session=invalid; leadboard_login=pending' },
});
assert.equal(logout.status, 302);
assert.equal(logout.headers.get('location'), '/logged-out');
assert.match(logout.headers.get('set-cookie'), /pm_board_session=;.*Max-Age=0/);
assert.match(logout.headers.get('set-cookie'), /leadboard_session=;.*Max-Age=0/);
const loggedOut = await fetch('http://127.0.0.1:18083/logged-out');
assert.equal(loggedOut.status, 200);
assert.match(await loggedOut.text(), /已登出/);
assert.equal((await fetch('http://127.0.0.1:18083/api/bootstrap', { headers: { cookie: 'pm_board_session=invalid' } })).status, 401);
assert.equal((await fetch('http://127.0.0.1:18083/api/bootstrap', { headers: { cookie: 'leadboard_session=invalid' } })).status, 401);
assert.equal((await fetch('http://127.0.0.1:18083/api/auth/logout', {
method: 'POST', redirect: 'manual', headers: { origin: 'https://other.example.test' },
})).status, 403);
@@ -148,10 +168,10 @@ test('a signed-in session is revoked by logout and cannot be replayed', async (t
nonce = authorize.searchParams.get('nonce');
const state = authorize.searchParams.get('state');
const callback = await fetch(`${base}/api/auth/callback/authentik?state=${state}&code=test-code`, {
redirect: 'manual', headers: { cookie: `pm_board_login=${state}` },
redirect: 'manual', headers: { cookie: `leadboard_login=${state}` },
});
assert.equal(callback.status, 302);
const cookie = callback.headers.getSetCookie().find(value => value.startsWith('pm_board_session=')).split(';')[0];
const cookie = callback.headers.getSetCookie().find(value => value.startsWith('leadboard_session=')).split(';')[0];
const app = await fetch(`${base}/`, { headers: { cookie } });
assert.equal(app.status, 200);
const appHtml = await app.text();
@@ -180,7 +200,7 @@ test('a signed-in session is revoked by logout and cannot be replayed', async (t
body: JSON.stringify({ role: 'A - 藝術家', weeklyWorkDays: 3, h1Start: 1, h1End: 6 }),
});
assert.equal(override.status, 200);
const savedOverrides = JSON.parse(await readFile(join(dataDir, 'cost-overrides.json'), 'utf8'));
const savedOverrides = JSON.parse(stored(dataDir, 'cost-overrides.json'));
assert.equal(savedOverrides['20150906'].role, 'A - 藝術家');
const updatedModel = await fetch(`${base}/api/hr/cost-model`, { headers: { cookie } });
const updatedPerson = (await updatedModel.json()).baseData.find(person => person.employeeNumber === '20150906');
@@ -226,16 +246,16 @@ test('a signed-in session is revoked by logout and cannot be replayed', async (t
assert.equal((await fetch(`${base}/`, { headers: { cookie }, redirect: 'manual' })).status, 302);
// A stale callback starts one fresh login, then shows a page instead of looping.
const stale = await fetch(`${base}/api/auth/callback/authentik?state=gone&code=test-code`, { redirect: 'manual', headers: { cookie: 'pm_board_login=gone' } });
const stale = await fetch(`${base}/api/auth/callback/authentik?state=gone&code=test-code`, { redirect: 'manual', headers: { cookie: 'leadboard_login=gone' } });
assert.equal(stale.status, 302);
assert.equal(stale.headers.get('location'), '/api/auth/login');
const staleAgain = await fetch(`${base}/api/auth/callback/authentik?state=gone&code=test-code`, { redirect: 'manual', headers: { cookie: 'pm_board_login=gone; pm_board_login_retry=1' } });
const staleAgain = await fetch(`${base}/api/auth/callback/authentik?state=gone&code=test-code`, { redirect: 'manual', headers: { cookie: 'leadboard_login=gone; leadboard_login_retry=1' } });
assert.equal(staleAgain.status, 400);
assert.match(await staleAgain.text(), /重新登入/);
// Two tabs logging in at once: the earlier tab's state still completes.
const tabA = new URL((await fetch(`${base}/api/auth/login`, { redirect: 'manual' })).headers.get('location'));
const tabB = await fetch(`${base}/api/auth/login`, { redirect: 'manual', headers: { cookie: `pm_board_login=${tabA.searchParams.get('state')}` } });
const bothCookie = tabB.headers.getSetCookie().find(value => value.startsWith('pm_board_login=')).split(';')[0];
const tabB = await fetch(`${base}/api/auth/login`, { redirect: 'manual', headers: { cookie: `leadboard_login=${tabA.searchParams.get('state')}` } });
const bothCookie = tabB.headers.getSetCookie().find(value => value.startsWith('leadboard_login=')).split(';')[0];
nonce = tabA.searchParams.get('nonce');
const tabADone = await fetch(`${base}/api/auth/callback/authentik?state=${tabA.searchParams.get('state')}&code=test-code`, { redirect: 'manual', headers: { cookie: bothCookie } });
assert.equal(tabADone.status, 302);
@@ -246,9 +266,9 @@ test('a signed-in session is revoked by logout and cannot be replayed', async (t
nonce = secondAuthorize.searchParams.get('nonce');
const secondState = secondAuthorize.searchParams.get('state');
const secondCallback = await fetch(`${base}/api/auth/callback/authentik?state=${secondState}&code=test-code`, {
redirect: 'manual', headers: { cookie: `pm_board_login=${secondState}` },
redirect: 'manual', headers: { cookie: `leadboard_login=${secondState}` },
});
const secondCookie = secondCallback.headers.getSetCookie().find(value => value.startsWith('pm_board_session=')).split(';')[0];
const secondCookie = secondCallback.headers.getSetCookie().find(value => value.startsWith('leadboard_session=')).split(';')[0];
const companyLogout = await fetch(`${base}/api/auth/company-logout`, {
method: 'POST', redirect: 'manual', headers: { cookie: secondCookie, origin: 'https://127.0.0.1:18085' },
});
@@ -258,7 +278,7 @@ test('a signed-in session is revoked by logout and cannot be replayed', async (t
assert.equal(companyTarget.searchParams.get('post_logout_redirect_uri'), 'https://127.0.0.1:18085/logged-out');
assert(companyTarget.searchParams.has('id_token_hint'));
assert.equal((await fetch(`${base}/api/auth/me`, { headers: { cookie: secondCookie } })).status, 401);
const returnedCookie = companyLogout.headers.getSetCookie().find(value => value.startsWith('pm_board_company_logout=')).split(';')[0];
const returnedCookie = companyLogout.headers.getSetCookie().find(value => value.startsWith('leadboard_company_logout=')).split(';')[0];
const returnedPage = await fetch(`${base}/logged-out`, { headers: { cookie: returnedCookie } });
assert.match(await returnedPage.text(), /已從 MoonShine 公司帳號登出/);
});
@@ -289,7 +309,7 @@ test('contractors saved on the board persist across restarts in COST_MODEL_DATA_
const contractors = bootstrap.baseData.filter(person => person.role.startsWith('O'));
assert.deepEqual(contractors.map(person => person.name), ['測試外包']);
assert.equal(contractors[0].dayrate, '3000');
const file = JSON.parse(await readFile(join(dataDir, 'contractors.json'), 'utf8'));
const file = JSON.parse(stored(dataDir, 'contractors.json'));
assert.equal(file.length, 1);
});
@@ -370,9 +390,9 @@ async function signIn(base, provider) {
provider.nonce = authorize.searchParams.get('nonce');
const loginState = authorize.searchParams.get('state');
const callback = await fetch(`${base}/api/auth/callback/authentik?state=${loginState}&code=test-code`, {
redirect: 'manual', headers: { cookie: `pm_board_login=${loginState}` },
redirect: 'manual', headers: { cookie: `leadboard_login=${loginState}` },
});
const cookie = callback.headers.getSetCookie().find(value => value.startsWith('pm_board_session='))?.split(';')[0];
const cookie = callback.headers.getSetCookie().find(value => value.startsWith('leadboard_session='))?.split(';')[0];
return { callback, cookie };
}
@@ -405,7 +425,8 @@ test('login flow: any company account gets in; only the top admin reaches the bo
for (const [method, path] of [['GET', '/api/model'], ['GET', '/api/bootstrap'], ['GET', '/api/hr/cost-model'], ['GET', '/api/hr/employees'],
['GET', '/api/permissions'], ['POST', '/api/permissions'], ['GET', '/api/archive'], ['PUT', '/api/cost-model/settings'],
['PUT', '/api/cost-model/contractors'], ['POST', '/api/year/next'], ['POST', '/api/hr/cost-model/employees/30000001'],
['DELETE', '/api/hr/cost-model/employees/30000001/overrides/role']]) {
['DELETE', '/api/hr/cost-model/employees/30000001/overrides/role'], ['GET', '/api/anchors'], ['POST', '/api/anchors'],
['GET', '/api/hr/organizations'], ['GET', '/api/hr/employees/30000001/salary'], ['GET', '/api/names'], ['PUT', '/api/names'], ['GET', '/api/plans'], ['PUT', '/api/plans']]) {
const response = await fetch(`${base}${path}`, { method, headers: { ...headers, 'content-type': 'application/json' }, body: method === 'GET' ? undefined : '{}' });
assert.equal(response.status, 403, `${method} ${path}`);
}
@@ -421,13 +442,19 @@ test('login flow: any company account gets in; only the top admin reaches the bo
const admin = await signIn(base, provider);
assert.equal(admin.callback.headers.get('location'), '/');
assert.equal((await fetch(`${base}/`, { headers: { cookie: admin.cookie }, redirect: 'manual' })).status, 200);
assert.equal((await fetch(`${base}/permissions`, { headers: { cookie: admin.cookie }, redirect: 'manual' })).status, 200);
// 權限管理搬進主看板後,舊網址導回看板並直接打開那個區塊。
const permRedirect = await fetch(`${base}/permissions`, { headers: { cookie: admin.cookie }, redirect: 'manual' });
assert.equal(permRedirect.status, 302);
assert.equal(permRedirect.headers.get('location'), '/?view=permissions');
// 部署重新啟動:兩個人都不用重新登入;檔案裡沒有 cookie 原始值。
child.kill('SIGTERM');
await new Promise(resolve => child.once('exit', resolve));
const saved = await readFile(join(dataDir, 'sessions.json'), 'utf8');
const saved = stored(dataDir, 'sessions.json');
assert.ok(!saved.includes(admin.cookie.split('=')[1]) && !saved.includes(staff.cookie.split('=')[1]));
// 登入資料(含 token、工號)加密存放。
assert.equal(JSON.parse(saved).version, 2);
assert.ok(!saved.includes('20150906') && !saved.includes('refreshToken') && !saved.includes('accessToken'));
child = start(env);
await waitFor(`${base}/api/health`);
assert.equal((await fetch(`${base}/api/auth/me`, { headers: { cookie: admin.cookie } })).status, 200);
@@ -443,3 +470,26 @@ test('login flow: any company account gets in; only the top admin reaches the bo
assert.equal((await fetch(`${base}/api/auth/me`, { headers })).status, 401);
assert.equal((await fetch(`${base}/api/auth/me`, { headers: { cookie: admin.cookie } })).status, 200);
});
test('planned hires saved in 預排異動 appear on the board and persist in COST_MODEL_DATA_DIR', async (t) => {
const dataDir = await mkdtemp(join(tmpdir(), 'pm-board-plans-'));
t.after(() => rm(dataDir, { recursive: true, force: true }));
const env = { PORT: '18093', HOST: '127.0.0.1', NODE_ENV: 'development', COST_MODEL_DATA_DIR: dataDir };
const base = 'http://127.0.0.1:18093';
const child = start(env);
t.after(() => child.kill());
await waitFor(`${base}/api/health`);
const before = (await (await fetch(`${base}/api/bootstrap`)).json()).baseData.length;
const empty = await (await fetch(`${base}/api/plans`)).json();
assert.deepEqual(empty.plans, { departures: [], hires: [], transfers: [], history: [] });
const bad = await fetch(`${base}/api/plans`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ hires: [{ id: 'x' }] }) });
assert.equal(bad.status, 400);
const hire = { id: 'h1', name: '預排動畫師', dept: '動畫部', role: 'A - 藝術家', salaryType: 'monthly', amount: 45000, startMonth: '2027-03' };
const saved = await fetch(`${base}/api/plans`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ hires: [hire] }) });
assert.equal(saved.status, 200);
assert.ok(['pending', 'overdue'].includes((await saved.json()).status.hires[0].status));
const after = (await (await fetch(`${base}/api/bootstrap`)).json()).baseData;
assert.equal(after.length, before + 1);
assert.equal(after.find(p => p.source === 'planned').name, '預排動畫師');
assert.equal(JSON.parse(stored(dataDir, 'planned-changes.json')).hires[0].id, 'h1');
});
+45 -8
View File
@@ -1,42 +1,47 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, readFile, rm, stat } from 'node:fs/promises';
import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createSessionStore } from '../session-store.js';
const SECRET = 'unit-test-runtime-secret';
test('sessions survive a restart; the file has no raw session id, no caches and no expired sessions', async (t) => {
const dir = await mkdtemp(join(tmpdir(), 'pm-board-sessions-'));
t.after(() => rm(dir, { recursive: true, force: true }));
const path = join(dir, 'sessions.json');
let clock = 1_000_000;
const store = createSessionStore(path, { now: () => clock });
store.set('raw-cookie-value', { claims: { employee_number: '100' }, expiresAt: clock + 1000, accessToken: 'a', refreshToken: 'r', rosterCache: { records: ['secret'] }, permissionCache: { value: 1 } });
const store = createSessionStore(path, { now: () => clock, secret: SECRET });
store.set('raw-cookie-value', { claims: { employee_number: '100' }, expiresAt: clock + 1000, accessToken: 'ACCESS-TOKEN-VALUE', refreshToken: 'REFRESH-TOKEN-VALUE', rosterCache: { records: ['secret'] }, permissionCache: { value: 1 } });
store.set('old-cookie', { claims: { employee_number: '200' }, expiresAt: clock - 1 });
store.flush();
const text = await readFile(path, 'utf8');
assert.ok(!text.includes('raw-cookie-value'));
assert.ok(!text.includes('rosterCache') && !text.includes('secret') && !text.includes('permissionCache'));
assert.ok(!text.includes('"200"'));
// 登入資料加密:檔案裡看不到 token、工號。
assert.ok(!text.includes('REFRESH-TOKEN-VALUE') && !text.includes('ACCESS-TOKEN-VALUE') && !text.includes('employee_number'));
assert.equal(JSON.parse(text).version, 2);
assert.equal((await stat(path)).mode & 0o777, 0o600);
const restarted = createSessionStore(path, { now: () => clock });
const restarted = createSessionStore(path, { now: () => clock, secret: SECRET });
assert.equal(restarted.load(), 1);
assert.equal(restarted.get('raw-cookie-value').claims.employee_number, '100');
assert.equal(restarted.get('raw-cookie-value').refreshToken, 'r');
assert.equal(restarted.get('raw-cookie-value').refreshToken, 'REFRESH-TOKEN-VALUE');
assert.equal(restarted.get('old-cookie'), undefined);
// 登出後重新啟動,也不會回來。
restarted.delete('raw-cookie-value');
restarted.flush();
assert.equal(createSessionStore(path, { now: () => clock }).load(), 0);
assert.equal(createSessionStore(path, { now: () => clock, secret: SECRET }).load(), 0);
// 過期的不載入。
const later = createSessionStore(path, { now: () => clock });
const later = createSessionStore(path, { now: () => clock, secret: SECRET });
later.set('x', { claims: {}, expiresAt: clock + 10 });
later.flush();
clock += 20;
assert.equal(createSessionStore(path, { now: () => clock }).load(), 0);
assert.equal(createSessionStore(path, { now: () => clock, secret: SECRET }).load(), 0);
});
test('without a data folder (local preview) sessions stay in memory only', () => {
@@ -46,3 +51,35 @@ test('without a data folder (local preview) sessions stay in memory only', () =>
assert.ok(store.get('a'));
store.flush();
});
test('a different secret cannot read the file; without a secret nothing is written', async (t) => {
const dir = await mkdtemp(join(tmpdir(), 'pm-board-sessions-key-'));
t.after(() => rm(dir, { recursive: true, force: true }));
const path = join(dir, 'sessions.json');
const store = createSessionStore(path, { secret: SECRET });
store.set('cookie', { claims: { employee_number: '100' }, expiresAt: Date.now() + 60_000, refreshToken: 'REFRESH' });
store.flush();
assert.equal(createSessionStore(path, { secret: 'another-runtime-secret' }).load(), 0);
assert.equal(createSessionStore(path, { secret: SECRET }).load(), 1);
const other = join(dir, 'none.json');
const memoryOnly = createSessionStore(other, { secret: '' });
memoryOnly.set('cookie', { claims: {}, expiresAt: Date.now() + 60_000 });
memoryOnly.flush();
await assert.rejects(readFile(other, 'utf8'), { code: 'ENOENT' });
});
test('an old unencrypted file is loaded once and rewritten encrypted', async (t) => {
const dir = await mkdtemp(join(tmpdir(), 'pm-board-sessions-old-'));
t.after(() => rm(dir, { recursive: true, force: true }));
const path = join(dir, 'sessions.json');
const { createHash } = await import('node:crypto');
const id = createHash('sha256').update('legacy-cookie').digest('hex');
await writeFile(path, JSON.stringify({ version: 1, sessions: { [id]: { claims: { employee_number: '100' }, expiresAt: Date.now() + 60_000, refreshToken: 'OLD-PLAIN-TOKEN' } } }));
const store = createSessionStore(path, { secret: SECRET });
assert.equal(store.load(), 1);
assert.equal(store.get('legacy-cookie').refreshToken, 'OLD-PLAIN-TOKEN');
const text = await readFile(path, 'utf8');
assert.equal(JSON.parse(text).version, 2);
assert.ok(!text.includes('OLD-PLAIN-TOKEN'));
});
+25
View File
@@ -37,3 +37,28 @@ test('invoice roles keep only bear / share / exclude per company and department'
assert.throws(() => normalizeSettings({ invoiceRoles: [] }), TypeError);
assert.deepEqual(applySettings({}, settings).invoiceRoles, settings.invoiceRoles);
});
test('CODA 分配規則經過驗證才保存,格式不對的整條跳過', () => {
const settings = normalizeSettings({
codaShareRules: [
{ company: '夢想創造', from: [' 業務部 '], to: ['前製部', '業務部', '動畫部', '前製部'], noDeptP: 1 },
{ from: [], to: ['前製部'] },
{ from: ['甲部'], to: [] },
{ from: ['甲部'], to: ['甲部'] },
'nope',
null,
['from', 'to'],
],
});
assert.deepEqual(settings.codaShareRules, [
{ company: '夢想創造', from: ['業務部'], to: ['前製部', '動畫部'], noDeptP: true },
]);
assert.deepEqual(applySettings({}, settings).codaShareRules, settings.codaShareRules);
});
test('沒有送 CODA 分配規則時設定不帶這個欄位,程式才會用內建預設', () => {
assert.equal('codaShareRules' in normalizeSettings({}), false);
assert.equal('codaShareRules' in applySettings({}, normalizeSettings({})), false);
assert.throws(() => normalizeSettings({ codaShareRules: 'x' }), TypeError);
assert.deepEqual(normalizeSettings({ codaShareRules: [] }).codaShareRules, []);
});
+234
View File
@@ -0,0 +1,234 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { MIGRATIONS, migrate, openDatabase } from '../db.js';
import { compareRecords, discover, importJson, records } from '../import-json.js';
import { openDataStorage } from '../data-store.js';
import { bind, bindFile, fileStorage, prefixed, sha256, sqliteStorage } from '../storage.js';
import { createAnchorStore } from '../anchor-store.js';
import { createArchiveStore } from '../archive-store.js';
import { createPermissionStore } from '../permissions.js';
import { createPlanStore } from '../plans.js';
import { createSessionStore } from '../session-store.js';
const quiet = { log() {}, warn() {} };
async function workspace(t) {
const dir = await mkdtemp(join(tmpdir(), 'leadboard-sqlite-'));
t.after(() => rm(dir, { recursive: true, force: true }));
return dir;
}
// 跟正式資料同樣的各種寫法:縮排 2 格、單行加換行、單行不換行、中文、跳脫字元。
async function seedJson(dir) {
await mkdir(join(dir, 'archives'), { recursive: true });
const files = {
'cost-overrides.json': `${JSON.stringify({ 20150906: { role: 'A - 藝術家', weeklyWorkDays: 3 }, abc: { isManager: true } }, null, 2)}`,
'contractors.json': JSON.stringify([{ row: 'c1', name: '王小明', dayrate: '3000' }, { row: 'c2', name: 'Lee "Q"\n', dayrate: '0' }], null, 2),
'board-settings.json': JSON.stringify({ rdGroups: ['夢想創造|RD'], params: { usdRate: 31.5 } }, null, 2),
'english-names.json': JSON.stringify({ byEmployee: { 20150906: 'Woody Yeh' }, byName: {} }, null, 2),
'permissions.json': `${JSON.stringify({ grants: { 20120201: { company: true } }, denied: ['20240407'], log: [{ at: 'x' }] })}\n`,
'anchors.json': `${JSON.stringify({ version: 1, years: { 2027: { anchors: [{ n: 1 }], peaks: { a: 1 }, version: 3 } } })}\n`,
'current-year.json': JSON.stringify({ year: 2027, log: [] }),
'month-overrides-2028.json': JSON.stringify({ 20150906: { h1Start: 2 } }, null, 2),
'archives/2026.json': `${JSON.stringify({ year: 2026, depts: [{ dept: 'A' }, { dept: 'B' }] })}\n`,
};
for (const [name, text] of Object.entries(files)) await writeFile(join(dir, name), text);
await writeFile(join(dir, 'anchors.json.123.tmp'), 'junk');
await writeFile(join(dir, 'note.txt'), 'not json');
return files;
}
test('migrations run once, in order, and can be re-run', () => {
const db = openDatabase(':memory:');
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(row => row.name);
for (const name of ['documents', 'import_log', 'schema_migrations']) assert.ok(tables.includes(name), name);
assert.deepEqual(migrate(db), []);
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM schema_migrations').get().n, MIGRATIONS.length);
const next = [...MIGRATIONS, { version: 2, name: 'extra', sql: 'CREATE TABLE extra (id INTEGER PRIMARY KEY) STRICT;' }];
assert.deepEqual(migrate(db, next), [2]);
assert.throws(() => migrate(db, MIGRATIONS), /不認得的版本 2/);
const broken = [...next, { version: 3, name: 'bad', sql: 'CREATE TABLE ok_then_fail (id INTEGER); SELECT * FROM nope;' }];
assert.throws(() => migrate(db, broken), /migration 3/);
assert.equal(db.prepare("SELECT COUNT(*) AS n FROM sqlite_master WHERE name = 'ok_then_fail'").get().n, 0, 'a failed migration rolls back');
});
test('sqlite storage keeps text verbatim and supports exclusive writes and prefixes', () => {
const storage = sqliteStorage(openDatabase(':memory:'));
assert.equal(storage.read('missing.json'), null);
const text = '{"a":"中文 \\u00e9"}\n';
storage.write('x.json', text);
assert.equal(storage.read('x.json'), text);
storage.write('x.json', 'next');
assert.equal(storage.read('x.json'), 'next');
storage.write('archives/2027.json', '1', { exclusive: true });
assert.throws(() => storage.write('archives/2027.json', '2', { exclusive: true }), { code: 'EEXIST' });
assert.equal(storage.read('archives/2027.json'), '1');
storage.write('archives/2026.json', '0');
assert.deepEqual(prefixed(storage, 'archives/').list(), ['2026.json', '2027.json']);
const row = storage.db.prepare('SELECT sha256, bytes FROM documents WHERE name = ?').get('x.json');
assert.deepEqual({ ...row }, { sha256: sha256('next'), bytes: 4 });
});
test('file storage matches the old behaviour (atomic, exclusive, private)', async (t) => {
const dir = await workspace(t);
const storage = fileStorage(join(dir, 'nested'));
assert.equal(storage.read('a.json'), null);
assert.deepEqual(storage.list('archives/'), []);
storage.write('a.json', 'one');
storage.write('archives/2027.json', 'x', { exclusive: true });
assert.throws(() => storage.write('archives/2027.json', 'y', { exclusive: true }), { code: 'EEXIST' });
assert.deepEqual(storage.list('archives/'), ['archives/2027.json']);
assert.deepEqual((await readdir(join(dir, 'nested'))).sort(), ['a.json', 'archives']);
const handle = bindFile(join(dir, 'nested', 'b.json'));
assert.equal(handle.read(), null);
handle.write('two');
assert.equal(await readFile(join(dir, 'nested', 'b.json'), 'utf8'), 'two');
});
test('records() counts records the way the verification reports them', () => {
assert.equal(records([1, 2, 3]).length, 3);
assert.equal(records({ grants: { a: 1, b: 2 }, denied: ['x'], log: [] }).length, 3);
assert.equal(records({ year: 2027, log: [{}, {}] }).length, 3);
assert.deepEqual(compareRecords({ a: [1, 2] }, { a: [1, 3] }).bad, ['a[1]']);
assert.deepEqual(compareRecords({ a: [1] }, { a: [1], b: 1 }).bad, ['b']);
});
test('import copies every JSON file verbatim, verifies each record, and leaves the JSON alone', async (t) => {
const dir = await workspace(t);
const files = await seedJson(dir);
assert.deepEqual(discover(dir), ['anchors.json', 'archives/2026.json', 'board-settings.json', 'contractors.json', 'cost-overrides.json',
'current-year.json', 'english-names.json', 'month-overrides-2028.json', 'permissions.json']);
const db = openDatabase(join(dir, 'leadboard.db'));
t.after(() => db.close());
const result = importJson({ dir, db });
assert.equal(result.ok, true);
assert.equal(result.imported, Object.keys(files).length);
assert.ok(result.records > 10);
const storage = sqliteStorage(db);
for (const [name, text] of Object.entries(files)) {
assert.equal(storage.read(name), text, name);
assert.equal(await readFile(join(dir, name), 'utf8'), text, `${name} untouched`);
}
assert.equal(storage.read('note.txt'), null);
assert.equal(storage.read('anchors.json.123.tmp'), null);
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM import_log WHERE ok = 1').get().n, 1);
});
test('the importer can be re-run: unchanged files are skipped, DB edits are never overwritten without --force', async (t) => {
const dir = await workspace(t);
const files = await seedJson(dir);
const db = openDatabase(join(dir, 'leadboard.db'));
t.after(() => db.close());
importJson({ dir, db });
const again = importJson({ dir, db });
assert.equal(again.ok, true);
assert.equal(again.imported, 0);
assert.equal(again.unchanged, Object.keys(files).length);
const storage = sqliteStorage(db);
storage.write('permissions.json', '{"grants":{},"denied":[],"log":[]}\n'); // 上線後在資料庫裡改過
const clash = importJson({ dir, db });
assert.equal(clash.ok, false);
assert.equal(clash.conflicts, 1);
assert.equal(storage.read('permissions.json'), '{"grants":{},"denied":[],"log":[]}\n', 'not overwritten');
assert.equal(importJson({ dir, db, mode: 'verify' }).ok, false);
const forced = importJson({ dir, db, force: true });
assert.equal(forced.ok, true);
assert.equal(storage.read('permissions.json'), files['permissions.json']);
await writeFile(join(dir, 'late.json'), '[1]');
const added = importJson({ dir, db });
assert.equal(added.imported, 1);
assert.equal(added.ok, true);
});
test('dry-run writes nothing; verify reports files the database lacks; a broken JSON file stops the whole batch', async (t) => {
const dir = await workspace(t);
await seedJson(dir);
const db = openDatabase(join(dir, 'leadboard.db'));
t.after(() => db.close());
const dry = importJson({ dir, db, mode: 'dry-run' });
assert.equal(dry.imported, 0);
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM documents').get().n, 0);
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM import_log').get().n, 0);
assert.equal(importJson({ dir, db, mode: 'verify' }).ok, false);
await writeFile(join(dir, 'sessions.json'), '{ not json');
const broken = importJson({ dir, db });
assert.equal(broken.ok, false);
assert.match(broken.problems[0], /sessions\.json/);
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM documents').get().n, 0, 'nothing imported');
});
test('the server storage imports once on first start and then trusts the database', async (t) => {
const dir = await workspace(t);
const files = await seedJson(dir);
const storage = openDataStorage(dir, { backend: 'sqlite', log: quiet });
assert.equal(storage.kind, 'sqlite');
assert.equal(storage.read('cost-overrides.json'), files['cost-overrides.json']);
storage.write('current-year.json', '{"year":2028,"log":[]}');
storage.db.close();
await writeFile(join(dir, 'current-year.json'), '{"year":2027,"log":[]}'); // JSON 之後怎麼變都不影響資料庫
const restarted = openDataStorage(dir, { backend: 'sqlite', log: quiet });
assert.equal(restarted.read('current-year.json'), '{"year":2028,"log":[]}');
restarted.db.close();
assert.equal(openDataStorage(dir, { backend: 'json', log: quiet }).kind, 'file');
});
test('the server storage refuses to start when the import cannot be verified', async (t) => {
const dir = await workspace(t);
await writeFile(join(dir, 'permissions.json'), '{ broken');
assert.throws(() => openDataStorage(dir, { backend: 'sqlite', log: quiet }), /不啟動/);
});
test('a fresh data folder starts with an empty database', async (t) => {
const dir = await workspace(t);
const storage = openDataStorage(dir, { backend: 'sqlite', log: quiet });
assert.equal(storage.read('anchors.json'), null);
storage.db.close();
});
test('permissions, plans, archives, sessions and anchors all persist through the SQLite storage', async () => {
const storage = sqliteStorage(openDatabase(':memory:'));
const permissions = createPermissionStore(bind(storage, 'permissions.json'));
await permissions.load();
await permissions.set({ employeeNumber: '20990101', grant: { company: true }, by: 'test' });
assert.equal(JSON.parse(storage.read('permissions.json')).grants['20990101'].company, true);
assert.equal((await createPermissionStore(bind(storage, 'permissions.json')).load()).grants['20990101'].company, true);
const hire = { id: 'h1', name: '預排動畫師', dept: '動畫部', role: 'A - 藝術家', salaryType: 'monthly', amount: 45000, startMonth: '2027-03' };
await createPlanStore(bind(storage, 'planned-changes.json')).save({ hires: [hire] });
assert.equal((await createPlanStore(bind(storage, 'planned-changes.json')).load()).hires[0].id, 'h1');
const archives = createArchiveStore(prefixed(storage, 'archives/'));
assert.deepEqual(await archives.list(), []);
await archives.save({ year: 2027, depts: [] });
assert.deepEqual(await archives.list(), [2027]);
assert.equal((await archives.get(2027)).year, 2027);
assert.equal(await archives.get(2026), null);
await assert.rejects(() => archives.save({ year: 2027, depts: [] }), /already archived/);
assert.equal(storage.read('archives/2027.json'), '{"year":2027,"depts":[]}\n');
const secret = 'a-long-enough-secret';
const sessions = createSessionStore(bind(storage, 'sessions.json'), { secret });
sessions.set('cookie-value', { claims: { employee_number: '1' }, expiresAt: Date.now() + 60_000 });
sessions.flush();
assert.equal(JSON.parse(storage.read('sessions.json')).version, 2);
assert.ok(!storage.read('sessions.json').includes('cookie-value'));
const restarted = createSessionStore(bind(storage, 'sessions.json'), { secret });
assert.equal(restarted.load(), 1);
assert.equal(restarted.get('cookie-value').claims.employee_number, '1');
const anchors = createAnchorStore(bind(storage, 'anchors.json'));
assert.equal(await anchors.hasAnchor(2027), false);
assert.equal(storage.read('anchors.json'), null, 'reading alone writes nothing');
});
test('a data folder with a store-written JSON set imports and loads back through the SQLite storage', async (t) => {
const dir = await workspace(t);
await createPermissionStore(bindFile(join(dir, 'permissions.json'))).set({ employeeNumber: '20990101', grant: { company: true }, by: 'test' });
await createArchiveStore(join(dir, 'archives')).save({ year: 2026, depts: [] });
const storage = openDataStorage(dir, { backend: 'sqlite', log: quiet });
assert.equal(storage.read('permissions.json'), await readFile(join(dir, 'permissions.json'), 'utf8'));
assert.equal((await createPermissionStore(bind(storage, 'permissions.json')).load()).grants['20990101'].company, true);
assert.deepEqual(await createArchiveStore(prefixed(storage, 'archives/')).list(), [2026]);
storage.db.close();
});