Compare 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
walkdoggo.yehandClaude Opus 5.5 1278974239 feat: 主看板金額依幣別顯示、核心參數加匯率、加語言與幣別切換
CI / build (push) Successful in 32s
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-11 17:37:15 +00:00
walkdoggo.yehandClaude Opus 5.5 cbc6829a45 feat: /my 加語言與幣別切換
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-11 17:37:13 +00:00
walkdoggo.yehandClaude Opus 5.5 ce9613c16e feat: /my 與模擬試算的金額依幣別顯示
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-11 17:37:11 +00:00
walkdoggo.yehandClaude Opus 5.5 106bd5382b build: 映像檔加入 i18n.js、english-names.js
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-11 17:37:10 +00:00
walkdoggo.yehandClaude Opus 5.5 f7aec7bff5 feat: 核心參數新增美金匯率 usdRate
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-11 17:37:08 +00:00
walkdoggo.yehandClaude Opus 5.5 a59abba067 feat: /api/names 英文名、/api/scope 帶匯率、提供 i18n.js
CI / build (push) Failing after 29s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-11 17:37:07 +00:00
walkdoggo.yehandClaude Opus 5.5 7031ac799c test: 語言、幣別換算與英文名對照
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-11 17:37:05 +00:00
walkdoggo.yehandClaude Opus 5.5 ca5a9c5bd3 feat: 英文名對照(資料區存放,不進 Git)
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-11 17:37:03 +00:00
walkdoggo.yehandClaude Opus 5.5 05a7e9b14e feat: 語言(中文/English)與幣別(TWD/USD)切換元件
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-11 17:37:02 +00:00
walkdoggo.yehandClaude Opus 5.5 c8252d695e Merge pull request 'docs: 對外接口 skill 對齊上線後的程式' (#24) from docs/skill-api-online into main
CI / build (push) Successful in 47s
Reviewed-on: walkdoggo.yeh/pm-board#24

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
2026-11-11 16:04:52 +00:00
38 changed files with 3119 additions and 612 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 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;
}
+52
View File
@@ -0,0 +1,52 @@
// 英文名對照(English 介面顯示「中文+英文」用)。
// 存在 COST_MODEL_DATA_DIR/english-names.json(不進 Git)。HR 之後補齊英文名時,
// 這份對照表只留給 HR 沒有的人(例如常態型外包)與指定的寫法(例如 Woody Yeh)。
// - byEmployee:工號 → 英文名(HR 在職人員)
// - byName:中文姓名 → 英文名(常態型外包等不在 HR 的人)
const MAX = 3000;
const clean = (value) => (typeof value === 'string' ? value.replace(/\s+/g, ' ').trim().slice(0, 80) : '');
export function normalizeEnglishNames(input = {}) {
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new TypeError('names must be an object');
const section = (value, keyOk) => {
if (value === undefined) return {};
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('names section must be an object');
const output = {};
for (const [rawKey, rawValue] of Object.entries(value).slice(0, MAX)) {
const key = clean(rawKey);
const english = clean(rawValue);
if (keyOk(key) && /[A-Za-z]/.test(english)) output[key] = english;
}
return output;
};
return {
byEmployee: section(input.byEmployee, key => /^\d{1,12}$/.test(key)),
byName: section(input.byName, key => key.length <= 20 && /[㐀-鿿]/.test(key)),
};
}
// 目前名單上的人 → { 中文姓名: 英文名 }。工號對照優先,其次姓名對照;離職的人不在名單上就不會出現。
export function englishNameMap(people, store) {
const byEmployee = store?.byEmployee || {};
const byName = store?.byName || {};
const names = {};
for (const person of people || []) {
const name = clean(person?.name);
if (!name) continue;
const english = byEmployee[String(person.employeeNumber || '').trim()] || byName[name];
if (english) names[name] = english;
}
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: '對外接口開始提供' },
+447
View File
@@ -0,0 +1,447 @@
// 語言(中文/English)與幣別(TWD/USD)切換。主看板與 /my 共用。
// - 語言:中文是原始畫面;切成 English 時,這裡把畫面上的中文換成英文(依下面的對照表),
// 姓名顯示「中文+英文」(英文名由 /api/names 提供)。
// - 幣別:金額一律用 PMI18n.cur()/amt()/sym() 顯示;USD 依核心參數的匯率(預設 30)換算。
// - 兩個設定各自存在瀏覽器(pmb-lang、pmb-currency),預設中文、TWD。
(function () {
'use strict';
function read(key) { try { return localStorage.getItem(key); } catch (e) { return null; } }
function write(key, value) { try { localStorage.setItem(key, value); } catch (e) {} }
var lang = read('pmb-lang') === 'en' ? 'en' : 'zh';
var currency = read('pmb-currency') === 'USD' ? 'USD' : 'TWD';
var rate = Number(read('pmb-usd-rate')) > 0 ? Number(read('pmb-usd-rate')) : 30;
document.documentElement.setAttribute('lang', lang === 'en' ? 'en' : 'zh-Hant');
// ---- 金額 ----
function convert(v) { var n = Number(v) || 0; return currency === 'USD' ? n / rate : n; }
function amt(v) { return Math.round(convert(v)).toLocaleString('en-US'); }
function sym() { return currency === 'USD' ? 'US$' : 'NT$'; }
function cur(v) {
if (v === null || v === undefined) return '—';
var n = Math.round(convert(v));
return (n < 0 ? '−' : '') + sym() + ' ' + Math.abs(n).toLocaleString('en-US');
}
// 大數字的簡寫:中文 TWD 用「萬」,其他用 K/M(例如 US$ 1.2M)。
function compact(v) {
var n = Math.abs(convert(v));
if (lang === 'zh' && currency === 'TWD') return Math.round(n / 10000).toLocaleString('en-US') + ' 萬';
if (n >= 1e6) return (n / 1e6).toFixed(n >= 1e8 ? 0 : 1) + 'M';
if (n >= 1e3) return Math.round(n / 1e3).toLocaleString('en-US') + 'K';
return Math.round(n).toLocaleString('en-US');
}
function setRate(value) {
var next = Number(value);
if (!(next > 0)) return false;
var changed = next !== rate;
rate = next;
write('pmb-usd-rate', String(next));
return changed && currency === 'USD';
}
// ---- 中文 → English 對照表 ----
var DICT = {
// 導覽與共用
'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',
'未登入': 'Not signed in', '登出': 'Sign out', '公司帳號登入': 'Sign in with company account',
'同時登出 MoonShine 公司帳號': 'Also signs you out of your MoonShine company account',
'正在從預覽伺服器載入合成資料…': 'Loading synthetic data from the preview server…',
'營運概況': 'Overview', '各部門 發票 vs CODA': 'Invoice vs CODA by Department', '年度發票目標': 'Annual Invoice Target',
'承擔發票': 'Bears Invoice', '其他': 'Other', '人力分佈': 'Headcount Mix', '部門倍率': 'Department Multiplier',
'人薪倍率 × 內部成本 ÷ A 成本': 'Salary Multiplier × Internal Cost ÷ A Cost',
'人員概況': 'People', '查看完整名單': 'View full list', '各部門人力預算佔比': 'Labor Budget Share by Department',
'人員主表 (全部門': 'Staff Table (All Departments', '人員主表': 'Staff Table',
'所有公司': 'All companies', '所有部門': 'All departments', '所有組別': 'All teams',
'顯示薪資': 'Show salaries', '隱藏薪資': 'Hide salaries', '新增內部人員': 'Add internal staff',
'公司': 'Company', '姓名': 'Name', '職稱': 'Title', '部門': 'Department', '組別': 'Team', '職能': 'Function',
'管理職': 'Manager', '月/時薪': 'Monthly / Hourly Pay', '每週天數': 'Days / Week',
'H1 起': 'H1 Start', 'H1 迄': 'H1 End', 'H2 起': 'H2 Start', 'H2 迄': 'H2 End',
'狀態': 'Status', '個人總成本': 'Total Cost per Person', '操作': 'Actions',
'全體 P 系列預算': 'Total P Budget', 'P 年度薪資承擔額(依管理/PC比例)': 'P Annual Salary Share (by Manager / PC ratio)',
'製作部門藝術家成本(含支援分攤)': 'Artist Cost in Production Departments (incl. shared support)',
'調整全公司營運基準、倍率、以及各項自動計算參數。變動將立即影響所有視圖。': 'Company-wide baselines, multipliers and calculation parameters. Changes apply to every view immediately.',
'P 系列預算': 'P Budget',
'藝術家預算 = 各部門最終 CODA。成本=年薪 × 人薪倍率,不除以產出率。': 'Artist budget = each department’s final CODA. Cost = annual salary × salary multiplier, not divided by output rate.',
'全公司總 CODA': 'Company Total CODA',
'選一個部門,試試加人或調薪後實際 CODA、平均日 CODA、定錨 CODA、發票會變多少。只是試算,不會存檔、不影響正式數字。部長們看到的是同一份畫面(/my)。': 'Pick a department and see how Actual CODA, Avg. Daily CODA, Anchored CODA and invoice change if you add people or raise pay. A what-if only: nothing is saved and official numbers are unaffected. Heads of Production see the same screen (/my).',
'公司 → 部門 → 組別。外包依所在部門與組別歸入該部門的公司;沒有部門的人列在各公司的「未歸部門」(不列入部門 CODA)。': 'Company → Department → Team. Contractors follow the company of their department and team; people without a department are listed under “No department” of each company (not counted in department CODA).',
'全部展開': 'Expand all', '全部收合': 'Collapse all', '公司/部門/組別': 'Company / Department / Team',
'人數': 'Headcount', '總成本': 'Total Cost', '佔上一層比例': 'Share of Parent',
'整體 A:P 成本比': 'Overall A:P Cost Ratio', '試算': 'Run', '(vs 正式)': ' (vs official)', 'vs 正式': 'vs official',
'底線發票': 'Break-even Invoice', '夢想創造 CODA(不含研發部)': 'MoonShine Creative CODA (excl. R&D)',
'全企業總成本': 'Total Company Cost', '發票/CODA 覆蓋率': 'Invoice / CODA Coverage', '未對應公司': 'Unmapped company',
'CODA 為 0(只有營運支援或外包,或已分攤至其他部門):': 'CODA is 0 (operations support or contractors only, or allocated to other departments): ',
'全企業不虧本至少要開的發票,不含利潤:全企業總成本': 'Minimum invoice for the company to break even, before profit: total company cost',
'全體正職': 'All full-time staff',
'全公司': 'Whole company', '最高': 'Highest', '差額': 'Difference', '佔比': 'Share', '上半年': 'H1', '下半年': 'H2',
'燈號依四部門 A:P 成本比相對排名:': 'Indicator ranks the four departments by A:P cost ratio: ',
'精實': 'Lean', '接近精實': 'Near lean', '臨近超標': 'Near over', '超標': 'Over', '無 P': 'No P',
'相同': 'same', '位 P': ' P staff', '成本比': 'Cost Ratio',
'定錨後': 'After anchoring', '新進': 'New hire', '離職': 'Left', '調薪/成本變動': 'Pay / cost change', '職能改變': 'Function change',
'調動': 'Transfer', '定錨(': 'Anchor (', ':定錨全年': ': Anchored annual', '定錨全年': 'Anchored annual',
'調動移轉': 'Transfer adjustment', '半年內增加(最高點)': 'Increase this half (peak)', '= 全年': '= Annual', '全年': 'Annual',
'有效比例 (全額承擔': 'Effective ratio (full share', '有效比例 (×': 'Effective ratio (×', 'PC承擔': 'PC share',
'管理職 ×': 'Manager ×', '主管承擔': 'Manager share', '個部門': ' departments', '未指定公司': 'No company', '未歸部門': 'No department',
'年度薪資成本': 'Annual Salary Cost', '成本(× 人薪倍率)': 'Cost (× Salary Multiplier)', '發票總額': 'Total Invoice', '怎麼來': 'How it is calculated',
'內部人力成本': 'Internal labor cost', '÷ 毛利率': '÷ Gross margin', '+ 常態型外包': '+ Regular contractors', '+ 專案委外': '+ Project outsourcing', '+ 員旅': '+ Company trip',
'誰來分:': 'Who shares it: ', '只有「承擔發票」的部門分這筆總額,依下面三個指標的加權比例分配。': 'Only departments that bear invoice share this total, split by the weighted mix of the three indicators below.',
'不計入的單位:': 'Excluded units: ', '不分發票,列出年度薪資成本與成本供參考。角色在「核心參數 › 發票承擔設定」調整。': 'They get no invoice; annual salary cost and cost are shown for reference. Change roles in “Core Parameters › Invoice Roles”.',
'「成本」的意思:': 'What “cost” means: ', '本站的成本=年薪 × 人薪倍率': 'Cost on this site = annual salary × salary multiplier',
';A 再除以產出率': '; A is further divided by output rate', '%。「年度薪資成本」是實際年薪。': '%. “Annual Salary Cost” is the actual annual salary.',
'燈號:': 'Indicator: ', '依四個部門的 A:P 成本比': 'by the A:P cost ratio of the four departments', '相對排名': 'relative ranking',
':最精實的是「精實」、最重的是「超標」,其餘和四部門平均比較,分成「接近精實」和「臨近超標」(橘色表示比其他臨近超標的部門更重)。燈號只是標示,不影響計算。': ': the leanest is “Lean”, the heaviest is “Over”; the rest are compared with the four-department average as “Near lean” or “Near over” (orange = heavier than other “Near over” departments). The indicator is a label only and does not affect calculations.',
'指標3 P 輕重:': 'Indicator 3, P Weight: ',
'P 成本 × (P 成本 ÷ A 成本),A 成本含常態型外包,再換算成四個部門的佔比;A:P 成本比 = A 成本 ÷ P 成本。': 'P cost × (P cost ÷ A cost), with A cost including regular contractors, then converted to a share of the four departments; A:P cost ratio = A cost ÷ P cost.',
'公司/部門/人員': 'Company / Department / Person', '指標1 P佔比': 'Ind. 1 P Share', '權重': 'Weight', '指標2 A佔比': 'Ind. 2 A Share',
'指標3 P 輕重': 'Ind. 3 P Weight', '最終比例': 'Final Share', '責任發票額': 'Invoice Target', '員旅配額': 'Company Trip Quota',
'P 人員承擔比計算說明': 'How P staff invoice share is calculated', '一般 P:有效承擔成本 = 全額薪資成本(×100%)': 'Regular P: effective cost = full salary cost (×100%)',
'P 管理職(isManager):有效承擔成本 ×': 'P manager (isManager): effective cost ×', '(釋出': ' (released ',
'PC(Production Coordinator):有效承擔成本 ×': 'PC (Production Coordinator): effective cost ×',
'各 P 的個人承擔額 = 部門發票目標 × (個人有效成本 / 部門有效P成本合計': 'Each P’s personal share = department invoice target × (personal effective cost / department total effective P cost',
'原始薪資預算總計': 'Total Raw Salary Budget', '全公司 P 總計': 'Company P Total', '全公司 A 總計': 'Company A Total', '全公司 O 總計': 'Company O Total',
'人員 | 佔比': 'Staff | Share', '專案 P': 'Project P', '內製 A': 'In-house A', '外包 O': 'Contractor O', '個部門 · 預設': ' departments · default',
'發票承擔設定': 'Invoice Roles', '承擔發票:計入總額並分配發票': 'Bears invoice: counted in the total and allocated invoice',
'成本分攤:計入總額、不分配': 'Cost sharing: counted in the total, not allocated', '不計入:只看成本 × 人薪倍率': 'Excluded: shown as cost × salary multiplier only',
'承擔發票的部門': 'Departments bearing invoice', '成本分攤': 'Cost sharing', '不計入單位成本': 'Excluded unit cost',
'新部門自動套用所屬公司的預設;部門可以個別改。': 'New departments use their company’s default; each department can be changed individually.',
// 定錨
'定錨': 'Anchor', '定錨資料讀取失敗,請重新整理。': 'Could not load anchor data. Please refresh.',
'H1(1–6 月)': 'H1 (Jan–Jun)', 'H2(7–12 月)': 'H2 (Jul–Dec)', '已定錨': 'anchored', '說明:': 'Note: ',
'尚未定錨。第一次正式定錨:': 'Not anchored yet. First official anchor: ', '年 1 月。': ' January.', '確定': 'OK', '取消': 'Cancel',
'定錨後這半年的發票與定錨 CODA 只增不減,快照不能修改,只能由下一次定錨取代。': 'After anchoring, invoice and Anchored CODA for this half can only increase. The snapshot cannot be edited; only the next anchor replaces it.',
'確認': 'Confirm', '定錨…': 'Anchoring…', '實際 CODA': 'Actual CODA', '定錨 CODA 全年': 'Anchored CODA (Annual)', '發票全年': 'Invoice (Annual)',
'定錨 CODA:各組取半年內的最高點,部門=各組加總;沒有全公司合計(調動時原單位不降、新單位增加,加總會重複)。發票:定錨全年+調動淨額+半年內自身增加的最高點。H1=全年÷2;H2=最新全年−H1 結算。': 'Anchored CODA: each team takes its peak within the half; department = sum of teams. No company total (on transfer, the old unit does not drop and the new unit increases, so a sum would double count). Invoice: anchored annual + net transfers + the department’s own peak increase within the half. H1 = annual ÷ 2; H2 = latest annual − settled H1.',
'調動(定錨後)': 'Transfers (after anchoring)', '從': 'From', '到': 'To', '生效月份': 'Effective month',
'異動清單(與定錨快照比對,': 'Changes (compared with the anchor snapshot, ', '筆)': ' items)', '類型': 'Type', '部門/組': 'Department / Team',
'全年成本增減': 'Annual Cost Change', '發票增減': 'Invoice Change', '定錨後沒有異動。': 'No changes since anchoring.', '發票:': 'Invoice: ', '定錨 CODA:': 'Anchored CODA: ', '定錨 CODA': 'Anchored CODA',
'重設最高點(資料打錯時用,只有你能按,會留紀錄)': 'Reset peak (for data entry errors; only you can do this; it is logged)', '重設': 'Reset',
'項目': 'Item', '重設前': 'Before reset', '原因': 'Reason', '時間': 'Time', '已還原': 'Restored', '還原': 'Restore',
'撤銷最近一次定錨(只有你能按,會留紀錄)': 'Undo the latest anchor (only you can do this; it is logged)',
'撤銷後回到定錨前的狀態,可以重新定錨;外部系統會看到資料版本換號。': 'Undo returns to the state before anchoring so you can anchor again; external systems will see a new data version.',
'研發組勾選': 'R&D team flags', 'CG Lead 組勾選': 'CG Lead team flags', '發票角色': 'Invoice Role',
'下一次定錨才生效的修改': 'Changes that take effect at the next anchor', '與目前相同': 'Same as current', '撤銷紀錄:': 'Undo log: ', ',原因:': ', reason: ',
'定錨(發票+定錨 CODA)': 'Anchor (Invoice + Anchored CODA)', '沒有完成:': 'Not completed: ', '定錨沒有完成:': 'Anchoring was not completed: ',
// 核心參數
'基本參數': 'Basic Parameters',
'調整人薪倍率、年度工作天數與產出率,這些值會直接影響各部門 CODA 的計算基準。': 'Salary multiplier, annual working days and output rates. These directly drive each department’s CODA.',
'人薪倍率(正職)': 'Salary Multiplier (full-time)', '外包倍率': 'Contractor Multiplier', '年度工作天數': 'Annual Working Days', '月平均工作天數': 'Avg. Working Days per Month',
'P 產出率': 'P Output Rate', 'A 產出率': 'A Output Rate', '美金匯率(1 USD = 幾 TWD)': 'Exchange Rate (TWD per 1 USD)',
'發票分配與目標': 'Invoice Allocation & Targets', '設定各項指標權重與年度專案成本,系統將依此自動演算出各部門應達成的發票目標。': 'Indicator weights and annual project costs. The system derives each department’s invoice target from them.',
'指標1:P 成本': 'Indicator 1: P Cost', '指標2:A 成本': 'Indicator 2: A Cost', '指標3:P 輕重(A:P 成本比)': 'Indicator 3: P Weight (A:P cost ratio)',
'發票總額參數': 'Total Invoice Parameters', '專案委外': 'Project Outsourcing', '員旅(不除毛利率)': 'Company Trip (not divided by gross margin)', '毛利率': 'Gross Margin',
'研發參數與標註': 'R&D Parameters & Flags', '設定研發減免比例。': 'Set the R&D deduction rate.', '研發減免': 'R&D Deduction',
'管理職與 PC 承擔比例': 'Manager & PC Share Ratios', '定義管理職與 PC 職位的成本承擔比例,未承擔的成本將由組員共同分攤。': 'Share ratios for managers and PCs; the unshared cost is spread across the team.',
'未分組': 'No team', '指定部門': 'Assigned department', '手動分組': 'Manual team', '修改手動': 'Edit manual', '清除手動': 'Clear manual',
'修改後自動儲存;清空欄位或按「清除手動」可還原。HR 之後提供資料時以 HR 為準。': 'Saved automatically. Clear the field or press “Clear manual” to revert. HR data takes priority once HR provides it.',
'手動': 'Manual', '依 HR 組織資料自動產生:公司 → 部門 → 組別。RD/CG 勾選會自動儲存;未歸部門的人員不列入部門 CODA。': 'Built from HR organization data: Company → Department → Team. R&D / CG flags save automatically; people without a department are not counted in department CODA.',
'無結果': 'No results', '重新計算中...': 'Recalculating...', '外包(未對應公司)': 'Contractors (unmapped company)', '佔全部': 'of total',
'沒有資料。': 'No data.', '未分組 (需由管理清單指派': 'No team (assign from the management list', '佔總 P 預算': 'of total P budget', '月薪': 'Monthly Pay',
'管理率': 'Management Ratio', '年度預算估計': 'Annual Budget Estimate', '主管': 'Manager', '研發釋出 -': 'R&D release -', '分攤研製預算': 'Shared R&D budget',
'原始加總:': 'Raw total: ', '未分攤': 'Not shared', '月/日薪': 'Monthly / Daily Pay', '工作率': 'Work Rate', '年度總成本': 'Annual Total Cost',
'請輸入有效數值;工作天數、產出率與毛利率必須大於零。': 'Please enter a valid number. Working days, output rates, gross margin and exchange rate must be greater than zero.',
'在職 (12m': 'Active (12m', '未安排 (0m': 'Not scheduled (0m', '非滿年度': 'Partial year',
'沒有符合條件的人員,可調整篩選或新增。': 'No matching people. Adjust the filters or add someone.',
'實習生:薪資 × 1 只算進發票,不算 CODA,計入 A/P 人數': 'Intern: salary × 1 counts toward invoice only, not CODA; included in A/P headcount',
'待分類': 'Unclassified', '篩選總額': 'Filtered Total', '待設定 P/A 職能': 'P / A function not set', 'HR 尚未提供可用薪資': 'HR has not provided a usable salary',
'不計入': 'Excluded', '已儲存': 'Saved', '儲存失敗': 'Save failed',
'HR 試算資料更新失敗,請重新整理後再試。': 'Could not update HR planning data. Please refresh and try again.',
'部門/組別儲存失敗,請重新整理後再試。': 'Could not save department / team. Please refresh and try again.',
'清除手動部門/組別失敗,請重新整理後再試。': 'Could not clear the manual department / team. Please refresh and try again.',
'HR 未提供,可手動補': 'Not provided by HR; can be filled in manually', 'O - 外包': 'O - Contractor', 'A - 藝術家': 'A - Artist',
'新增常態型外包': 'Add regular contractor', '— 未分組': '— No team', '日薪': 'Daily Pay', '時薪': 'Hourly Pay', '/ 日': '/ day', '/ 月': '/ month',
'已刪除': 'Deleted', '已復原': 'Restored', 'HR 組織資料:不是任何單位的主管': 'HR organization data: not a manager of any unit', 'HR 組織資料:': 'HR organization data: ',
'顯示每個人的薪資與成本': 'Show each person’s salary and cost', '隱藏每個人的薪資與成本': 'Hide each person’s salary and cost', '復原': 'Undo',
'常態型外包不在 HR 系統內,在此獨立維護日薪、合約月份與部門/組別;新增、修改、刪除會自動儲存在本站。': 'Regular contractors are not in the HR system. Their daily pay, contract months and department / team are kept here; additions, edits and deletions save automatically.',
'HR 試算名單。姓名、職稱、部門/組別與薪資來自 HR;P/A、管理職及未辨識部/組可在此補齊。未完成 P/A 的人會列出,但不納入正式總額。': 'HR planning roster. Name, title, department / team and salary come from HR; P / A, manager flags and unrecognized departments / teams can be completed here. People without P / A are listed but excluded from official totals.',
'新增人員': 'Add person', '未指定': 'Not set', '其他 (未定義': 'Other (undefined', '已分攤至': 'Allocated to', '含分攤': 'incl. allocation',
'P 預算': 'P Budget', 'A 預算': 'A Budget', '倍率': 'Multiplier', '佔部門總成本': 'of department total cost', '平均日工作 CODA': 'Avg. Daily CODA',
'不含O': 'excl. O', '總月份': 'Total Months', '應負責 CODA': 'Responsible CODA', '日工作 CODA': 'Daily CODA', '[不負責業績]': '[No revenue responsibility]',
'主管承擔 −': 'Manager share −', '您目前以': 'You are signed in as', '身份登入,以下僅顯示您所屬部門': '; only your department',
'的成本組成與細節,全公司總 CODA 仍維持整體規模呈現。': ' cost breakdown and details are shown below. Company total CODA still shows the full scale.',
'佔全公司': 'of company', '平均倍率': 'Avg. Multiplier', 'CODA 組成 (純內製 P+A': 'CODA Composition (in-house P+A only', '部門平均日工作 CODA': 'Department Avg. Daily CODA',
'組別倍率=人薪倍率 × 組別最終 CODA ÷ 組內 A 成本': 'Team multiplier = salary multiplier × team final CODA ÷ team A cost',
'部門平均倍率=人薪倍率 × 部門 CODA ÷ 部門 A 成本(即各組倍率依 A 成本加權的平均)': 'Department avg. multiplier = salary multiplier × department CODA ÷ department A cost (A-cost-weighted average of team multipliers)',
'常態型外包儲存失敗,請重新整理後再試;剛才的外包修改尚未保存。': 'Could not save contractors. Please refresh and try again; your recent contractor changes were not saved.',
'已定錨:剛才的參數修改會在下一次定錨才生效,這半年的數字照舊。': 'Anchored: your parameter changes take effect at the next anchor; numbers for this half stay as they are.',
'RD/CG 勾選或核心參數儲存失敗,請重新整理後再試;剛才的修改尚未保存。': 'Could not save R&D / CG flags or core parameters. Please refresh and try again; your changes were not saved.',
// 登入狀態
'本機預覽': 'Local preview', '本機預覽,尚未啟用登入或權限控管': 'Local preview; sign-in and permissions are not enabled', '確認登入狀態中': 'Checking sign-in', '無法確認登入狀態': 'Cannot confirm sign-in',
'本機未啟用公司登入': '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.',
'目前登入的公司帳號不在 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.',
'HR Sync 暫時無法回應,請稍後重新整理。': 'HR Sync is not responding. Please refresh later.', 'HR Sync 服務目前尚未可用。': 'The HR Sync service is not available yet.',
'HR 試算資料讀取失敗(HTTP': 'Could not load HR planning data (HTTP', '伺服器回傳格式不符。': 'The server response format is not valid.',
'HR 試算|已轉入': 'HR planning | Imported', '位 HR 在職人員;': ' active HR employees; ',
'位待確認 P/A 或薪資,暫不納入正式總額。時薪先按每週 5 天、每天 8 小時計算;H1 預設為 1–6 月。常態型外包': ' need P / A or salary confirmation and are excluded from official totals for now. Hourly pay assumes 5 days a week, 8 hours a day; H1 defaults to Jan–Jun. Regular contractors: ',
'位,在本站手動維護並儲存。': ', maintained and saved on this site.',
'合成資料預覽|姓名、薪資與參數皆為虛構資料;修改只保留在目前頁面工作階段。': 'Synthetic data preview | Names, salaries and parameters are fictional; edits last only for this page session.',
'無法載入預覽資料:': 'Could not load preview data: ',
// 新增人員視窗
'職能角色': 'Function', 'P - 製作人': 'P - Producer', 'P - 執行製作': 'P - Line Producer', 'A - 特效師': 'A - FX Artist', 'A - 動畫師': 'A - Animator',
'A - 剪輯': 'A - Editor', 'A - 燈光': 'A - Lighting', '屬性': 'Type', 'H1 上半年合約期間': 'H1 Contract Period', '— 無': '— None',
'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 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)',
'G 管理': 'G Manager', '外包': 'Contractor', '實習': 'Intern', '工讀': 'Part-time',
'本試算只用來快速估算加人、調薪後大約的 CODA 與發票量,結果只代表試算當下的狀態。實際數字會隨人員與參數變動,正式數字一律以每年 1 月、7 月定錨後統一公布的為準。': 'This simulation is only a quick estimate of CODA and invoice after adding people or raising pay, as of the moment it runs. Actual numbers change with staffing and parameters; official numbers are always those published after the January and July anchors.',
'尚未定錨': 'Not anchored yet', '在職月份': 'Months Employed', '薪資': 'Salary', '年度成本': 'Annual Cost',
'這個部門不分配發票': 'This department is not allocated invoice', '定錨:上半年': 'Anchor: H1', '/下半年': ' / H2', '(定錨前預估)': ' (estimate before anchoring)',
'指標 1 P 佔比': 'Indicator 1 P Share', '你部門 P 的成本,佔四個出發票部門 P 成本總和的比例。': 'Your department’s P cost as a share of total P cost in the four invoicing departments.',
'指標 2 A 佔比': 'Indicator 2 A Share', '你部門 A 的成本,佔四個出發票部門 A 成本總和的比例。': 'Your department’s A cost as a share of total A cost in the four invoicing departments.',
'指標 3 P 輕重': 'Indicator 3 P Weight', 'P 成本 ×(P 成本 ÷ A 成本,A 含常態型外包),再換算成佔比。P 相對 A 越重,分得越多。': 'P cost × (P cost ÷ A cost, A including regular contractors), converted to a share. The heavier P is relative to A, the larger the share.',
'發票佔比 = 三個指標各自乘上權重後加總。下面是你部門的三個指標:': 'Invoice share = sum of the three indicators, each times its weight. Your department’s three indicators:',
'指標': 'Indicator', '你部門': 'Your department', '貢獻': 'Contribution', '發票佔比': 'Invoice Share',
'A:P 成本比(A 含外包 ÷ P):你部門': 'A:P cost ratio (A incl. contractors ÷ P): your department', ',四個部門整體': ', four departments overall',
'。數字越大,代表每 1 元 P 成本對應的 A 越多。': '. A higher number means more A per dollar of P cost.', '目前沒有資料': 'No data yet',
'實際 CODA(部門)': 'Actual CODA (Department)', '平均日 CODA(部門)': 'Avg. Daily CODA (Department)', '定錨 CODA(部門)': 'Anchored CODA (Department)',
'定錨後發票': 'Invoice after Anchoring', '尚未定錨,定錨後才有': 'Available after the first anchor', '不變': 'No change', '▲ 增加': '▲ Up', '▼ 減少': '▼ Down',
'個百分點': ' percentage points', '加 1 人:': 'Add 1 person: ', '調薪:': 'Raise: ', '沒有調整任何東西(目前的數字)。': 'Nothing adjusted (current numbers).',
'各組的實際 CODA 都沒有變。': 'Actual CODA did not change for any team.', '人(不算 CODA)': ' people (not counted in CODA)', '調薪': 'Raise',
'實際 CODA 的變化,變最多的排最上面。': 'Change in Actual CODA, largest first.', '發票是全公司一起分的:你部門': 'Invoice is shared across the company: your department', '變多,其他部門會相對變少。': ' goes up, so other departments go down.', '變少,其他部門會相對變多。': ' goes down, so other departments go up.', '金額': 'Amount', '清除': 'Clear', '加 1 人': 'Add 1 person',
'① 你這次試算了什麼': '① What you changed', '② 結果:現在 → 試算後': '② Result: now → after', '③ 影響在哪一組': '③ Which teams are affected',
'移除': 'Remove', '模擬調薪(': 'Simulated raises (', '人可調)': ' people adjustable)', '可調)': ' adjustable)', '預算': 'Budget', '模擬後': 'After', '已調整': 'Adjusted',
'模擬試算(不會存檔)': 'Simulation (not saved)',
'在本部門加人或調薪,看看實際 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.',
'你目前沒有 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',
// 補充(畫面檢查時找到的)
'主選單': 'Main menu', '搜尋姓名、職稱...': 'Search name, title...', '搜尋': 'Search', '請輸入姓名': 'Enter a name', '請輸入': 'Enter', '例:': 'e.g. ', '資深特效師': 'Senior FX Artist',
'切換年份(查看已封存的年度)': 'Switch year (view archived years)', '說明': 'info', '只供參考,不影響任何計算。': 'For reference only; does not affect any calculation.',
'只供參考': 'For reference only', '不影響任何計算': 'does not affect any calculation', '查看分配明細': 'view allocation details', '明細': 'details',
'與「部門 CODA」頁相同:P + A 成本,不含營運支援與外包': 'Same as the “Department CODA” page: P + A cost, excluding operations support and contractors',
'人薪倍率': 'Salary Multiplier', '成本': 'cost', '不含': 'excl.', '含': 'incl.', '多': 'over by', '差': 'short by', '全公司(含未歸部門人員)': 'Whole company (incl. people with no department)',
'研發組減免比例': 'R&D Team Deduction Rate', '管理職 P 承擔比例': 'Manager P Share Ratio', 'PC 承擔比例': 'PC Share Ratio', '管理職 A 承擔比例': 'Manager A Share Ratio', 'CG Lead 承擔比例': 'CG Lead Share Ratio',
'承擔比例': 'Share Ratio', '承擔': 'share', '比例': 'ratio', '公司預設': 'Company default', '預設': 'Default', '全部跟隨': 'All follow company', '跟隨公司': 'Follow company', '改回跟隨': 'Revert to company default',
'含外包': 'incl. contractors', '(不列入部門 CODA)': ' (not counted in department CODA)', '不列入': 'not counted in', '專案管理': 'Project Management', '員工': 'Employee ',
'輸入部門': 'Enter department', '輸入組別': 'Enter team', '輸入': 'Enter', '(部)': ' (Dept.)', '(組)': ' (Team)', '(公司)': ' (Company)', '(集團)': ' (Group)', '(集團,次要)': ' (Group, secondary)',
'(公司,次要)': ' (Company, secondary)', '(組,次要)': ' (Team, secondary)', '(部,次要)': ' (Dept., secondary)', '次要': 'secondary', '集團': 'Group',
'管理職(由 HR 提供,不可修改)': 'Manager (from HR, read-only)', '由 HR 提供,目前不可在試算頁覆寫': 'Provided by HR; cannot be overridden on the planning page', '薪資已隱藏': 'Salary hidden', 'HR 同步': 'HR sync',
'G 營運支援:計成本 × 人薪倍率': 'G Operations Support: cost × salary multiplier', 'AI影像企劃': 'AI Visual Planner', '實習AI概念美術': 'AI Concept Art Intern', '實習工程師': 'Engineering Intern',
'內部人員': 'Internal staff', '導演': 'Director', '特約藝術家': 'Freelance Artist', '須另行負擔之外包成本:': 'Additional contractor cost:', '須另行負擔之外包成本': 'Additional contractor cost',
'含主管及 CG Lead 承擔分攤': 'incl. manager and CG Lead share allocation', '組內 P+A': 'Team P+A', 'O外包': 'O Contractors', '年度總成本(組內佔比)': 'Annual Total Cost (share within team)', '組內佔比': 'share within team',
'分攤研製及管理 CODA': 'Allocated R&D and Management CODA', '分攤來源:': 'Allocated from: ', '依各部門自身 CODA 比例': 'in proportion to each department’s own CODA',
'本部門 P+A 合計': 'This department P + A total', '依比例分攤': 'allocated proportionally', '合計': 'Total', '公司合計': 'Company total',
'底線發票說明': 'Break-even invoice info', '全企業總成本說明': 'Total company cost info', '指標3 說明': 'Indicator 3 info',
'全企業不虧本至少要開的發票,不含利潤:全企業總成本': 'Minimum invoice for the company to break even, before profit: total company cost',
'年度發票目標,查看分配明細': 'Annual invoice target; view allocation details',
'指標3=P 成本 × (P 成本 ÷ A 成本),A 成本含常態型外包,再換算成佔比:P 相對 A 越重,分得越多。下方「P 比平均多/少」是和四部門整體成本比(': 'Indicator 3 = P cost × (P cost ÷ A cost), with A cost including regular contractors, converted to a share: the heavier P is relative to A, the larger the share. “P above / below average” below compares with the four departments’ overall cost ratio (',
')相比。': ').', 'A:P 成本比': 'A:P cost ratio', '(承擔部門平均': ' (average of invoice-bearing departments', '。A 成本含常態型外包。': '. A cost includes regular contractors.',
'P 比平均多': 'P above average by', 'P 比平均少': 'P below average by', '與平均相同': 'same as average',
'不計入發票的單位(成本 × 人薪倍率)': 'Units outside the invoice (cost × salary multiplier)', '人員資料(全部門)': 'Staff (All Departments)', '常態型外包(全部門)': 'Regular Contractors (All Departments)',
'刪除': 'Delete', 'RD 研發組:成本扣除研發比例': 'R&D team: cost minus R&D deduction', '選擇部門': 'Select department', '定錨 CODA(部門=各組加總)': 'Anchored CODA (department = sum of teams)',
'發票與倍率': 'Invoice & Multiplier', '部門內部成本(P+A+G,不含外包)÷ A 成本 × 人薪倍率': 'Department internal cost (P + A + G, excl. contractors) ÷ A cost × salary multiplier',
'發票佔比怎麼來的': 'How the invoice share is calculated', '人力': 'Headcount', '部門總人力成本(年)': 'Department Total Labor Cost (annual)', '總人力成本(年)': 'Total Labor Cost (annual)',
'正職年薪 × 人薪倍率 + 外包 × 外包倍率,不含實習生': 'Full-time annual salary × salary multiplier + contractors × contractor multiplier, excl. interns',
'各組': 'Teams', '平均日 CODA': 'Avg. Daily CODA', '人數是算 CODA 的人(A 與外包);總人力成本含組內所有人(含 P、外包,不含實習生)。': 'Headcount counts people in CODA (A and contractors); total labor cost covers everyone in the team (incl. P and contractors, excl. interns).',
'顯示目前薪資': 'Show current salaries', '隱藏目前薪資': 'Hide current salaries', '最高管理者': 'Top administrator', '管理者': 'Administrator',
'全公司沒有定錨 CODA 合計(調動時原單位不降、新單位增加,加總會重複)。': 'There is no company total for Anchored CODA (on transfer the old unit does not drop and the new unit increases, so a sum would double count).',
'個人明細(': 'Individual details (', '個人明細': 'Individual details', '人)': ' people)', '人,': ' people, ', '發票': 'Invoice', '年薪': 'Annual Salary', '倍數': 'Multiple',
'正職': 'Full-time', '比較': 'Comparison', '平均': 'Average', '人員': 'Staff', '總額': 'Total',
// 公司、部門、組別(依架構圖)
'夢想動畫股份有限公司': 'MoonShine Animation Co., Ltd.', '夢想創造股份有限公司': 'MoonShine Creative Co., Ltd.', '夢境現實股份有限公司': 'MoonDream Reality Co., Ltd.',
'虛擬實景股份有限公司': 'MoonShine XR Studio Co., Ltd.', '登月智慧股份有限公司': 'Moonland AI Co., Ltd.',
'夢想集團': 'MoonShine Group', '夢想動畫': 'MoonShine Animation', '夢想創造': 'MoonShine Creative', '夢境現實': 'MoonDream Reality', '虛擬實景': 'MoonShine XR Studio', '登月智慧': 'Moonland AI', '虛實入口': 'Phygitalport',
'前製部': 'Pre-Production', '動畫部': 'Animation', '視效部': 'VFX', '廣告部': 'Commercial', '研發部': 'R&D', '營運部': 'Operations', '業務部': 'Business',
'互動技術部': 'Interactive Technology', '互動美術部': 'Interactive Art', '專案與場館營運部': 'Projects & Venue Operations',
'導演組': 'Directing', '設計概念組': 'Concept Design', '畢製續約': 'Graduate Renewal', '動畫組': 'Animation', '前製組': 'Pre-Production', '後製組': 'Post-Production',
'技術組': 'Technical', '專案組': 'Production', '動畫部管理組': 'Animation Management', '3D組': '3D', '3D 組': '3D', '特效組': 'FX', '合成組': 'Compositing',
'視效部管理組': 'VFX Management', 'A組': 'Team A', 'B組': 'Team B', 'C組': 'Team C', 'D組': 'Team D', 'AD組': 'Art Direction', 'AD 組': 'Art Direction',
'開發1組': 'Development 1', '開發2組': 'Development 2', '平台組': 'Platform', '研發部製程組': 'Pipeline', 'AI內容製作組': 'AI Content Production', '管理組': 'Management',
'資訊組': 'IT', '行政管理組': 'Administration', '企劃行銷組': 'Marketing & Planning', '美術組': 'Art', '場館營運組': 'Venue Operations',
'研發組': 'R&D team', '營運支援': 'Operations Support', '執行長': 'CEO', '部長': 'Head of Production', '督導': 'Supervisor', '組長': 'Lead'
};
var PUNCT = { ',': ', ', '。': '. ', ':': ': ', ';': '; ', '(': ' (', ')': ') ', '「': '“', '」': '”', '、': ', ', ' ': ' ',
'=': ' = ', '+': ' + ', '/': ' / ', '!': '! ', '?': '? ', '~': '~', '《': '“', '》': '”' };
var CJK = /[㐀-鿿]/;
var names = {}; // 中文姓名 → 英文名
var table = null, matcher = null;
var missing = new Map(); // 沒翻到的中文 → 原句(檢查用)
function escapeRe(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
function build() {
table = Object.assign({}, DICT);
Object.keys(names).forEach(function (zh) { table[zh] = zh + ' ' + names[zh]; });
var keys = Object.keys(table).filter(function (k) { return k && CJK.test(k); }).sort(function (a, b) { return b.length - a.length; });
matcher = new RegExp(keys.map(escapeRe).join('|'), 'g');
}
var WORD_END = /[A-Za-z0-9)%\]$]$/, WORD_START = /^[A-Za-z0-9(\[$#]/;
function join(parts) {
var out = '';
parts.forEach(function (p) {
if (!p) return;
if (out && WORD_END.test(out) && WORD_START.test(p)) out += ' ';
out += p;
});
return out;
}
// 跟數字連在一起的單字(人、位、年、月、日、時、倍、天):只在數字旁邊才換,避免拆壞其他詞。
// 只在整段文字就是這個字時才換(單位、頭像縮寫)。
var EXACT = { '倍': '×', '天': 'days', '率': '%', '組': 'Team', '預': 'P', '日': 'day', '時': 'hr', '人': 'people', '年': '', '位': '', '月': '', '元': 'NT$' };
var MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function mon(n) { var i = Number(n); return i >= 1 && i <= 12 ? MONTHS[i - 1] : n; }
function numberRules(s) {
return s
.replace(/(\d+)–(\d+)、(\d+)–(\d+)\s*月/g, function (m, a, b, c, d) { return mon(a) + '–' + mon(b) + ', ' + mon(c) + '–' + mon(d); })
.replace(/(\d+)–(\d+)\s*月/g, function (m, a, b) { return mon(a) + '–' + mon(b); })
.replace(/(^|\s)日 (?=(?:NT|US)\$)/g, '$1Daily ').replace(/(^|\s)時 (?=(?:NT|US)\$)/g, '$1Hourly ')
.replace(/佔(?=[\u3400-\u9fffA-Za-z])/g, 'of ')
.replace(/(\d+)\s*月(?![份薪平])/g, function (m, n) { var i = Number(n); return i >= 1 && i <= 12 ? MONTHS[i - 1] : m; })
.replace(/(\d[\d,]*)\s*(?:位|名)?\s*人(?![員力數])/g, '$1 people')
.replace(/(\d[\d,]*)\s*位/g, '$1')
.replace(/(\d{4})\s*年(?!度)/g, '$1')
.replace(/(\d[\d,.]*)\s*倍/g, '$1×')
.replace(/(\d[\d,.]*)\s*天/g, '$1 days')
.replace(/(\d[\d,.]*)\s*筆/g, '$1 items');
}
function translate(text, spacing) {
if (lang !== 'en' || !text || !CJK.test(text)) return text;
if (!matcher) build();
var lead = text.match(/^\s*/)[0], tail = text.match(/\s*$/)[0];
var body = text.trim();
if (EXACT[body] !== undefined) return lead + EXACT[body] + tail;
body = body.replace(/(\d{4}) 試算/g, '$1 Planning');
var parts = [], last = 0, m;
matcher.lastIndex = 0;
while ((m = matcher.exec(body))) {
parts.push(body.slice(last, m.index));
parts.push(table[m[0]]);
last = m.index + m[0].length;
}
parts.push(body.slice(last));
var out = numberRules(join(parts)).replace(/[,。:;()「」、 =+/!?~《》]/g, function (c) { return PUNCT[c]; });
out = out.replace(/ {2,}/g, ' ').replace(/ ([,.;:)%])/g, '$1').replace(/\( /g, '(').replace(/^ +/, '');
// 中文原本不用空格;和旁邊的文字(另一個節點)相連時補一個空格,避免黏在一起。
if (spacing) {
if (spacing.after && /[\u3400-\u9fff]$/.test(body) && /[A-Za-z0-9)]$/.test(out) && !tail) out += ' ';
if (spacing.before && /^[\u3400-\u9fff]/.test(body) && /^[A-Za-z0-9(]/.test(out) && !lead) out = ' ' + out;
}
var check = out;
Object.keys(names).forEach(function (zh) { check = check.split(zh).join(''); });
var left = check.match(/[㐀-鿿][㐀-鿿\s]*/g);
if (left && !missing.has(body)) missing.set(body, left.map(function (s) { return s.trim(); }).join(' | '));
return lead + out + tail;
}
// ---- 畫面翻譯(只在 English 時啟動) ----
var ATTRS = ['title', 'placeholder', 'aria-label', 'data-tip', 'alt'];
var SKIP = { SCRIPT: 1, STYLE: 1, TEXTAREA: 1, CODE: 1 };
// 每個節點記住原文與譯文:畫面程式改了內容才重翻;英文名載入後從原文重翻,不會翻兩次。
var seen = new WeakMap();
function doText(node, again) {
var value = node.nodeValue;
var rec = seen.get(node);
var source = rec && (value === rec.out) ? rec.orig : value;
if (rec && value === rec.out && !again) return;
var next = translate(source, { before: !!node.previousSibling, after: !!node.nextSibling });
seen.set(node, { orig: source, out: next });
if (next !== value) node.nodeValue = next;
}
function doAttrs(el, again) {
var rec = seen.get(el) || {};
ATTRS.forEach(function (a) {
if (!el.hasAttribute(a)) return;
var v = el.getAttribute(a);
var r = rec[a];
var source = r && v === r.out ? r.orig : v;
if (r && v === r.out && !again) return;
if (!CJK.test(source)) return;
var n = translate(source);
rec[a] = { orig: source, out: n };
if (n !== v) el.setAttribute(a, n);
});
seen.set(el, rec);
}
function skipped(node) {
for (var el = node.nodeType === 1 ? node : node.parentElement; el; el = el.parentElement) {
if (SKIP[el.tagName] || el.hasAttribute('data-i18n-skip')) return true;
}
return false;
}
function walk(root, again) {
if (!root || skipped(root)) return;
if (root.nodeType === 3) { doText(root, again); return; }
if (root.nodeType !== 1) return;
doAttrs(root, again);
var walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {
acceptNode: function (n) { return n.nodeType === 1 && (SKIP[n.tagName] || n.hasAttribute('data-i18n-skip')) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT; }
});
var n;
while ((n = walker.nextNode())) { if (n.nodeType === 3) doText(n, again); else doAttrs(n, again); }
}
function startDom() {
if (lang !== 'en' || !document.body) return;
document.title = translate(document.title);
walk(document.body);
new MutationObserver(function (records) {
records.forEach(function (r) {
if (r.type === 'characterData') { if (!skipped(r.target)) doText(r.target); }
else if (r.type === 'attributes') { if (!skipped(r.target)) doAttrs(r.target); }
else r.addedNodes.forEach(function (n) { walk(n); });
});
}).observe(document.body, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ATTRS });
['alert', 'confirm', 'prompt'].forEach(function (k) {
var original = window[k];
window[k] = function (message) { var args = Array.prototype.slice.call(arguments); args[0] = translate(String(message == null ? '' : message)); return original.apply(window, args); };
});
}
// ---- 英文名 ----
function loadNames() {
if (lang !== 'en') return Promise.resolve();
return fetch('/api/names', { cache: 'no-store' }).then(function (r) { return r.ok ? r.json() : null; }).then(function (data) {
if (!data || !data.names) return;
names = data.names; build();
if (document.body) walk(document.body, true);
}).catch(function () {});
}
// ---- 切換按鈕:放在有 data-pmb-switches 的位置 ----
function renderSwitches() {
document.querySelectorAll('[data-pmb-switches]').forEach(function (host) {
var cls = host.getAttribute('data-pmb-switches') || 'theme-toggle';
host.setAttribute('data-i18n-skip', '');
host.innerHTML =
'<div class="' + cls + '" role="group" aria-label="Language / 語言">' +
'<button type="button" data-pmb-lang="zh" aria-pressed="' + (lang === 'zh') + '">中文</button>' +
'<button type="button" data-pmb-lang="en" aria-pressed="' + (lang === 'en') + '">EN</button></div>' +
'<div class="' + cls + '" role="group" aria-label="Currency / 幣別">' +
'<button type="button" data-pmb-cur="TWD" aria-pressed="' + (currency === 'TWD') + '">NT$</button>' +
'<button type="button" data-pmb-cur="USD" aria-pressed="' + (currency === 'USD') + '">US$</button></div>';
host.querySelectorAll('[data-pmb-lang]').forEach(function (b) { b.addEventListener('click', function () { if (b.dataset.pmbLang !== lang) { write('pmb-lang', b.dataset.pmbLang); location.reload(); } }); });
host.querySelectorAll('[data-pmb-cur]').forEach(function (b) { b.addEventListener('click', function () { if (b.dataset.pmbCur !== currency) { write('pmb-currency', b.dataset.pmbCur); location.reload(); } }); });
});
}
function init() { renderSwitches(); startDom(); loadNames(); }
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init); else init();
window.PMI18n = {
lang: function () { return lang; }, currency: function () { return currency; }, rate: function () { return rate; },
setRate: setRate, amt: amt, sym: sym, cur: cur, compact: compact, t: function (s) { return translate(s); },
missing: function () { return Array.from(missing.entries()); }
};
})();
+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));
+675 -90
View File
File diff suppressed because it is too large Load Diff
+4 -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);沒選過就跟著系統。
@@ -14,6 +14,7 @@
document.documentElement.setAttribute('data-theme', theme);
})();
</script>
<script src="/i18n.js"></script>
<style>
:root { color-scheme: light; --bg:#f6f4ef; --card:#ffffff; --text:#1f2328; --muted:#5f6670; --line:#e4e0d8; --accent:#4f6bed; --warn:#b4540a; --good:#2f7d4f; }
:root[data-theme="dark"] { color-scheme: dark; --bg:#16181c; --card:#1f2228; --text:#eceef1; --muted:#a3a9b3; --line:#30343c; --accent:#8fa2ff; --warn:#f0a35a; --good:#6fcf97; }
@@ -39,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>
@@ -53,6 +55,7 @@ button:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }
<button type="button" data-theme-set="light">日間</button>
<button type="button" data-theme-set="dark">夜間</button>
</div>
<div data-pmb-switches="theme" style="display:contents;"></div>
<form class="logout" method="post" action="/api/auth/company-logout">
<button type="submit" title="同時登出 MoonShine 公司帳號">登出</button>
</form>
-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;
},
};
}
+22 -8
View File
@@ -2,8 +2,10 @@
// 數字都由伺服器算(/api/scope、/api/simulate),這裡只負責顯示。
// 顏色用 --sx-* 變數,放進主看板時由主看板換成自己的配色。
(function () {
const money = v => v === null || v === undefined ? '—' : 'NT$ ' + Math.round(v).toLocaleString();
// 金額依右上角的幣別顯示(i18n.js);沒有載入 i18n.js 時照舊用 NT$。
const money = v => v === null || v === undefined ? '—' : (window.PMI18n ? PMI18n.cur(v) : 'NT$ ' + Math.round(v).toLocaleString());
const num = v => Math.round(v).toLocaleString();
const amtv = v => (window.PMI18n ? PMI18n.amt(v) : num(v));
const pct = (v, digits = 1) => v === null || v === undefined ? '—' : `${(v * 100).toFixed(digits)}%`;
const times = v => v === null || v === undefined ? '—' : `${Number(v).toFixed(2)}x`;
const ratio = v => v === null || v === undefined ? '無 P' : `${Number(v).toFixed(1)} : 1`;
@@ -159,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>` :
@@ -175,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), '正職年薪 × 人薪倍率 + 外包 × 外包倍率,不含實習生') : ''}
@@ -185,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>`;
}
@@ -209,7 +220,7 @@
const word = delta > 0 ? '▲ 增加' : '▼ 減少';
const amount = r.key === 'multiplier' ? Math.abs(delta).toFixed(2)
: r.key === 'invoiceShare' ? `${Math.abs(delta * 100).toFixed(2)} 個百分點`
: num(Math.abs(delta));
: amtv(Math.abs(delta));
const rel = r.key !== 'invoiceShare' && r.before ? `(${delta > 0 ? '+' : '−'}${Math.abs(delta / r.before * 100).toFixed(1)}%)` : '';
say = `<div class="say ${cls}">${word} ${amount}${rel}</div>`;
}
@@ -220,14 +231,14 @@
const people = new Map((d.people || []).map(p => [p.employeeNumber, p]));
const items = [];
ran.additions.forEach(a => {
const pay = a.amount === '' ? '—' : num(Number(a.amount) || 0);
const pay = a.amount === '' ? '—' : 'NT$ ' + num(Number(a.amount) || 0);
items.push(`加 1 人:${esc(KIND_LABEL[a.kind] || a.kind)}・${esc(a.group || '未分組')}・${PAY_LABEL[a.salaryType] || ''} ${pay}・${monthsText(a)} 月`);
});
Object.entries(ran.raises).forEach(([id, amount]) => {
const p = people.get(id);
const current = p ? p.salary : null;
const diff = current !== null && current !== undefined ? `<span class="sx-val">(${amount - current >= 0 ? '+' : '−'}${num(Math.abs(amount - current))})</span>` : '';
items.push(`調薪:${esc(p?.name || id)}${p?.group ? `(${esc(p.group)})` : ''} → ${p?.salaryType === 'hourly' ? '時薪 ' : ''}${num(amount)}${diff}`);
items.push(`調薪:${esc(p?.name || id)}${p?.group ? `(${esc(p.group)})` : ''} → ${p?.salaryType === 'hourly' ? '時薪 ' : ''}NT$ ${num(amount)}${diff}`);
});
return items.length ? `<ul class="sx-did">${items.map(i => `<li>${i}</li>`).join('')}</ul>` : '<div class="sx-sub">沒有調整任何東西(目前的數字)。</div>';
}
@@ -251,7 +262,7 @@
const tags = [g.people ? `${g.people > 0 ? '+' : '−'}${Math.abs(g.people)} 人` : (added[g.group] ? `+${added[g.group]} 人(不算 CODA)` : ''), raisedIn[g.group] ? `調薪 ${raisedIn[g.group]} 人` : ''].filter(Boolean);
return `<div>${esc(g.group)}${tags.map(t => `<span class="sx-tag">${t}</span>`).join('')}</div>
<div class="sx-bar" aria-hidden="true"><span class="${g.delta < 0 ? 'down' : ''}" style="width:${(Math.abs(g.delta) / max * 100).toFixed(1)}%"></span></div>
<div class="num ${g.delta > 0 ? 'up' : g.delta < 0 ? 'down' : ''}" style="text-align:right;font-variant-numeric:tabular-nums;">${g.noCoda ? '不算 CODA' : g.delta === 0 ? '不變' : `${g.delta > 0 ? '+' : '−'}${num(Math.abs(g.delta))}`}</div>`;
<div class="num ${g.delta > 0 ? 'up' : g.delta < 0 ? 'down' : ''}" style="text-align:right;font-variant-numeric:tabular-nums;">${g.noCoda ? '不算 CODA' : g.delta === 0 ? '不變' : `${g.delta > 0 ? '+' : '−'}${amtv(Math.abs(g.delta))}`}</div>`;
}).join('')}</div>
<div class="sx-sub" style="margin-top:4px;">實際 CODA 的變化,變最多的排最上面。</div>`;
}
@@ -289,7 +300,7 @@
${open ? `<div class="sx-row">${salaryButton('顯示目前薪資', '隱藏目前薪資')}</div>` : ''}
<div class="sx-scroll"><table><thead><tr><th>姓名</th><th>組</th><th class="num sal">目前</th><th class="num">模擬後</th></tr></thead><tbody>${raisable.map(p => {
const changed = st.raises[p.employeeNumber] !== undefined;
return `<tr class="${changed ? 'sx-changed' : ''}"><td>${esc(p.name)}</td><td>${esc(p.group)}</td><td class="num sal">${salaryCell((p.salaryType === 'hourly' ? '時 ' : '') + money(p.salary))}</td>
return `<tr class="${changed ? 'sx-changed' : ''}"><td>${esc(p.name)}</td><td>${esc(p.group)}</td><td class="num sal">${salaryCell((p.salaryType === 'hourly' ? '時 ' : '') + 'NT$ ' + num(p.salary || 0))}</td>
<td class="num"><input type="number" min="0" class="${changed ? 'sx-changed' : ''}" value="${st.raises[p.employeeNumber] ?? ''}" placeholder="不調整" data-sim="raise" data-id="${esc(p.employeeNumber)}" aria-label="${esc(p.name)} 模擬薪資"></td></tr>`;
}).join('')}</tbody></table></div></details>` : '';
const raiseCount = Object.keys(st.raises).length;
@@ -316,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('');
@@ -413,9 +426,10 @@
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);
state.data = data;
rerender();
} finally {
+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,
+166 -113
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,15 +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, 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);
@@ -29,61 +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;
// 目前年度(新檔案)。預設 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,
@@ -92,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;
@@ -129,6 +120,8 @@ const allowedStaticFiles = new Map([
['/2022_Moonshine_Logo_MS_logo_w_EN.png', ['2022_Moonshine_Logo_MS_logo_w_EN.png', 'image/png']],
['/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']],
@@ -148,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' };
@@ -235,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;
}
@@ -257,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();
@@ -326,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);
@@ -341,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) {
@@ -350,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();
@@ -391,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) {
@@ -464,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']);
@@ -529,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')));
@@ -543,63 +553,54 @@ 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;
async function getEnglishNames() {
if (englishNames) return englishNames;
englishNames = { byEmployee: {}, byName: {} };
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;
storage?.write('english-names.json', JSON.stringify(next, null, 2));
return next;
}
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));
}
// 待生效的設定和目前設定差在哪裡(給畫面顯示)。
@@ -661,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 };
@@ -682,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') {
@@ -698,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 {}
@@ -719,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>');
@@ -931,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, {
@@ -948,6 +956,50 @@ const server = createServer(async (request, response) => {
return response.end(content);
}
// 預排異動:只有最高管理者能看、能改。
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;
const permission = await getPermission(session, url);
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(visiblePeople(board.payload.baseData, permission), await getEnglishNames()) });
}
// 匯入英文名對照(整份取代):只有最高管理者。
if (request.method === 'PUT' && url.pathname === '/api/names') {
const session = requireAuth(request, response, true);
if (!session) return;
if (isProduction && !isTopAdmin(session.claims)) return sendJson(response, 403, { error: 'top_admin_only' });
let saved;
try {
saved = await saveEnglishNames(await readJson(request, 300_000));
} catch (error) {
if (error instanceof TypeError) return sendJson(response, 400, { error: 'invalid_names' });
throw error;
}
return sendJson(response, 200, { ok: true, byEmployee: Object.keys(saved.byEmployee).length, byName: Object.keys(saved.byName).length });
}
if (request.method === 'GET' && url.pathname === '/api/scope') {
const session = requireAuth(request, response, true);
if (!session) return;
@@ -958,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 }));
// 預排傳進去只為了「誰離開」那份清單(轉調後的人已經不在原部門,要靠 fromDept 才找得到)。
return sendJson(response, 200, { ...buildScopedView(model, anchors, permission, { year, plans: await planStore.load() }), usdRate: Number(board.payload.globalParams?.usdRate) || 30 });
}
// 對外接口:只接受 Bearer token(不用登入 session、不套工號白名單),只讀。
@@ -967,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;
@@ -1124,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;
}
+25 -1
View File
@@ -6,9 +6,10 @@ export const PARAM_KEYS = Object.freeze([
'invoiceWeightP', 'invoiceWeightA', 'invoiceWeightSurplus', 'targetAPRatio',
'externalProjectOutsourcing', 'employeeTripInvoices', 'grossMarginPct',
'rdReductionPct', 'pManagerReductionPct', 'pPCReductionPct', 'managerReductionPct', 'cgLeadReductionPct',
'contractorMultiplier',
'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);
});
+84
View File
@@ -0,0 +1,84 @@
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, visiblePeople } from '../english-names.js';
// 在沒有瀏覽器的環境載入 i18n.js,模擬瀏覽器裡存的語言/幣別設定。
async function loadI18n(saved = {}) {
const source = await readFile(new URL('../i18n.js', import.meta.url), 'utf8');
const attrs = {};
const context = {
localStorage: { getItem: key => saved[key] ?? null, setItem: (key, value) => { saved[key] = value; } },
document: { readyState: 'complete', documentElement: { setAttribute: (k, v) => { attrs[k] = v; } }, querySelectorAll: () => [], body: null, title: '' },
window: {}, fetch: () => Promise.resolve({ ok: false }), Promise, Set, WeakMap, Object, Array, Math, Number, String, RegExp,
};
context.window = context;
vm.runInNewContext(source, context);
return { api: context.PMI18n, attrs, saved };
}
test('default is Chinese and TWD; amounts keep NT$', async () => {
const { api, attrs } = await loadI18n();
assert.equal(api.lang(), 'zh');
assert.equal(api.currency(), 'TWD');
assert.equal(attrs.lang, 'zh-Hant');
assert.equal(api.cur(1234567.4), 'NT$ 1,234,567');
assert.equal(api.t('年度發票額'), '年度發票額');
});
test('USD converts with the core-parameter rate (default 30)', async () => {
const { api, saved } = await loadI18n({ 'pmb-currency': 'USD' });
assert.equal(api.rate(), 30);
assert.equal(api.cur(3_000_000), 'US$ 100,000');
assert.equal(api.cur(-300), '−US$ 10');
assert.equal(api.setRate(32), true);
assert.equal(saved['pmb-usd-rate'], '32');
assert.equal(api.amt(3200), '100');
assert.equal(api.setRate(0), false);
assert.equal(api.rate(), 32);
assert.equal(api.compact(30_000_000), '938K');
});
test('English translates phrases, departments and punctuation', async () => {
const { api, attrs } = await loadI18n({ 'pmb-lang': 'en' });
assert.equal(attrs.lang, 'en');
assert.equal(api.t('年度發票額'), 'Annual Invoice');
assert.equal(api.t(' 前製部 '), ' Pre-Production ');
assert.equal(api.t('實際 CODA(部門)'), 'Actual CODA (Department)');
assert.equal(api.t('部門 CODA'), 'Department CODA');
assert.equal(api.t('ABC 123'), 'ABC 123');
});
test('English names: only valid entries are kept; people not on the roster are left out', () => {
const store = normalizeEnglishNames({
byEmployee: { 20150906: 'Woody Yeh', 'x1': 'Bad Key', 20210701: ' ChihShiang Jan ', 20990101: '中文' },
byName: { 黃思豪: 'Triston Huang', Abc: 'No CJK key' },
});
assert.deepEqual(store, { byEmployee: { 20150906: 'Woody Yeh', 20210701: 'ChihShiang Jan' }, byName: { 黃思豪: 'Triston Huang' } });
const people = [
{ employeeNumber: '20150906', name: '葉傳耀' },
{ employeeNumber: '20210701', name: '詹智翔' },
{ employeeNumber: 'C-1', name: '黃思豪' },
{ employeeNumber: '20990202', name: '沒有英文名' },
];
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();
});