Compare commits
216
Commits
+13
-13
@@ -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
@@ -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 calc-engine.js anchor-calc.js anchor-store.js index.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
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
# 對外接口規格與發布規則
|
||||
|
||||
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)。發票半年定錨的實作計畫見 PLAN-ANCHOR.md。
|
||||
- 文件狀態:規格已確認,程式已上線(2026-10-28;2026-11-04 更新:CODA 分為實際 CODA 與定錨 CODA;2026-11-12:接口已上線,第一次定錨前一律回 503 尚未定錨)。發票半年定錨的實作計畫見 PLAN-ANCHOR.md。
|
||||
- 負責人:walkdoggo.yeh(定錨、發布與規則);RD(存取權限與系統帳號)
|
||||
|
||||
---
|
||||
|
||||
## 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
@@ -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`,不可直接開啟。網站只在伺服器處理上游憑證和全員資料,送到瀏覽器的內容依站台權限限制。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# pm-board
|
||||
# LeadBoard
|
||||
|
||||
MoonShine 成本與發票目標試算站。內部人員以 HR Sync 的在職名冊、組織與目前薪資轉入 2027 試算;常態型外包仍獨立維護。
|
||||
MoonShine 成本與發票目標試算站(原名 PM Board,2026-11 改名;對外接口的代號也已同步改為 leadboard。)。內部人員以 HR Sync 的在職名冊、組織與目前薪資轉入 2027 試算;常態型外包仍獨立維護。
|
||||
|
||||
## 本機預覽
|
||||
|
||||
|
||||
+91
-11
@@ -30,19 +30,32 @@ function invoiceMonths(person) {
|
||||
};
|
||||
}
|
||||
|
||||
// 調動後同一個人會拆成「調動前」「調動後」兩筆(splitTransfers);比對與快照時合回一個人:
|
||||
// 金額相加,部門/組用調動後(現在)的。
|
||||
export function mergedPeople(people) {
|
||||
const byKey = new Map();
|
||||
for (const p of people) {
|
||||
const key = personKey(p);
|
||||
const months = invoiceMonths(p);
|
||||
const entry = byKey.get(key);
|
||||
if (!entry) { byKey.set(key, { person: p, pa: months.pa, o: months.o, cost: (p.totalCost || 0) + (p.invoiceCost || 0) }); continue; }
|
||||
entry.pa = entry.pa.map((v, i) => v + months.pa[i]);
|
||||
entry.o = entry.o.map((v, i) => v + months.o[i]);
|
||||
entry.cost += (p.totalCost || 0) + (p.invoiceCost || 0);
|
||||
if (p.transferSplit !== 'before') entry.person = p;
|
||||
}
|
||||
return byKey;
|
||||
}
|
||||
|
||||
// 快照:從伺服器算好的模型抓出定錨需要的數字。
|
||||
export function buildSnapshot(model, { year, half, note, by, at }) {
|
||||
const invoiceDeptNames = Object.keys(model.allocations?.deptData || {});
|
||||
const people = model.people
|
||||
.filter(p => (p.totalCost || 0) > 0 || (p.invoiceCost || 0) > 0)
|
||||
.map(p => {
|
||||
const months = invoiceMonths(p);
|
||||
return {
|
||||
key: personKey(p), name: p.name || '', dept: (p.dept || '').trim(), group: (p.group || '').trim(),
|
||||
role: p.role || '', invoiceRole: p.invoiceRoleAtAnchor || null,
|
||||
pa: months.pa, o: months.o,
|
||||
};
|
||||
});
|
||||
const people = [...mergedPeople(model.people)]
|
||||
.filter(([, e]) => e.cost > 0)
|
||||
.map(([key, { person: p, pa, o }]) => ({
|
||||
key, name: p.name || '', dept: (p.dept || '').trim(), group: (p.group || '').trim(),
|
||||
role: p.role || '', invoiceRole: p.invoiceRoleAtAnchor || null, pa, o,
|
||||
}));
|
||||
const invoice = {};
|
||||
for (const dept of invoiceDeptNames) {
|
||||
const data = model.allocations.deptData[dept];
|
||||
@@ -64,7 +77,7 @@ export function buildSnapshot(model, { year, half, note, by, at }) {
|
||||
|
||||
// 調動:快照時的部門與現在不同。effectiveMonth 由使用者確認,預設為偵測到的月份。
|
||||
export function detectTransfers(snapshot, model, savedMonths = {}, detectedMonth = 1) {
|
||||
const now = new Map(model.people.map(p => [personKey(p), p]));
|
||||
const now = new Map([...mergedPeople(model.people)].map(([key, e]) => [key, e.person]));
|
||||
const list = [];
|
||||
for (const before of snapshot.people) {
|
||||
const current = now.get(before.key);
|
||||
@@ -175,3 +188,70 @@ export function halves(annual, half, h1Settled) {
|
||||
const h1 = Number(h1Settled) || 0;
|
||||
return { h1, h1Settled: true, h2: annual - h1 };
|
||||
}
|
||||
|
||||
// 異動清單:拿現在的資料和定錨快照逐人比對(新進、離職、調薪/成本變動、職能改變、調動)。
|
||||
// 金額是「全年」的增減;發票增減 = 內部人力 ÷ 毛利率 + 外包。生效月份取 HR 的日期。
|
||||
export function detectChanges(snapshot, model) {
|
||||
const margin = snapshot.grossMargin || 1;
|
||||
const before = new Map(snapshot.people.map(p => [p.key, p]));
|
||||
const merged = mergedPeople(model.people);
|
||||
const now = new Map([...merged].map(([key, e]) => [key, e.person]));
|
||||
const monthOf = (date) => { const m = /^\d{4}-(\d{2})/.exec(String(date || '')); return m ? Number(m[1]) : null; };
|
||||
const list = [];
|
||||
const push = (type, key, name, dept, group, beforeCost, afterCost, effectiveMonth, extra = {}) => {
|
||||
const pa = afterCost.pa - beforeCost.pa;
|
||||
const o = afterCost.o - beforeCost.o;
|
||||
list.push({ type, key, name, dept, group, effectiveMonth, costDelta: Math.round(pa + o), invoiceDelta: Math.round(pa / margin + o), ...extra });
|
||||
};
|
||||
const zero = { pa: 0, o: 0 };
|
||||
for (const [key, p] of now) {
|
||||
const cost = { pa: sum(merged.get(key).pa), o: sum(merged.get(key).o) };
|
||||
const old = before.get(key);
|
||||
const dept = (p.dept || '').trim();
|
||||
const group = (p.group || '').trim();
|
||||
if (!old) {
|
||||
if (cost.pa + cost.o > 0) push('new', key, p.name || '', dept, group, zero, cost, monthOf(p.hireDate));
|
||||
continue;
|
||||
}
|
||||
const oldCost = { pa: sum(old.pa), o: sum(old.o) };
|
||||
if (old.dept !== dept || old.group !== group) {
|
||||
list.push({ type: 'transfer', key, name: p.name || old.name, dept, group, from: { dept: old.dept, group: old.group }, effectiveMonth: null, costDelta: 0, invoiceDelta: 0 });
|
||||
}
|
||||
if (old.role !== (p.role || '')) push('role', key, p.name || old.name, dept, group, oldCost, cost, null, { fromRole: old.role, toRole: p.role || '' });
|
||||
else if (Math.abs((cost.pa + cost.o) - (oldCost.pa + oldCost.o)) > 1) {
|
||||
const type = p.leaveDate && cost.pa + cost.o < oldCost.pa + oldCost.o ? 'leave' : 'cost';
|
||||
push(type, key, p.name || old.name, dept, group, oldCost, cost, monthOf(type === 'leave' ? p.leaveDate : p.salaryEffectiveDate));
|
||||
}
|
||||
}
|
||||
for (const [key, old] of before) {
|
||||
if (now.has(key)) continue;
|
||||
push('leave', key, old.name, old.dept, old.group, { pa: sum(old.pa), o: sum(old.o) }, zero, null);
|
||||
}
|
||||
const order = { new: 0, leave: 1, cost: 2, role: 3, transfer: 4 };
|
||||
return list.sort((a, b) => order[a.type] - order[b.type] || a.dept.localeCompare(b.dept, 'zh-Hant'));
|
||||
}
|
||||
|
||||
// 實際 CODA 依調動月份拆分:生效月份之前算原部門/組,之後算新部門/組。
|
||||
// splits:[{ key, from: { dept, group }, month }]。只拆在職月份,薪資與設定不變。
|
||||
export function splitTransfers(people, splits) {
|
||||
if (!splits?.length) return people;
|
||||
const byKey = new Map(splits.map(s => [s.key, s]));
|
||||
const clip = (p, first, last) => {
|
||||
const out = { ...p };
|
||||
for (const [a, b] of [['h1Start', 'h1End'], ['h2Start', 'h2End']]) {
|
||||
if (out[a] === '' || out[b] === '' || out[a] === undefined || out[b] === undefined) continue;
|
||||
const start = Math.max(Number(out[a]), first);
|
||||
const end = Math.min(Number(out[b]), last);
|
||||
if (start > end) { out[a] = ''; out[b] = ''; } else { out[a] = start; out[b] = end; }
|
||||
}
|
||||
return out;
|
||||
};
|
||||
const result = [];
|
||||
for (const p of people) {
|
||||
const split = byKey.get(personKey(p));
|
||||
if (!split || split.month <= 1 || split.month > 12) { result.push(p); continue; }
|
||||
result.push({ ...clip(p, 1, split.month - 1), dept: split.from.dept, group: split.from.group, transferSplit: 'before', transferMonth: split.month, row: `${p.row}-before` });
|
||||
result.push({ ...clip(p, split.month, 12), transferSplit: 'after', transferMonth: split.month });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
+108
-26
@@ -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 { HALVES, anchoredCoda, anchoredInvoice, buildSnapshot, detectTransfers, halves } from './anchor-calc.js';
|
||||
import { bindFile } from './storage.js';
|
||||
import { HALVES, anchoredCoda, anchoredInvoice, buildSnapshot, detectChanges, detectTransfers, halves } from './anchor-calc.js';
|
||||
|
||||
const emptyYear = () => ({ anchors: [], peaks: {}, transfers: {}, log: [] });
|
||||
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`);
|
||||
}
|
||||
|
||||
// 所有寫入排隊執行,避免同時寫檔。
|
||||
@@ -57,13 +50,16 @@ export function createAnchorStore(path) {
|
||||
}
|
||||
|
||||
// 依目前模型算出定錨數字;最高點、新偵測到的調動會存檔。
|
||||
function evaluate(model, year, now = Date.now()) {
|
||||
// persist=false:模擬試算用,算完不存最高點、不記錄調動。
|
||||
function evaluate(model, year, now = Date.now(), { persist = true } = {}) {
|
||||
return serial(async () => {
|
||||
await load();
|
||||
const data = yearState(year);
|
||||
// 模擬時在複本上算,不改到記憶體裡的最高點與調動紀錄。
|
||||
const data = persist ? yearState(year) : JSON.parse(JSON.stringify(yearState(year)));
|
||||
const anchor = activeAnchor(data);
|
||||
const meta = data.anchors.map(({ year: y, half, note, by, at }) => ({ year: y, half, note, by, at }));
|
||||
if (!anchor) return { year, active: null, anchors: meta, nextHalf: 'H1' };
|
||||
const meta = data.anchors.map(({ year: y, half, note, by, at, version }) => ({ year: y, half, note, by, at, version }));
|
||||
const undone = (data.undone || []).map(({ half, at, undoneAt, undoneBy, reason, version }) => ({ half, at, undoneAt, undoneBy, reason, version }));
|
||||
if (!anchor) return { year, active: null, anchors: meta, nextHalf: 'H1', undone };
|
||||
let dirty = false;
|
||||
const detected = detectTransfers(anchor, model, data.transfers, currentMonth(year, now));
|
||||
for (const t of detected) {
|
||||
@@ -82,7 +78,7 @@ export function createAnchorStore(path) {
|
||||
const at = new Date(now).toISOString();
|
||||
for (const [dept, value] of Object.entries(invoice.peakUpdates)) { peaks.invoice[dept] = { value, at }; dirty = true; }
|
||||
for (const [id, value] of Object.entries(coda.peakUpdates)) { peaks.coda[id] = { value, at }; dirty = true; }
|
||||
if (dirty) await save();
|
||||
if (dirty && persist) await save();
|
||||
const h1Settled = anchor.h1Settled || {};
|
||||
const invoiceOut = Object.fromEntries(Object.entries(invoice.depts).map(([dept, v]) =>
|
||||
[dept, { ...v, ...halves(v.annual, anchor.half, h1Settled.invoice?.[dept]) }]));
|
||||
@@ -92,9 +88,12 @@ export function createAnchorStore(path) {
|
||||
[g, { ...gv, ...halves(gv.value, anchor.half, h1Settled.codaGroups?.[`${dept}|${g}`]) }])),
|
||||
}]));
|
||||
return {
|
||||
year, active: { half: anchor.half, at: anchor.at, by: anchor.by, note: anchor.note },
|
||||
year, active: { half: anchor.half, at: anchor.at, by: anchor.by, note: anchor.note, version: anchor.version || data.anchors.length },
|
||||
anchors: meta, nextHalf: anchor.half === 'H1' ? 'H2' : null,
|
||||
invoice: invoiceOut, coda: codaOut, transfers,
|
||||
changes: detectChanges(anchor, model),
|
||||
peakResets: (data.peakResets || []).filter(r => r.half === anchor.half),
|
||||
undone,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -120,6 +119,11 @@ export function createAnchorStore(path) {
|
||||
Object.entries(v.groups).map(([g, gv]) => [`${d}|${g}`, gv.h1]))),
|
||||
};
|
||||
}
|
||||
// 資料版本:每次定錨 +1,撤銷後重按也會 +1(對外系統看得出資料換過)。
|
||||
data.version = Math.max(Number(data.version) || 0, data.anchors.length + (data.undone || []).length) + 1;
|
||||
snapshot.version = data.version;
|
||||
// 撤銷時要還原:上一個半年的調動生效月份。
|
||||
snapshot.transfersBefore = data.transfers;
|
||||
data.anchors.push(snapshot);
|
||||
data.peaks[half] = { invoice: {}, coda: {} };
|
||||
data.transfers = {};
|
||||
@@ -147,5 +151,83 @@ export function createAnchorStore(path) {
|
||||
});
|
||||
}
|
||||
|
||||
return { evaluate, anchor, setTransferMonth };
|
||||
// 重設最高點(打錯資料時用):只有最高管理者,必須填原因,原本的值存起來可以還原。
|
||||
async function resetPeak({ year, kind, key, reason, by, now = Date.now() }) {
|
||||
if (!['invoice', 'coda'].includes(kind)) throw new RangeError('kind must be invoice or coda');
|
||||
if (!String(reason || '').trim()) throw new RangeError('reason is required');
|
||||
return serial(async () => {
|
||||
await load();
|
||||
const data = yearState(year);
|
||||
const anchor = activeAnchor(data);
|
||||
if (!anchor) throw new RangeError('not anchored');
|
||||
const peaks = data.peaks[anchor.half] || (data.peaks[anchor.half] = { invoice: {}, coda: {} });
|
||||
const previous = peaks[kind][key] || null;
|
||||
if (!previous) throw new RangeError('no peak to reset');
|
||||
const at = new Date(now).toISOString();
|
||||
const entry = { id: `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`, half: anchor.half, kind, key, previous, reason: String(reason).slice(0, 300), by, at };
|
||||
data.peakResets = [...(data.peakResets || []), entry];
|
||||
delete peaks[kind][key];
|
||||
data.log.push({ action: 'peak-reset', kind, key, previous, reason: entry.reason, by, at });
|
||||
await save();
|
||||
return { ok: true, id: entry.id };
|
||||
});
|
||||
}
|
||||
|
||||
// 還原最高點重設:把當時的值放回去(只會更高,不會讓數字降)。
|
||||
async function restorePeak({ year, id, by, now = Date.now() }) {
|
||||
return serial(async () => {
|
||||
await load();
|
||||
const data = yearState(year);
|
||||
const entry = (data.peakResets || []).find(r => r.id === id && !r.restoredAt);
|
||||
if (!entry) throw new RangeError('unknown reset');
|
||||
const peaks = data.peaks[entry.half] || (data.peaks[entry.half] = { invoice: {}, coda: {} });
|
||||
const current = Number(peaks[entry.kind][entry.key]?.value) || 0;
|
||||
if (Number(entry.previous.value) > current) peaks[entry.kind][entry.key] = entry.previous;
|
||||
const at = new Date(now).toISOString();
|
||||
entry.restoredAt = at;
|
||||
entry.restoredBy = by;
|
||||
data.log.push({ action: 'peak-restore', id, kind: entry.kind, key: entry.key, by, at });
|
||||
await save();
|
||||
return { ok: true };
|
||||
});
|
||||
}
|
||||
|
||||
// 撤銷最近一次定錨:只有最高管理者,必須填原因。快照移到「已撤銷」保留紀錄,
|
||||
// 回到定錨前的狀態(上一個半年的最高點與調動月份還在),可以重新定錨。
|
||||
async function undoAnchor({ year, reason, by, now = Date.now() }) {
|
||||
if (!String(reason || '').trim()) throw new RangeError('reason is required');
|
||||
return serial(async () => {
|
||||
await load();
|
||||
const data = yearState(year);
|
||||
const last = data.anchors.pop();
|
||||
if (!last) throw new RangeError('not anchored');
|
||||
const at = new Date(now).toISOString();
|
||||
data.undone = [...(data.undone || []), { ...last, undoneAt: at, undoneBy: by, reason: String(reason).slice(0, 300) }];
|
||||
delete data.peaks[last.half];
|
||||
data.transfers = last.transfersBefore || {};
|
||||
data.log.push({ action: 'undo-anchor', half: last.half, version: last.version, reason: String(reason).slice(0, 300), by, at });
|
||||
await save();
|
||||
return { ok: true, half: last.half };
|
||||
});
|
||||
}
|
||||
|
||||
// 目前定錨後的調動(給實際 CODA 按月拆分用):key、原部門/組、生效月份。
|
||||
async function transferSplits(year) {
|
||||
await load();
|
||||
const data = state.years[String(year)];
|
||||
const anchor = data && activeAnchor(data);
|
||||
if (!anchor) return [];
|
||||
const before = new Map(anchor.people.map(p => [p.key, p]));
|
||||
return Object.entries(data.transfers || {}).filter(([key]) => before.has(key)).map(([key, t]) => ({
|
||||
key, from: { dept: before.get(key).dept, group: before.get(key).group }, month: t.month || t.detectedMonth,
|
||||
}));
|
||||
}
|
||||
|
||||
// 這一年有沒有定錨過(對外接口在第一次定錨前一律回 503)。
|
||||
async function hasAnchor(year) {
|
||||
await load();
|
||||
return Boolean(state.years[String(year)]?.anchors?.length);
|
||||
}
|
||||
|
||||
return { evaluate, anchor, setTransferMonth, hasAnchor, resetPeak, restorePeak, undoAnchor, transferSplits };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// 年度封存:年底(H2 定錨之後)把這一年的結果存成唯讀快照,之後可以切換年份查看。
|
||||
// 存在 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);
|
||||
|
||||
// 只存部門、組的數字與定錨結果;個人資料不進封存。
|
||||
export function buildArchive(model, anchors, { year, by, note, at }) {
|
||||
return {
|
||||
year, by, note: String(note || '').slice(0, 500), archivedAt: at,
|
||||
calcVersion: model.calcVersion,
|
||||
anchors: anchors?.anchors || [],
|
||||
invoiceTotal: round(model.invoice?.finalInvoiceTotal),
|
||||
depts: Object.entries(model.codaGroups || {}).map(([dept, data]) => ({
|
||||
dept, company: model.deptCompany?.[dept] || '',
|
||||
actualCoda: round(data.coda), avgDailyCoda: round(data.avgDailyCoda),
|
||||
invoice: model.allocations?.deptData?.[dept] ? round(model.invoice.finalInvoiceTotal * (model.allocations.deptData[dept].finalPct || 0)) : null,
|
||||
anchoredInvoice: anchors?.invoice?.[dept] ? { annual: round(anchors.invoice[dept].annual), h1: round(anchors.invoice[dept].h1), h2: anchors.invoice[dept].h2 === null ? null : round(anchors.invoice[dept].h2) } : null,
|
||||
anchoredCoda: anchors?.coda?.[dept] ? { annual: round(anchors.coda[dept].value), h1: round(anchors.coda[dept].h1), h2: anchors.coda[dept].h2 === null ? null : round(anchors.coda[dept].h2) } : null,
|
||||
groups: Object.entries(data.groups).map(([group, g]) => ({
|
||||
group, actualCoda: round(g.coda), avgDailyCoda: round(g.avgDailyCoda),
|
||||
anchoredCoda: anchors?.coda?.[dept]?.groups?.[group] ? round(anchors.coda[dept].groups[group].value) : null,
|
||||
})),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export function createArchiveStore(source) {
|
||||
const memory = new Map();
|
||||
const storage = bindDirectory(source);
|
||||
const name = (year) => `${Number(year)}.json`;
|
||||
return {
|
||||
async list() {
|
||||
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 (!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 (!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;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-Hant">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<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; }
|
||||
@media (prefers-color-scheme: dark) { :root { --bg:#16181c; --card:#1f2228; --text:#eceef1; --muted:#a3a9b3; --line:#30343c; --accent:#8fa2ff; --warn:#f0a35a; } }
|
||||
* { 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:1100px; margin:0 auto; padding:24px 16px 64px; }
|
||||
h1 { font-size:1.5rem; margin:0 0 4px; }
|
||||
.sub { color:var(--muted); font-size:.85rem; }
|
||||
.card { background:var(--card); border:1px solid var(--line); border-radius:14px; padding:18px; margin:16px 0; }
|
||||
table { width:100%; border-collapse:collapse; font-size:.88rem; }
|
||||
th, td { padding:7px 6px; border-bottom:1px solid var(--line); text-align:left; vertical-align:top; }
|
||||
th { color:var(--muted); font-weight:500; font-size:.8rem; }
|
||||
td.num, th.num { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; }
|
||||
.scroll { overflow-x:auto; }
|
||||
.years { display:flex; gap:8px; flex-wrap:wrap; }
|
||||
.years a, .years span { border:1px solid var(--line); border-radius:99px; padding:3px 12px; text-decoration:none; color:var(--text); }
|
||||
.years .on { background:var(--accent); color:#fff; border-color:var(--accent); }
|
||||
input[type=text] { font:inherit; padding:4px 8px; border:1px solid var(--line); border-radius:6px; background:var(--bg); color:var(--text); min-width:260px; }
|
||||
button { font:inherit; border:1px solid var(--line); background:var(--card); color:var(--text); border-radius:8px; padding:4px 12px; cursor:pointer; }
|
||||
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">← 回到 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>
|
||||
<div id="content"></div>
|
||||
</main>
|
||||
<script>
|
||||
const money = v => v === null || v === undefined ? '—' : 'NT$ ' + Math.round(v).toLocaleString();
|
||||
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const params = new URLSearchParams(location.search);
|
||||
let info = null; let confirming = false; let confirmingNext = false;
|
||||
|
||||
async function startNextYear() {
|
||||
const response = await fetch('/api/year/next', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ confirm: true }) });
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (!response.ok) { document.getElementById('action').insertAdjacentHTML('beforeend', `<div class="warn" role="alert">沒有完成:${body.error === 'archive_required' ? '要先封存目前年度' : esc(body.error || response.status)}</div>`); return; }
|
||||
location.href = '/';
|
||||
}
|
||||
|
||||
function drawAction() {
|
||||
const el = document.getElementById('action');
|
||||
if (info.years.includes(info.currentYear)) {
|
||||
el.innerHTML = confirmingNext
|
||||
? `<button type="button" onclick="startNextYear()">確定開始 ${info.currentYear + 1} 年</button> <button type="button" onclick="confirmingNext=false;drawAction()">取消</button>
|
||||
<div class="sub">開始後首頁、定錨、對外接口都改用 ${info.currentYear + 1} 年;職能沿用,在職月份重設為全年(再依 HR 到職/離職限縮)。${info.currentYear} 年留在封存裡,可以切回來看。</div>`
|
||||
: `<span class="sub">${info.currentYear} 年已封存。</span> <button type="button" onclick="confirmingNext=true;drawAction()">開始 ${info.currentYear + 1} 年…</button>`;
|
||||
return;
|
||||
}
|
||||
el.innerHTML = confirming
|
||||
? `<input id="note" type="text" maxlength="500" placeholder="說明(必填)" aria-label="封存說明"> <button type="button" onclick="archiveNow()">確定封存 ${info.currentYear} 年</button> <button type="button" onclick="confirming=false;drawAction()">取消</button>
|
||||
<div class="sub">封存後不能修改,請確認 H2 已定錨、年底結算已完成。</div>`
|
||||
: `<button type="button" onclick="confirming=true;drawAction()">封存 ${info.currentYear} 年…</button> <span class="sub">(年底、H2 定錨之後)</span>`;
|
||||
}
|
||||
|
||||
async function archiveNow() {
|
||||
const note = document.getElementById('note').value.trim();
|
||||
if (!note) { document.getElementById('note').focus(); return; }
|
||||
const response = await fetch('/api/archive', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ note, confirm: true }) });
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
document.getElementById('action').insertAdjacentHTML('beforeend', `<div class="warn" role="alert">沒有封存:${body.error === 'h2_anchor_required' ? '要先完成 H2 定錨' : esc(body.error || response.status)}</div>`);
|
||||
return;
|
||||
}
|
||||
location.href = `/archive?year=${body.year}`;
|
||||
}
|
||||
|
||||
function drawArchive(a) {
|
||||
const rows = a.depts.filter(d => d.actualCoda || d.invoice || d.anchoredCoda?.annual).map(d => `<tr><td>${esc(d.dept)}<div class="sub">${esc(d.company)}</div></td>
|
||||
<td class="num">${money(d.actualCoda)}</td><td class="num">${money(d.avgDailyCoda)}</td><td class="num">${d.anchoredCoda ? money(d.anchoredCoda.annual) : '—'}</td>
|
||||
<td class="num">${d.anchoredInvoice ? money(d.anchoredInvoice.annual) : money(d.invoice)}</td><td class="num">${d.anchoredInvoice ? money(d.anchoredInvoice.h1) + ' / ' + money(d.anchoredInvoice.h2) : '—'}</td></tr>`).join('');
|
||||
document.getElementById('content').innerHTML = `<div class="card"><h2 style="margin:0;font-size:1.1rem;">${a.year} 年(已封存)</h2>
|
||||
<div class="sub">封存時間 ${new Date(a.archivedAt).toLocaleString('zh-TW', { hour12: false })} 說明:${esc(a.note)} 定錨 ${a.anchors.map(x => x.half).join('、') || '—'} 年度發票目標 ${money(a.invoiceTotal)}</div>
|
||||
<div class="scroll" style="margin-top:10px;"><table><thead><tr><th>部門</th><th class="num">實際 CODA</th><th class="num">平均日 CODA</th><th class="num">定錨 CODA</th><th class="num">發票全年</th><th class="num">H1 / H2</th></tr></thead><tbody>${rows}</tbody></table></div></div>`;
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const response = await fetch('/api/archive', { cache: 'no-store' });
|
||||
if (response.status === 401) { location.href = '/api/auth/login'; return; }
|
||||
if (!response.ok) { document.getElementById('years').textContent = '只有最高管理者可以查看年度封存。'; return; }
|
||||
info = await response.json();
|
||||
const selected = Number(params.get('year')) || null;
|
||||
document.getElementById('years').innerHTML = [`<a href="/">${info.currentYear}(目前)</a>`, ...info.years.filter(y => y !== info.currentYear || true).map(y => `<a href="/archive?year=${y}" class="${y === selected ? 'on' : ''}">${y}(已封存)</a>`)].join('')
|
||||
+ (info.years.length ? '' : '<span class="sub" style="border:0;">還沒有封存的年度</span>');
|
||||
drawAction();
|
||||
if (selected) {
|
||||
const a = await fetch(`/api/archive?year=${selected}`, { cache: 'no-store' });
|
||||
document.getElementById('content').innerHTML = a.ok ? '' : '<div class="card">這一年還沒有封存。</div>';
|
||||
if (a.ok) drawArchive(await a.json());
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+54
@@ -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;
|
||||
}
|
||||
}
|
||||
+49
-8
@@ -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);
|
||||
@@ -566,14 +595,19 @@
|
||||
|
||||
// Calculate Total Redistribution Pool from RD and CG Lead
|
||||
const totalRDTax = sortedGroups.filter(g => g.isRD).reduce((acc, g) => acc + (g.initialCoda * rdReductionPct), 0);
|
||||
const totalCGLeadTax = sortedGroups.filter(g => g.isCGLead).reduce((acc, g) => acc + (g.initialCoda * (1 - cgLeadReductionPct)), 0);
|
||||
// 同時是研發組與 CG Lead 組:先減研發,再對剩下的部分減 CG Lead(2026-11-04 決定「兩個都減」),
|
||||
// 兩份減掉的金額都進分攤池,所以各組加總仍等於部門 CODA。
|
||||
const totalCGLeadTax = sortedGroups.filter(g => g.isCGLead).reduce((acc, g) => acc + (g.initialCoda * (g.isRD ? (1 - rdReductionPct) : 1) * (1 - cgLeadReductionPct)), 0);
|
||||
|
||||
// Final pool to redistribute to NORMAL groups (Non-RD AND Non-CGLead)
|
||||
const totalRedistributionPool = totalRDTax + totalCGLeadTax;
|
||||
const normalGroupsInitialCodaTotal = sortedGroups.filter(g => !g.isRD && !g.isCGLead).reduce((acc, g) => acc + g.initialCoda, 0);
|
||||
|
||||
sortedGroups.forEach(g => {
|
||||
if (g.isRD) {
|
||||
if (g.isRD && g.isCGLead) {
|
||||
g.finalCoda = g.initialCoda * (1 - rdReductionPct) * cgLeadReductionPct;
|
||||
g.rdNote = `研發減免 -${formatPct(rdReductionPct * 100)}%,CG Lead 承擔 -${formatPct((1 - cgLeadReductionPct) * 100)}%`;
|
||||
} else if (g.isRD) {
|
||||
g.finalCoda = g.initialCoda * (1 - rdReductionPct);
|
||||
g.rdNote = `研發減免 -${formatPct(rdReductionPct * 100)}%`;
|
||||
} else if (g.isCGLead) {
|
||||
@@ -607,7 +641,14 @@
|
||||
const out = {};
|
||||
targetDepts.forEach(d => {
|
||||
const { sortedGroups } = codaGroupsForDept(d, groupsByDept[d], deptCoda[d] || 0);
|
||||
out[d] = { coda: deptCoda[d] || 0, groups: {} };
|
||||
// 部門平均日 CODA:與 CODA 頁相同(組內所有人,不含實習生,依在職月份折算人數)。
|
||||
const deptFTE = Object.values(groupsByDept[d]).reduce((acc, g) => acc + g.people.reduce((acc2, p) => {
|
||||
if (isCostExcludedIntern(p)) return acc2;
|
||||
const m1 = (p.h1Start && p.h1End) ? Math.max(0, parseInt(p.h1End) - parseInt(p.h1Start) + 1) : 0;
|
||||
const m2 = (p.h2Start && p.h2End) ? Math.max(0, parseInt(p.h2End) - parseInt(p.h2Start) + 1) : 0;
|
||||
return acc2 + ((m1 + m2) / 12);
|
||||
}, 0), 0);
|
||||
out[d] = { coda: deptCoda[d] || 0, avgDailyCoda: deptFTE === 0 ? 0 : ((deptCoda[d] || 0) / annualWorkDays) / deptFTE, fte: deptFTE, groups: {} };
|
||||
sortedGroups.forEach(g => {
|
||||
out[d].groups[g.gName] = {
|
||||
coda: g.finalCoda,
|
||||
|
||||
+23
-1
@@ -7,7 +7,7 @@ const source = readFileSync(new URL('./calc-core.js', import.meta.url), 'utf8');
|
||||
const script = new vm.Script(`${source}
|
||||
;({ initOrgStructure, calculateAll, calculateInvoiceSummary, calculateDeptAllocations,
|
||||
codaPageByDept, codaShares, dashboardMultiplierUnits, activeMonths, deptCompanyMap,
|
||||
personCompany, personInvoiceRole, invoiceDepts, isCostExcludedIntern, codaByGroup })`, { filename: 'calc-core.js' });
|
||||
personCompany, personInvoiceRole, invoiceDepts, isCostExcludedIntern, codaByGroup, shortCompanyName })`, { filename: 'calc-core.js' });
|
||||
|
||||
const clone = (value) => JSON.parse(JSON.stringify(value));
|
||||
|
||||
@@ -30,6 +30,23 @@ export function computeModel(input) {
|
||||
const ownCoda = core.codaPageByDept(baseData, true);
|
||||
const codaSharing = core.codaShares(baseData, ownCoda);
|
||||
const codaGroups = core.codaByGroup(baseData);
|
||||
// 主看板的倍率:部門內部成本(P+A+G,不含外包)÷ A 成本;顯示時再乘人薪倍率。夢境現實整間公司算一個。
|
||||
const opMultiplier = Number(globalParams.opMultiplier) || 2.0;
|
||||
const multiplierUnits = core.dashboardMultiplierUnits(baseData, Object.keys(globalParams.orgStructure), deptStats);
|
||||
// 總人力成本(和主看板「全企業總成本」同一個算法):正職年薪 × 人薪倍率 + 常態型外包 × 外包倍率;不含實習生。
|
||||
const contractorRate = globalParams.contractorMultiplier !== undefined && globalParams.contractorMultiplier !== ''
|
||||
&& Number.isFinite(Number(globalParams.contractorMultiplier)) && Number(globalParams.contractorMultiplier) >= 0 ? Number(globalParams.contractorMultiplier) : 1.5;
|
||||
const staffCost = { depts: {}, groups: {} };
|
||||
for (const person of baseData) {
|
||||
const dept = (person.dept || '').trim();
|
||||
if (!dept) continue;
|
||||
const contractor = String(person.role || '').startsWith('O');
|
||||
if (!contractor && core.isCostExcludedIntern(person)) continue;
|
||||
const cost = (Number(person.realSalaryTotal) || 0) * (contractor ? contractorRate : opMultiplier);
|
||||
const key = `${dept}|${person.group || '未分組'}`;
|
||||
staffCost.depts[dept] = (staffCost.depts[dept] || 0) + cost;
|
||||
staffCost.groups[key] = (staffCost.groups[key] || 0) + cost;
|
||||
}
|
||||
return JSON.parse(JSON.stringify({
|
||||
calcVersion: 2,
|
||||
people: baseData,
|
||||
@@ -43,5 +60,10 @@ export function computeModel(input) {
|
||||
ownCoda,
|
||||
codaSharing,
|
||||
codaGroups,
|
||||
opMultiplier,
|
||||
multiplierUnits,
|
||||
staffCost,
|
||||
// 每個部門所屬公司(簡稱,例如「夢想創造」),對外接口用來分公司。
|
||||
deptCompany: Object.fromEntries([...core.deptCompanyMap(baseData)].map(([dept, company]) => [dept, core.shortCompanyName(company)])),
|
||||
}));
|
||||
}
|
||||
|
||||
+4
-3
@@ -85,13 +85,14 @@ export function boundMonths(months, hireDate, leaveDate, year) {
|
||||
return out;
|
||||
}
|
||||
|
||||
export function toCostPerson(person, salary, override = {}, { year } = {}) {
|
||||
export function toCostPerson(person, salary, override = {}, { year, fullYearDefault = false } = {}) {
|
||||
const saved = normalizeOverride(override);
|
||||
const months = boundMonths({
|
||||
h1Start: has(saved, 'h1Start') ? saved.h1Start : 1,
|
||||
h1End: has(saved, 'h1End') ? saved.h1End : 6,
|
||||
h2Start: has(saved, 'h2Start') ? saved.h2Start : '',
|
||||
h2End: has(saved, 'h2End') ? saved.h2End : '',
|
||||
// 2028 起預設全年(再依 HR 到職/離職限縮);2027 維持原本的預設(H2 留空)。
|
||||
h2Start: has(saved, 'h2Start') ? saved.h2Start : (fullYearDefault ? 7 : ''),
|
||||
h2End: has(saved, 'h2End') ? saved.h2End : (fullYearDefault ? 12 : ''),
|
||||
}, person.hireDate, person.leaveDate, year);
|
||||
const place = placement(person, saved);
|
||||
const salaryType = salary?.salaryType === 'hourly' ? 'hourly' : 'monthly';
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 || '未分組'}`);
|
||||
});
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
// 對外接口 /api/external/v1/{invoice,coda}(EXTERNAL-API-SPEC.md 第 8 節、AUTHENTIK-HANDOFF.md 第 2 節)。
|
||||
// - 驗證: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 = '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: '對外接口開始提供' },
|
||||
{ calcVersion: 2, date: '2027-01', change: '發票半年定錨、只增不減;部門調動依生效月份移轉發票', reason: '避免減人降低發票與部門間零和' },
|
||||
{ calcVersion: 3, date: '2027-01', change: '實際 CODA 與定錨 CODA;實習生 × 1 只進發票;工讀以外包計(日薪=時薪×8);管理職以 HR 組織主管為準', reason: '定錨 CODA 與發票一起半年定錨,實際 CODA 仍即時反映供定價' },
|
||||
]);
|
||||
const INVOICE_COMPANY = '夢想創造';
|
||||
const REALITY_COMPANY = '夢境現實';
|
||||
const RD_DEPT = '研發部';
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(status, code, message) { super(message || code); this.status = status; this.code = code; }
|
||||
}
|
||||
|
||||
const decode = (segment) => JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));
|
||||
|
||||
// getKeys(force) 回傳 JWKS;找不到 kid 時強制重抓一次(金鑰輪替)。
|
||||
export async function verifyApiToken(authorization, { issuer, getKeys, now = Date.now() }) {
|
||||
const match = /^Bearer\s+([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/.exec(String(authorization || ''));
|
||||
if (!match) throw new ApiError(401, 'token_required');
|
||||
const [head, body, signature] = match[1].split('.');
|
||||
let header; let payload;
|
||||
try { header = decode(head); payload = decode(body); } catch { throw new ApiError(401, 'invalid_token'); }
|
||||
if (header.alg !== 'RS256') throw new ApiError(401, 'invalid_token');
|
||||
let keys = await getKeys(false);
|
||||
let jwk = keys?.keys?.find(key => key.kid === header.kid && key.kty === 'RSA');
|
||||
if (!jwk) { keys = await getKeys(true); jwk = keys?.keys?.find(key => key.kid === header.kid && key.kty === 'RSA'); }
|
||||
if (!jwk) throw new ApiError(401, 'invalid_token');
|
||||
const valid = verify('RSA-SHA256', Buffer.from(`${head}.${body}`), createPublicKey({ key: jwk, format: 'jwk' }), Buffer.from(signature, 'base64url'));
|
||||
const audience = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
||||
const expected = `${String(issuer).replace(/\/+$/, '')}/`;
|
||||
if (!valid || payload.iss !== expected || !audience.includes(API_AUDIENCE)) throw new ApiError(401, 'invalid_token');
|
||||
if (!payload.exp || payload.exp * 1000 <= now) throw new ApiError(401, 'token_expired');
|
||||
const scopes = String(payload.scope || '').split(/\s+/);
|
||||
if (!scopes.includes(API_SCOPE)) throw new ApiError(403, 'insufficient_scope');
|
||||
return { sub: payload.sub, actorType: payload.actor_type || null, employeeNumber: payload.employee_number || null };
|
||||
}
|
||||
|
||||
// HR 組織代碼:依名稱與層級找。
|
||||
function codes(organizations) {
|
||||
const dept = new Map();
|
||||
const group = new Map();
|
||||
for (const unit of organizations || []) {
|
||||
const level = String(unit.levelName || '').trim();
|
||||
if (['部', '部門'].includes(level)) dept.set(unit.deptName, unit.deptCode);
|
||||
if (['組', '組別'].includes(level)) group.set(`${unit.upperDeptCode}|${unit.deptName}`, unit.deptCode);
|
||||
}
|
||||
return { dept, group };
|
||||
}
|
||||
|
||||
const round = (value) => Math.round(Number(value) || 0);
|
||||
|
||||
function anchoredBlock(v, half) {
|
||||
if (!v) return null;
|
||||
return {
|
||||
annual: round(v.value ?? v.annual), h1: round(v.h1), h1Settled: half === 'H2',
|
||||
h2: half === 'H2' ? round(v.h2) : round((v.value ?? v.annual) - v.h1), h2Provisional: half !== 'H2',
|
||||
};
|
||||
}
|
||||
|
||||
export function buildExternal(model, anchors, { organizations = [], generatedAt = new Date().toISOString(), opMultiplier = 2 } = {}) {
|
||||
if (!anchors?.active) throw new ApiError(503, 'not_anchored', '尚未定錨');
|
||||
const half = anchors.active.half;
|
||||
const common = {
|
||||
year: anchors.year,
|
||||
dataVersion: `v${anchors.active.version || anchors.anchors.length}`,
|
||||
anchoredAt: anchors.active.at,
|
||||
calcVersion: CALC_VERSION,
|
||||
half,
|
||||
generatedAt,
|
||||
calcChangelog: CALC_CHANGELOG,
|
||||
};
|
||||
const code = codes(organizations);
|
||||
const companyOf = model.deptCompany || {};
|
||||
const invoiceDepts = Object.keys(model.allocations?.deptData || {}).filter(d => companyOf[d] === INVOICE_COMPANY);
|
||||
const departments = invoiceDepts.map(dept => {
|
||||
const v = anchors.invoice?.[dept] || { anchored: 0, transferNet: 0, peak: 0, annual: 0, h1: 0, h2: null };
|
||||
return {
|
||||
company: INVOICE_COMPANY, deptCode: code.dept.get(dept) || null, dept,
|
||||
anchorAnnual: round(v.anchored + v.transferNet), increase: round(v.peak), annual: round(v.annual),
|
||||
h1: { target: round(v.h1), settled: half === 'H2' },
|
||||
h2: { target: round(half === 'H2' ? v.h2 : v.annual - v.h1), provisional: half !== 'H2' },
|
||||
};
|
||||
});
|
||||
const rdCost = model.people
|
||||
.filter(p => (p.dept || '').trim() === RD_DEPT && !String(p.role || '').startsWith('O') && !p.invoiceCost)
|
||||
.reduce((sum, p) => sum + (Number(p.realSalaryTotal) || 0), 0) * opMultiplier;
|
||||
const invoice = {
|
||||
...common, company: INVOICE_COMPANY,
|
||||
invoiceTotal: departments.reduce((sum, d) => sum + d.annual, 0),
|
||||
departments,
|
||||
rdDeptCost: { company: INVOICE_COMPANY, deptCode: code.dept.get(RD_DEPT) || null, dept: RD_DEPT, cost: round(rdCost) },
|
||||
};
|
||||
|
||||
const deptBlock = (dept, withGroups) => {
|
||||
const actual = model.codaGroups?.[dept] || { coda: 0, avgDailyCoda: 0, groups: {} };
|
||||
const anchored = anchors.coda?.[dept];
|
||||
const deptCode = code.dept.get(dept) || null;
|
||||
const block = { deptCode, dept, actualCoda: round(actual.coda), avgDailyCoda: round(actual.avgDailyCoda), anchoredCoda: anchoredBlock(anchored, half) };
|
||||
if (withGroups) {
|
||||
block.groups = Object.entries(actual.groups).map(([group, g]) => ({
|
||||
groupCode: code.group.get(`${deptCode}|${group}`) || null, group,
|
||||
actualCoda: round(g.coda), avgDailyCoda: round(g.avgDailyCoda),
|
||||
anchoredCoda: anchoredBlock(anchored?.groups?.[group], half),
|
||||
}));
|
||||
}
|
||||
return block;
|
||||
};
|
||||
const dream = invoiceDepts.map(d => deptBlock(d, true));
|
||||
const realityDepts = Object.keys(model.codaGroups || {}).filter(d => companyOf[d] === REALITY_COMPANY && round(model.codaGroups[d].coda) > 0);
|
||||
const reality = realityDepts.map(d => deptBlock(d, false));
|
||||
const coda = {
|
||||
...common,
|
||||
companies: [
|
||||
{ company: INVOICE_COMPANY, actualCoda: dream.reduce((s, d) => s + d.actualCoda, 0), departments: dream },
|
||||
{ company: REALITY_COMPANY, actualCoda: reality.reduce((s, d) => s + d.actualCoda, 0), departments: reality },
|
||||
],
|
||||
};
|
||||
return { invoice, coda };
|
||||
}
|
||||
@@ -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
@@ -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));
|
||||
+789
-90
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,93 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-Hant">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>MoonShine LeadBoard · 我的範圍</title>
|
||||
<link rel="icon" href="/2022_Moonshine_Logo_MS_logo_w_EN.png">
|
||||
<script>
|
||||
// 日間/夜間:和主看板共用同一個設定(pmb-theme);沒選過就跟著系統。
|
||||
(function () {
|
||||
var theme = null;
|
||||
try { theme = localStorage.getItem('pmb-theme'); } catch (e) {}
|
||||
if (theme !== 'light' && theme !== 'dark') theme = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
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; }
|
||||
:root { --sx-card:var(--card); --sx-text:var(--text); --sx-muted:var(--muted); --sx-line:var(--line); --sx-accent:var(--accent); --sx-warn:var(--warn); --sx-good:var(--good); --sx-input:var(--bg); --sx-up:var(--accent); --sx-down:var(--warn); }
|
||||
:root[data-theme="dark"] { --sx-on-accent:#16181c;
|
||||
--sx-tint-coda:#1d252e; --sx-tint-coda-border:#2c3a47; --sx-dot-coda:#7fa7c4;
|
||||
--sx-tint-inv:#2a2420; --sx-tint-inv-border:#45372a; --sx-dot-inv:#e0a15a; --sx-tint-inv2:#24201d;
|
||||
--sx-tint-group:#20251f; --sx-tint-group-border:#33402f; --sx-dot-group:#9bb38d;
|
||||
--sx-tint-sim:rgba(255,255,255,.03); --sx-sim-bar:#a9c23a; --sx-kpi-bg:rgba(255,255,255,.04); --sx-strong:rgba(255,255,255,.05); }
|
||||
* { 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:1100px; margin:0 auto; padding:24px 16px 64px; }
|
||||
header { display:flex; justify-content:space-between; align-items:flex-end; flex-wrap:wrap; gap:12px; margin-bottom:20px; }
|
||||
h1 { font-size:1.5rem; margin:0; }
|
||||
.sub { color:var(--muted); font-size:.85rem; }
|
||||
.bar { display:flex; align-items:center; gap:10px; flex-wrap:wrap; justify-content:flex-end; }
|
||||
.theme { display:inline-flex; border:1px solid var(--line); border-radius:99px; padding:2px; background:var(--card); }
|
||||
.theme button { font:inherit; font-size:.8rem; border:0; background:transparent; color:var(--muted); border-radius:99px; padding:4px 12px; cursor:pointer; }
|
||||
.theme button[aria-pressed="true"] { background:var(--text); color:var(--bg); }
|
||||
.logout { margin:0; }
|
||||
.logout button { font:inherit; font-size:.8rem; border:1px solid var(--line); background:var(--card); color:var(--text); border-radius:99px; padding:5px 14px; cursor:pointer; }
|
||||
.logout button:hover { border-color:var(--muted); }
|
||||
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>
|
||||
<header>
|
||||
<div>
|
||||
<h1>我的範圍</h1>
|
||||
<div class="sub" id="who">讀取中…</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="bar">
|
||||
<div class="theme" role="group" aria-label="配色">
|
||||
<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>
|
||||
</div>
|
||||
<div class="sub" id="year" style="text-align:right;margin-top:6px;"></div>
|
||||
</div>
|
||||
</header>
|
||||
<div id="content" aria-live="polite"></div>
|
||||
<p class="sub">實際 CODA:即時計算,資料一變就跟著變,定價看「平均日 CODA」。定錨 CODA:半年的目標(1 月、7 月定錨),半年內只增不減。所有數字都由伺服器計算。</p>
|
||||
</main>
|
||||
<script src="/scope-ui.js"></script>
|
||||
<script>
|
||||
function syncTheme() {
|
||||
const theme = document.documentElement.getAttribute('data-theme');
|
||||
document.querySelectorAll('[data-theme-set]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.themeSet === theme)));
|
||||
}
|
||||
document.querySelectorAll('[data-theme-set]').forEach(b => b.addEventListener('click', () => {
|
||||
document.documentElement.setAttribute('data-theme', b.dataset.themeSet);
|
||||
try { localStorage.setItem('pmb-theme', b.dataset.themeSet); } catch (e) {}
|
||||
syncTheme();
|
||||
}));
|
||||
syncTheme();
|
||||
let myName = '';
|
||||
fetch('/api/auth/me', { cache: 'no-store' }).then(r => (r.ok ? r.json() : null)).then(me => {
|
||||
if (me?.name) { myName = me.name; const who = document.getElementById('who'); if (!who.textContent.startsWith(myName)) who.textContent = `${myName} ${who.textContent}`; }
|
||||
}).catch(() => {});
|
||||
PMScope.mount(document.getElementById('content'), { mode: 'page', onMeta(data, error) {
|
||||
const prefix = myName ? `${myName} ` : '';
|
||||
if (!data) { document.getElementById('who').textContent = prefix + (error?.employeeNumber ? `工號 ${error.employeeNumber}` : ''); return; }
|
||||
document.getElementById('who').textContent = `${prefix}工號 ${data.me.employeeNumber} 權限來源:${data.me.sources.join(';') || '—'}`;
|
||||
document.getElementById('year').textContent = `${data.year} 年${data.anchor ? ` 目前 ${data.anchor.half} 定錨` : ' 尚未定錨'}`;
|
||||
} });
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
// 權限:誰能看哪個範圍。伺服器依權限只送出該看的數字,網頁只負責顯示。
|
||||
//
|
||||
// 來源有兩種:
|
||||
// - HR:部的主管(主要或次要)=看部門+看個人明細(含薪資)+部門模擬;組的主管=看組別。
|
||||
// HR 拿掉主管身分,這些權限就自動消失。
|
||||
// - 權限頁手動設定(COST_MODEL_DATA_DIR/permissions.json,新檔案):要手動拿掉。
|
||||
// 最高管理者(20150906)看得到全部,也是唯一能改核心參數、按定錨、刪資料、管理權限的人。
|
||||
import { bindFile } from './storage.js';
|
||||
import { splitOrganization } from './hr-org.js';
|
||||
|
||||
export const TOP_ADMIN = '20150906';
|
||||
|
||||
// 預設的手動設定(2026-11-04 決定)。權限頁可以改;存檔後以檔案為準。
|
||||
export const DEFAULT_GRANTS = Object.freeze({
|
||||
20120201: { company: true, note: '林家齊:全公司檢視(不能改核心參數)' },
|
||||
20150404: { company: true, note: '丘鳳怡:全公司檢視(不能改核心參數)' },
|
||||
});
|
||||
// 先不開放(待討論)。
|
||||
export const DEFAULT_DENIED = Object.freeze(['20240407']);
|
||||
|
||||
const text = (value) => (typeof value === 'string' ? value.trim() : '');
|
||||
const list = (value, max = 50) => (Array.isArray(value) ? [...new Set(value.map(text).filter(Boolean))].slice(0, max) : []);
|
||||
|
||||
export function normalizeGrant(input = {}) {
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new TypeError('grant must be an object');
|
||||
const grant = {
|
||||
company: input.company === true,
|
||||
depts: list(input.depts),
|
||||
groups: list(input.groups).filter(key => /^[^|]+\|[^|]+$/.test(key)),
|
||||
personDetail: input.personDetail === true,
|
||||
simulate: input.simulate === true,
|
||||
note: text(input.note).slice(0, 200),
|
||||
};
|
||||
return grant;
|
||||
}
|
||||
|
||||
// HR 主管單位 → 看板的部門/組。
|
||||
export function hrScopes(employeeNumber, supervisors, organizations) {
|
||||
const depts = new Set();
|
||||
const groups = new Set();
|
||||
for (const unit of supervisors.get(String(employeeNumber)) || []) {
|
||||
const place = splitOrganization({ departmentCode: unit.deptCode }, organizations);
|
||||
if (place.groupName && place.departmentName) groups.add(`${place.departmentName}|${place.groupName}`);
|
||||
else if (place.departmentName) depts.add(place.departmentName);
|
||||
}
|
||||
return { depts: [...depts], groups: [...groups] };
|
||||
}
|
||||
|
||||
// 把 HR 與手動設定合起來,得到這個人的權限。
|
||||
export function resolvePermissions(employeeNumber, { supervisors, organizations, store }) {
|
||||
const number = String(employeeNumber || '');
|
||||
if (number === TOP_ADMIN) {
|
||||
return { employeeNumber: number, admin: true, company: true, depts: [], groups: [], personDetail: true, simulate: true, sources: ['最高管理者'] };
|
||||
}
|
||||
if (store.denied.includes(number)) return { employeeNumber: number, admin: false, denied: true, company: false, depts: [], groups: [], personDetail: false, simulate: false, sources: ['暫不開放'] };
|
||||
const hr = hrScopes(number, supervisors, organizations);
|
||||
const manual = store.grants[number] || null;
|
||||
const sources = [];
|
||||
if (hr.depts.length) sources.push(`HR 部主管:${hr.depts.join('、')}`);
|
||||
if (hr.groups.length) sources.push(`HR 組主管:${hr.groups.map(g => g.split('|')[1]).join('、')}`);
|
||||
if (manual) sources.push(`手動:${manual.note || '權限頁設定'}`);
|
||||
return {
|
||||
employeeNumber: number,
|
||||
admin: false,
|
||||
company: Boolean(manual?.company),
|
||||
depts: [...new Set([...hr.depts, ...(manual?.depts || [])])],
|
||||
groups: [...new Set([...hr.groups, ...(manual?.groups || [])])],
|
||||
// 部主管預設可看個人明細與模擬;組主管要在權限頁勾。
|
||||
personDetail: hr.depts.length > 0 || Boolean(manual?.personDetail),
|
||||
simulate: hr.depts.length > 0 || Boolean(manual?.simulate),
|
||||
hr, manual, sources,
|
||||
};
|
||||
}
|
||||
|
||||
export function hasAnyScope(permission) {
|
||||
return Boolean(permission && !permission.denied && (permission.admin || permission.company || permission.depts.length || permission.groups.length));
|
||||
}
|
||||
|
||||
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 (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 || [] }
|
||||
: { grants: Object.fromEntries(Object.entries(DEFAULT_GRANTS).map(([k, v]) => [k, normalizeGrant(v)])), denied: [...DEFAULT_DENIED], log: [] };
|
||||
return state;
|
||||
}
|
||||
async function save() {
|
||||
if (!file) return;
|
||||
file.write(`${JSON.stringify(state)}\n`);
|
||||
}
|
||||
function serial(task) {
|
||||
const run = queue.then(task, task);
|
||||
queue = run.catch(() => {});
|
||||
return run;
|
||||
}
|
||||
return {
|
||||
load,
|
||||
// 手動設定:grant 為 null 時移除;denied 決定是否「暫不開放」。
|
||||
set: ({ employeeNumber, grant, denied, by }) => serial(async () => {
|
||||
await load();
|
||||
const number = text(String(employeeNumber || ''));
|
||||
if (!/^[A-Za-z0-9_-]{1,40}$/.test(number) || number === TOP_ADMIN) throw new RangeError('invalid employee');
|
||||
const before = { grant: state.grants[number] || null, denied: state.denied.includes(number) };
|
||||
if (grant === null) delete state.grants[number];
|
||||
else if (grant !== undefined) state.grants[number] = normalizeGrant(grant);
|
||||
if (denied === true && !state.denied.includes(number)) state.denied.push(number);
|
||||
if (denied === false) state.denied = state.denied.filter(n => n !== number);
|
||||
state.log.push({ employeeNumber: number, before, after: { grant: state.grants[number] || null, denied: state.denied.includes(number) }, by, at: new Date().toISOString() });
|
||||
if (state.log.length > 2000) state.log = state.log.slice(-2000);
|
||||
await save();
|
||||
return { ok: true };
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
},
|
||||
};
|
||||
}
|
||||
+445
@@ -0,0 +1,445 @@
|
||||
// 依權限的檢視與部門模擬試算(共用元件)。/my 單頁和主看板的「模擬試算」都用這一份。
|
||||
// 數字都由伺服器算(/api/scope、/api/simulate),這裡只負責顯示。
|
||||
// 顏色用 --sx-* 變數,放進主看板時由主看板換成自己的配色。
|
||||
(function () {
|
||||
// 金額依右上角的幣別顯示(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`;
|
||||
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const KINDS = [['A', 'A 藝術家'], ['P', 'P 製作'], ['O', 'O 外包'], ['intern', '實習生'], ['parttime', '工讀(算 O)']];
|
||||
const KIND_LABEL = Object.fromEntries(KINDS);
|
||||
const PAY_LABEL = { monthly: '月薪', daily: '日薪', hourly: '時薪' };
|
||||
const MONTH_FIELDS = ['amount', 'h1Start', 'h1End', 'h2Start', 'h2End'];
|
||||
const HEADCOUNT_LABELS = [['A', 'A'], ['P', 'P'], ['G', 'G 管理'], ['O', '外包'], ['intern', '實習'], ['parttime', '工讀'], ['other', '待分類']];
|
||||
const DISCLAIMER = '本試算只用來快速估算加人、調薪後大約的 CODA 與發票量,結果只代表試算當下的狀態。實際數字會隨人員與參數變動,正式數字一律以每年 1 月、7 月定錨後統一公布的為準。';
|
||||
|
||||
const CSS = `
|
||||
.sx { --sx-card-bg: var(--sx-card, #ffffff); color: var(--sx-text, #1f2328); }
|
||||
.sx .sx-sub { color: var(--sx-muted, #5f6670); font-size: .85rem; }
|
||||
.sx .sx-card { background: var(--sx-card-bg); border: 1px solid var(--sx-line, #e4e0d8); border-radius: 14px; padding: 18px; margin-bottom: 16px; }
|
||||
.sx h2 { margin: 0 0 4px; font-size: 1.05rem; }
|
||||
.sx h3 { margin: 0 0 6px; font-size: .95rem; }
|
||||
.sx h4 { margin: 14px 0 6px; font-size: .85rem; color: var(--sx-muted, #5f6670); font-weight: 500; }
|
||||
.sx .sx-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; margin: 12px 0; }
|
||||
.sx .sx-kpi { border: 1px solid var(--sx-line, #e4e0d8); border-radius: 10px; padding: 10px 12px; }
|
||||
.sx .sx-kpi .label { color: var(--sx-muted, #5f6670); font-size: .78rem; }
|
||||
.sx .sx-kpi .value { font-size: 1.15rem; font-weight: 600; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.sx .sx-kpi .note { color: var(--sx-muted, #5f6670); font-size: .75rem; font-weight: 400; }
|
||||
.sx table { width: 100%; border-collapse: collapse; font-size: .88rem; }
|
||||
.sx th, .sx td { padding: 8px 6px; border-bottom: 1px solid var(--sx-line, #e4e0d8); text-align: left; vertical-align: top; }
|
||||
.sx th { color: var(--sx-muted, #5f6670); font-weight: 500; font-size: .8rem; }
|
||||
.sx td.num, .sx th.num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.sx .sx-scroll { overflow-x: auto; }
|
||||
.sx .sx-tag { display: inline-block; font-size: .72rem; padding: 1px 8px; border-radius: 99px; border: 1px solid var(--sx-line, #e4e0d8); color: var(--sx-muted, #5f6670); margin-left: 6px; }
|
||||
.sx .sx-warn { color: var(--sx-warn, #b4540a); }
|
||||
.sx .up { color: var(--sx-up, #2f5fd0); }
|
||||
.sx .down { color: var(--sx-down, #b4540a); }
|
||||
.sx button { font: inherit; border: 1px solid var(--sx-line, #e4e0d8); background: var(--sx-card-bg); color: inherit; border-radius: 8px; padding: 4px 10px; cursor: pointer; }
|
||||
.sx button.sx-primary { background: var(--sx-accent, #4f6bed); border-color: var(--sx-accent, #4f6bed); color: var(--sx-on-accent, #fff); }
|
||||
.sx button:focus-visible, .sx select:focus-visible, .sx input:focus-visible { outline: 2px solid var(--sx-accent, #4f6bed); outline-offset: 2px; }
|
||||
.sx details summary { cursor: pointer; color: var(--sx-accent, #4f6bed); margin-top: 8px; }
|
||||
.sx .sx-mask { letter-spacing: 2px; color: var(--sx-muted, #5f6670); }
|
||||
.sx .sx-val { display: none; }
|
||||
.sx.show-salary .sx-val { display: inline; }
|
||||
.sx.show-salary .sx-sal .sx-mask { display: none; }
|
||||
.sx th.sal, .sx td.sal { width: 11em; min-width: 11em; }
|
||||
.sx .sx-block { border-radius: 14px; padding: 14px 16px; margin: 12px 0; background: var(--sx-tint, transparent); border: 1px solid var(--sx-tint-border, transparent); }
|
||||
.sx .sx-bh { display: flex; align-items: center; gap: 8px; font-weight: 600; font-size: .92rem; margin-bottom: 4px; }
|
||||
.sx .sx-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--sx-dot, var(--sx-muted, #5f6670)); flex: none; }
|
||||
.sx .b-coda { --sx-tint: var(--sx-tint-coda, #eef3f8); --sx-tint-border: var(--sx-tint-coda-border, #d6e1ec); --sx-dot: var(--sx-dot-coda, #5b7f98); }
|
||||
.sx .b-inv { --sx-tint: var(--sx-tint-inv, #fbf4ea); --sx-tint-border: var(--sx-tint-inv-border, #ecd9bf); --sx-dot: var(--sx-dot-inv, #b5722a); }
|
||||
.sx .b-inv2 { --sx-tint: var(--sx-tint-inv2, #fdf9f3); --sx-tint-border: var(--sx-tint-inv-border, #ecd9bf); --sx-dot: var(--sx-dot-inv, #b5722a); }
|
||||
.sx .b-people { --sx-tint: transparent; --sx-tint-border: var(--sx-line, #e4e0d8); --sx-dot: var(--sx-muted, #5f6670); }
|
||||
.sx .b-group { --sx-tint: var(--sx-tint-group, #f0f3ef); --sx-tint-border: var(--sx-tint-group-border, #d9e1d4); --sx-dot: var(--sx-dot-group, #6f8463); }
|
||||
.sx .b-sim { --sx-tint: var(--sx-tint-sim, rgba(0,0,0,.035)); --sx-tint-border: var(--sx-line, #e4e0d8); --sx-dot: var(--sx-sim-bar, #9bb32a); border-left: 4px solid var(--sx-sim-bar, #c7dc4a); }
|
||||
.sx .sx-block .sx-kpis { margin: 8px 0 2px; }
|
||||
.sx .sx-block .sx-kpi { background: var(--sx-kpi-bg, rgba(255,255,255,.6)); border-color: var(--sx-tint-border, var(--sx-line, #e4e0d8)); }
|
||||
.sx .sx-block table th, .sx .sx-block table td { border-bottom-color: var(--sx-tint-border, var(--sx-line, #e4e0d8)); }
|
||||
.sx .sx-step { border-radius: 10px; padding: 10px 12px; margin: 8px 0; }
|
||||
.sx .sx-step h4 { margin: 0 0 6px; }
|
||||
.sx .sx-step.strong { background: var(--sx-strong, rgba(0,0,0,.04)); }
|
||||
.sx select, .sx input { font: inherit; padding: 3px 6px; border: 1px solid var(--sx-line, #e4e0d8); border-radius: 6px; background: var(--sx-input, #f6f4ef); color: inherit; }
|
||||
.sx .sx-sim input[type=number] { width: 110px; }
|
||||
.sx .sx-sim input.m[type=number] { width: 58px; }
|
||||
.sx .sx-sim input.sx-changed { border-color: var(--sx-accent, #4f6bed); box-shadow: 0 0 0 2px color-mix(in srgb, var(--sx-accent, #4f6bed) 25%, transparent); }
|
||||
.sx tr.sx-changed td { background: color-mix(in srgb, var(--sx-accent, #4f6bed) 8%, transparent); }
|
||||
.sx .sx-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin: 8px 0; }
|
||||
.sx .sx-count { font-size: .8rem; color: var(--sx-muted, #5f6670); }
|
||||
.sx .sx-pick { display: flex; gap: 6px; flex-wrap: wrap; margin: 4px 0 16px; }
|
||||
.sx .sx-pick button[aria-pressed="true"] { background: var(--sx-accent, #4f6bed); border-color: var(--sx-accent, #4f6bed); color: var(--sx-on-accent, #fff); }
|
||||
.sx .sx-stale { border: 1px solid var(--sx-warn, #b4540a); color: var(--sx-warn, #b4540a); border-radius: 10px; padding: 8px 12px; margin: 10px 0; font-size: .85rem; }
|
||||
.sx .sx-result { border: 1px solid var(--sx-line, #e4e0d8); border-radius: 12px; padding: 6px 8px 10px; margin: 12px 0; background: var(--sx-card-bg); }
|
||||
.sx .sx-result.is-stale { opacity: .55; }
|
||||
.sx .sx-did { margin: 0 0 4px; padding-left: 1.2em; font-size: .88rem; }
|
||||
.sx .sx-did li { margin: 2px 0; }
|
||||
.sx .sx-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 10px; }
|
||||
.sx .sx-change { border: 1px solid var(--sx-line, #e4e0d8); border-radius: 10px; padding: 10px 12px; background: var(--sx-card-bg); }
|
||||
.sx .sx-change .label { color: var(--sx-muted, #5f6670); font-size: .78rem; }
|
||||
.sx .sx-change .ba { font-variant-numeric: tabular-nums; font-size: .88rem; margin: 2px 0; }
|
||||
.sx .sx-change .ba span { white-space: nowrap; }
|
||||
.sx .sx-change .ba b { white-space: nowrap; font-weight: 600; }
|
||||
.sx .sx-change .say { font-weight: 600; font-size: .9rem; }
|
||||
.sx .sx-change .say.same { font-weight: 400; color: var(--sx-muted, #5f6670); }
|
||||
.sx .sx-where { display: grid; grid-template-columns: minmax(90px, 1fr) 2fr auto; gap: 6px 10px; align-items: center; font-size: .86rem; }
|
||||
.sx .sx-bar { height: 8px; border-radius: 99px; background: var(--sx-line, #e4e0d8); overflow: hidden; }
|
||||
.sx .sx-bar span { display: block; height: 100%; border-radius: 99px; background: var(--sx-up, #2f5fd0); }
|
||||
.sx .sx-bar span.down { background: var(--sx-down, #b4540a); }
|
||||
.sx .sx-fine { font-size: .74rem; line-height: 1.5; color: var(--sx-muted, #5f6670); margin-top: 12px; padding-top: 8px; border-top: 1px solid var(--sx-line, #e4e0d8); }
|
||||
.sx .sx-ind td small { display: block; color: var(--sx-muted, #5f6670); font-size: .74rem; }
|
||||
`;
|
||||
|
||||
function injectStyle() {
|
||||
if (document.getElementById('sx-style')) return;
|
||||
const style = document.createElement('style');
|
||||
style.id = 'sx-style';
|
||||
style.textContent = CSS;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
// mount(root, { mode, onMeta })
|
||||
// mode 'page':/my 單頁,全部部門依序列出。
|
||||
// mode 'simulate':主看板,一次看一個部門,模擬區直接展開。
|
||||
function mount(root, { mode = 'page', onMeta } = {}) {
|
||||
injectStyle();
|
||||
root.classList.add('sx');
|
||||
const state = { data: null, salaryShown: false, sim: {}, dept: null, loading: false, open: {} };
|
||||
const isOpen = (key, fallback) => (key in state.open ? state.open[key] : fallback);
|
||||
|
||||
const emptySim = () => ({ additions: [], raises: {}, result: null, ran: null, stale: false, error: '' });
|
||||
const simFor = dept => state.sim[dept] || (state.sim[dept] = emptySim());
|
||||
const anchorText = a => !a ? '<span class="sx-sub">尚未定錨</span>'
|
||||
: `${money(a.annual)}<div class="note">H1 ${money(a.h1)}${a.h2 === null ? '' : ' H2 ' + money(a.h2)}</div>`;
|
||||
// 薪資:遮住和顯示兩種都先放好,切換時只換 CSS class,不重畫(畫面不會跳)。
|
||||
const salaryCell = text => `<span class="sx-sal"><span class="sx-mask">••••</span><span class="sx-val">${text}</span></span>`;
|
||||
const salaryButton = (labelShow, labelHide) => `<button type="button" data-act="salary" data-show="${labelShow}" data-hide="${labelHide}" aria-pressed="${state.salaryShown}">${state.salaryShown ? labelHide : labelShow}</button>`;
|
||||
const monthsText = m => [m.h1Start && `${m.h1Start}–${m.h1End}`, m.h2Start && `${m.h2Start}–${m.h2End}`].filter(Boolean).join('、') || '—';
|
||||
|
||||
function peopleTable(people) {
|
||||
const salary = p => p.dayrate !== null && p.dayrate !== undefined ? '日 ' + money(p.dayrate) : (p.salaryType === 'hourly' ? '時 ' : '') + money(p.salary);
|
||||
return `<div class="sx-scroll"><table><thead><tr><th>組</th><th>姓名</th><th>職稱</th><th>職能</th><th>在職月份</th><th class="num sal">薪資</th><th class="num sal">年度成本</th></tr></thead><tbody>
|
||||
${people.map(p => `<tr><td>${esc(p.group)}</td><td>${esc(p.name)}${p.isManager ? '<span class="sx-tag">主管</span>' : ''}${p.partTime ? '<span class="sx-tag">工讀</span>' : ''}${p.intern ? '<span class="sx-tag">實習</span>' : ''}${p.issue ? `<div class="sx-sub sx-warn">${esc(p.issue)}</div>` : ''}</td><td>${esc(p.title)}</td><td>${esc((p.role || '').split(' - ')[0] || '待分類')}</td>
|
||||
<td>${monthsText(p.months)} 月</td>
|
||||
<td class="num sal">${salaryCell(salary(p))}</td><td class="num sal">${salaryCell(money(p.cost || p.invoiceCost))}</td></tr>`).join('')}
|
||||
</tbody></table></div>`;
|
||||
}
|
||||
|
||||
// --- 部門的數字:倍率、發票佔比、三個指標、人數、總人力成本 ---
|
||||
function headcountText(h) {
|
||||
return HEADCOUNT_LABELS.filter(([k]) => h[k]).map(([k, l]) => `${l} ${h[k]}`).join('・') || '—';
|
||||
}
|
||||
|
||||
function invoiceKpi(d) {
|
||||
if (!d.invoice) return '<div class="sx-kpi"><div class="label">年度發票目標</div><div class="value">—</div><div class="note">這個部門不分配發票</div></div>';
|
||||
const a = d.anchoredInvoice;
|
||||
const halves = a
|
||||
? `定錨:上半年 ${money(a.h1)}${a.h2 === null ? '' : `/下半年 ${money(a.h2)}`}`
|
||||
: `上半年 ${money(d.invoice.h1)}/下半年 ${money(d.invoice.h2)}(定錨前預估)`;
|
||||
return `<div class="sx-kpi"><div class="label">年度發票目標</div><div class="value">${money(d.invoice.annual)}</div>
|
||||
<div class="note">佔全公司 ${pct(d.invoice.share)}</div><div class="note">${halves}</div>${a ? `<div class="note">定錨後全年:${money(a.annual)}</div>` : ''}</div>`;
|
||||
}
|
||||
|
||||
function indicatorsBlock(d) {
|
||||
const ind = d.invoice?.indicators;
|
||||
if (!ind) return '';
|
||||
const rows = [
|
||||
['指標 1 P 佔比', ind.p, '你部門 P 的成本,佔四個出發票部門 P 成本總和的比例。'],
|
||||
['指標 2 A 佔比', ind.a, '你部門 A 的成本,佔四個出發票部門 A 成本總和的比例。'],
|
||||
['指標 3 P 輕重', ind.s, 'P 成本 ×(P 成本 ÷ A 成本,A 含常態型外包),再換算成佔比。P 相對 A 越重,分得越多。'],
|
||||
];
|
||||
return `<div class="sx-sub">發票佔比 = 三個指標各自乘上權重後加總。下面是你部門的三個指標:</div>
|
||||
<div class="sx-scroll"><table class="sx-ind"><thead><tr><th>指標</th><th class="num">你部門</th><th class="num">權重</th><th class="num">貢獻</th></tr></thead><tbody>
|
||||
${rows.map(([name, v, hint]) => `<tr><td>${name}<small>${hint}</small></td><td class="num">${pct(v.value)}</td><td class="num">${pct(v.weight, 0)}</td><td class="num">${pct(v.value * v.weight, 2)}</td></tr>`).join('')}
|
||||
<tr><td><b>發票佔比</b></td><td></td><td></td><td class="num"><b>${pct(d.invoice.share, 2)}</b></td></tr>
|
||||
</tbody></table></div>
|
||||
<div class="sx-sub" style="margin-top:6px;">A:P 成本比(A 含外包 ÷ P):你部門 <b>${ratio(ind.apRatio)}</b>,四個部門整體 ${ratio(ind.overallApRatio)}。數字越大,代表每 1 元 P 成本對應的 A 越多。</div>`;
|
||||
}
|
||||
|
||||
// 區塊:沿用主看板的底色(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>` :
|
||||
`<tr><td>${esc(g.group)}</td><td class="num">${g.headcount} 人</td><td class="num">${money(g.actualCoda)}</td><td class="num">${money(g.avgDailyCoda)}</td><td class="num">${anchorText(g.anchoredCoda)}</td>${showCost ? `<td class="num">${money(g.totalCost)}</td>` : ''}</tr>`).join('');
|
||||
const kpi = (label, value, ...notes) => `<div class="sx-kpi"><div class="label">${label}</div><div class="value">${value}</div>${notes.filter(Boolean).map(n => `<div class="note">${n}</div>`).join('')}</div>`;
|
||||
const full = d.full ? `
|
||||
${block('coda', 'CODA', `<div class="sx-kpis">
|
||||
${kpi('實際 CODA(部門)', money(d.actualCoda))}
|
||||
${kpi('平均日 CODA(部門)', money(d.avgDailyCoda))}
|
||||
<div class="sx-kpi"><div class="label">定錨 CODA(部門=各組加總)</div><div class="value">${anchorText(d.anchoredCoda)}</div></div>
|
||||
</div>`)}
|
||||
${block('inv', '發票與倍率', `<div class="sx-kpis">
|
||||
${invoiceKpi(d)}
|
||||
${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), '正職年薪 × 人薪倍率 + 外包 × 外包倍率,不含實習生') : ''}
|
||||
</div>`)}` : '';
|
||||
return `<section class="sx-card">
|
||||
<h2>${esc(d.dept)}${d.full ? '' : '<span class="sx-tag">只看組別</span>'}</h2>
|
||||
${full}
|
||||
${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>${peopleTable(d.people)}</details>` : ''}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
// --- 模擬試算 ---
|
||||
const ROW_LABELS = { actualCoda: '實際 CODA(部門)', avgDailyCoda: '平均日 CODA(部門)', anchoredCoda: '定錨 CODA(部門)', invoice: '年度發票目標', anchoredInvoice: '定錨後發票', multiplier: '部門倍率', invoiceShare: '發票佔比' };
|
||||
const ROW_ORDER = ['actualCoda', 'avgDailyCoda', 'anchoredCoda', 'invoice', 'invoiceShare', 'anchoredInvoice', 'multiplier'];
|
||||
|
||||
function changeCard(r, anchored) {
|
||||
const label = ROW_LABELS[r.key];
|
||||
if (r.before === null && r.after === null) {
|
||||
if (r.key.startsWith('anchored') && !anchored) return `<div class="sx-change"><div class="label">${label}</div><div class="say same">尚未定錨,定錨後才有</div></div>`;
|
||||
return '';
|
||||
}
|
||||
const fmt = r.key === 'multiplier' ? times : r.key === 'invoiceShare' ? v => pct(v, 2) : money;
|
||||
const delta = r.delta ?? 0;
|
||||
const tiny = r.key === 'invoiceShare' ? Math.abs(delta) < 0.00005 : r.key === 'multiplier' ? Math.abs(delta) < 0.005 : Math.abs(delta) < 1;
|
||||
let say;
|
||||
if (tiny) say = '<div class="say same">不變</div>';
|
||||
else {
|
||||
const cls = delta > 0 ? 'up' : 'down';
|
||||
const word = delta > 0 ? '▲ 增加' : '▼ 減少';
|
||||
const amount = r.key === 'multiplier' ? Math.abs(delta).toFixed(2)
|
||||
: r.key === 'invoiceShare' ? `${Math.abs(delta * 100).toFixed(2)} 個百分點`
|
||||
: 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>`;
|
||||
}
|
||||
return `<div class="sx-change"><div class="label">${label}</div><div class="ba"><span>${fmt(r.before)}</span> → <b>${fmt(r.after)}</b></div>${say}</div>`;
|
||||
}
|
||||
|
||||
function didList(d, ran) {
|
||||
const people = new Map((d.people || []).map(p => [p.employeeNumber, p]));
|
||||
const items = [];
|
||||
ran.additions.forEach(a => {
|
||||
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' ? '時薪 ' : ''}NT$ ${num(amount)}${diff}`);
|
||||
});
|
||||
return items.length ? `<ul class="sx-did">${items.map(i => `<li>${i}</li>`).join('')}</ul>` : '<div class="sx-sub">沒有調整任何東西(目前的數字)。</div>';
|
||||
}
|
||||
|
||||
function whereBlock(d, st) {
|
||||
const ran = st.ran;
|
||||
const added = {};
|
||||
ran.additions.forEach(a => { const g = a.group || '未分組'; added[g] = (added[g] || 0) + 1; });
|
||||
const raisedIn = {};
|
||||
Object.keys(ran.raises).forEach(id => { const g = (d.people || []).find(p => p.employeeNumber === id)?.group || '未分組'; raisedIn[g] = (raisedIn[g] || 0) + 1; });
|
||||
// 加的人或調薪的人不在算 CODA 的組裡(例如 P),也列出來,標「不算 CODA」。
|
||||
const known = new Set(st.result.groups.map(g => g.group));
|
||||
const extra = [...new Set([...Object.keys(added), ...Object.keys(raisedIn)])].filter(g => !known.has(g))
|
||||
.map(group => ({ group, before: { actualCoda: 0, headcount: 0 }, after: { actualCoda: 0, headcount: 0 }, noCoda: true }));
|
||||
const groups = [...st.result.groups, ...extra].map(g => ({ ...g, delta: g.after.actualCoda - g.before.actualCoda, people: (g.after.headcount || 0) - (g.before.headcount || 0) }))
|
||||
.filter(g => g.delta !== 0 || g.people !== 0 || added[g.group] || raisedIn[g.group])
|
||||
.sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta));
|
||||
if (!groups.length) return '<div class="sx-sub">各組的實際 CODA 都沒有變。</div>';
|
||||
const max = Math.max(...groups.map(g => Math.abs(g.delta)), 1);
|
||||
return `<div class="sx-where">${groups.map(g => {
|
||||
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 ? '+' : '−'}${amtv(Math.abs(g.delta))}`}</div>`;
|
||||
}).join('')}</div>
|
||||
<div class="sx-sub" style="margin-top:4px;">實際 CODA 的變化,變最多的排最上面。</div>`;
|
||||
}
|
||||
|
||||
function resultBlock(d, st) {
|
||||
if (!st.result) return '';
|
||||
const rows = ROW_ORDER.map(key => st.result.rows.find(r => r.key === key)).filter(Boolean);
|
||||
const cards = rows.map(r => changeCard(r, st.result.anchored)).join('');
|
||||
const share = rows.find(r => r.key === 'invoiceShare');
|
||||
const invoiceNote = !share || share.delta === null || Math.abs(share.delta) < 0.00005 ? ''
|
||||
: `發票是全公司一起分的:你部門${share.delta > 0 ? '變多,其他部門會相對變少' : '變少,其他部門會相對變多'}。`;
|
||||
return `${st.stale ? '<div class="sx-stale" role="status">內容已改,請重新試算。下面是上一次試算的結果。</div>' : ''}
|
||||
<div class="sx-result${st.stale ? ' is-stale' : ''}">
|
||||
<div class="sx-step"><h4>① 你這次試算了什麼</h4>${didList(d, st.ran)}</div>
|
||||
<div class="sx-step strong"><h4>② 結果:現在 → 試算後</h4><div class="sx-cards">${cards}</div>
|
||||
${invoiceNote ? `<div class="sx-sub" style="margin-top:8px;">${invoiceNote}</div>` : ''}</div>
|
||||
<div class="sx-step"><h4>③ 影響在哪一組</h4>${whereBlock(d, st)}</div>
|
||||
<div class="sx-fine">※ ${DISCLAIMER}</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function simSection(d, open) {
|
||||
const st = simFor(d.dept);
|
||||
const groupOpts = sel => ['<option value="">未分組</option>', ...d.groups.map(g => `<option ${g.group === sel ? 'selected' : ''}>${esc(g.group)}</option>`)].join('');
|
||||
const addRows = st.additions.map((a, i) => `<tr class="sx-changed">
|
||||
<td><select data-sim="set" data-i="${i}" data-field="kind" aria-label="職能">${KINDS.map(([v, l]) => `<option value="${v}" ${a.kind === v ? 'selected' : ''}>${l}</option>`).join('')}</select></td>
|
||||
<td><select data-sim="set" data-i="${i}" data-field="group" aria-label="組">${groupOpts(a.group)}</select></td>
|
||||
<td><select data-sim="set" data-i="${i}" data-field="salaryType" aria-label="薪資類型">${[['monthly', '月薪'], ['daily', '日薪'], ['hourly', '時薪']].map(([v, l]) => `<option value="${v}" ${a.salaryType === v ? 'selected' : ''}>${l}</option>`).join('')}</select>
|
||||
<input type="number" min="0" value="${a.amount}" data-sim="set" data-i="${i}" data-field="amount" aria-label="金額"></td>
|
||||
<td>H1 <input class="m" type="number" min="1" max="6" value="${a.h1Start}" data-sim="set" data-i="${i}" data-field="h1Start" aria-label="H1 起">–<input class="m" type="number" min="1" max="6" value="${a.h1End}" data-sim="set" data-i="${i}" data-field="h1End" aria-label="H1 迄">
|
||||
H2 <input class="m" type="number" min="7" max="12" value="${a.h2Start}" data-sim="set" data-i="${i}" data-field="h2Start" aria-label="H2 起">–<input class="m" type="number" min="7" max="12" value="${a.h2End}" data-sim="set" data-i="${i}" data-field="h2End" aria-label="H2 迄"></td>
|
||||
<td><button type="button" data-act="remove" data-i="${i}">移除</button></td></tr>`).join('');
|
||||
const raisable = (d.people || []).filter(p => p.employeeNumber && !String(p.role).startsWith('O'));
|
||||
const raiseRows = raisable.length ? `<details data-key="raise|${esc(d.dept)}" ${isOpen(`raise|${d.dept}`, open) ? 'open' : ''}><summary>模擬調薪(${raisable.length} 人可調)</summary>
|
||||
${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' ? '時 ' : '') + '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;
|
||||
const counts = [raiseCount ? `已調整 ${raiseCount} 人` : '', st.additions.length ? `加 ${st.additions.length} 人` : ''].filter(Boolean).join('、');
|
||||
const dirty = st.result || st.additions.length || raiseCount;
|
||||
return `<div class="sx-block b-sim sx-sim" data-dept="${esc(d.dept)}"><div class="sx-bh"><span class="sx-dot"></span>模擬試算(不會存檔)</div>
|
||||
<div class="sx-sub">在本部門加人或調薪,看看實際 CODA、平均日 CODA、定錨 CODA、發票、倍率會變多少。工讀算 O:日薪=時薪×8。實習生只進發票、不算 CODA。</div>
|
||||
${st.additions.length ? `<div class="sx-scroll"><table><thead><tr><th>職能</th><th>組</th><th>薪資</th><th>在職月份</th><th></th></tr></thead><tbody>${addRows}</tbody></table></div>` : ''}
|
||||
<div class="sx-row"><button type="button" data-act="add">+ 加一個人</button><button type="button" class="sx-primary" data-act="run">試算</button>${dirty ? '<button type="button" data-act="reset">清除</button>' : ''}<span class="sx-count" data-count>${counts}</span></div>
|
||||
${st.error ? `<div class="sx-warn" role="alert">${esc(st.error)}</div>` : ''}${resultBlock(d, st)}
|
||||
${raiseRows}</div>`;
|
||||
}
|
||||
|
||||
function render() {
|
||||
const data = state.data;
|
||||
if (onMeta) onMeta(data);
|
||||
if (mode === 'simulate') {
|
||||
const depts = data.depts.filter(d => d.full && data.me.simulate);
|
||||
if (!depts.length) { root.innerHTML = '<div class="sx-card">你目前沒有可以模擬的部門。</div>'; return; }
|
||||
if (!depts.some(d => d.dept === state.dept)) state.dept = depts[0].dept;
|
||||
const pick = `<div class="sx-pick" role="group" aria-label="選擇部門">${depts.map(d => `<button type="button" data-act="dept" data-dept="${esc(d.dept)}" aria-pressed="${d.dept === state.dept}">${esc(d.dept)}</button>`).join('')}</div>`;
|
||||
root.innerHTML = pick + deptCard(depts.find(d => d.dept === state.dept), data, true);
|
||||
return;
|
||||
}
|
||||
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('');
|
||||
}
|
||||
|
||||
// 重畫時保留展開狀態(直接畫成展開,不會先收起再打開)與捲動位置,畫面不會跳。
|
||||
function scrollers() {
|
||||
const list = [];
|
||||
for (let el = root.parentElement; el; el = el.parentElement) if (el.scrollHeight > el.clientHeight && /(auto|scroll)/.test(getComputedStyle(el).overflowY)) list.push([el, el.scrollTop]);
|
||||
return list;
|
||||
}
|
||||
function rerender() {
|
||||
const saved = scrollers();
|
||||
const y = window.scrollY;
|
||||
root.style.minHeight = `${root.offsetHeight}px`;
|
||||
render();
|
||||
root.classList.toggle('show-salary', state.salaryShown);
|
||||
saved.forEach(([el, top]) => { el.scrollTop = top; });
|
||||
window.scrollTo({ top: y, behavior: 'instant' });
|
||||
root.style.minHeight = '';
|
||||
}
|
||||
root.addEventListener('toggle', event => {
|
||||
const key = event.target?.dataset?.key;
|
||||
if (key) state.open[key] = event.target.open;
|
||||
}, true);
|
||||
|
||||
const deptOf = el => el.closest('[data-dept]')?.getAttribute('data-dept');
|
||||
const markStale = st => { if (st.result) st.stale = true; };
|
||||
|
||||
root.addEventListener('click', async event => {
|
||||
const button = event.target.closest('button[data-act]');
|
||||
if (!button || !root.contains(button)) return;
|
||||
const act = button.dataset.act;
|
||||
if (act === 'salary') {
|
||||
state.salaryShown = !state.salaryShown;
|
||||
root.classList.toggle('show-salary', state.salaryShown);
|
||||
root.querySelectorAll('button[data-act="salary"]').forEach(b => { b.textContent = state.salaryShown ? b.dataset.hide : b.dataset.show; b.setAttribute('aria-pressed', String(state.salaryShown)); });
|
||||
return;
|
||||
}
|
||||
if (act === 'dept') { state.dept = button.dataset.dept; render(); return; }
|
||||
const dept = deptOf(button);
|
||||
const st = simFor(dept);
|
||||
if (act === 'add') { st.additions.push({ kind: 'A', group: '', salaryType: 'monthly', amount: 45000, h1Start: 1, h1End: 6, h2Start: 7, h2End: 12 }); markStale(st); }
|
||||
if (act === 'remove') { st.additions.splice(Number(button.dataset.i), 1); markStale(st); }
|
||||
if (act === 'reset') state.sim[dept] = emptySim();
|
||||
if (act === 'run') {
|
||||
button.disabled = true;
|
||||
const ran = { additions: st.additions.map(a => ({ ...a })), raises: { ...st.raises } };
|
||||
const response = await fetch('/api/simulate' + location.search, { method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ dept, additions: ran.additions, raises: Object.entries(ran.raises).map(([employeeNumber, amount]) => ({ employeeNumber, amount })) }) });
|
||||
const body = await response.json().catch(() => ({}));
|
||||
st.result = response.ok ? body : null;
|
||||
st.ran = response.ok ? ran : null;
|
||||
st.stale = false;
|
||||
st.error = response.ok ? '' : `試算失敗:${body.error || response.status}(請檢查在職月份與金額)`;
|
||||
}
|
||||
rerender();
|
||||
});
|
||||
|
||||
root.addEventListener('change', event => {
|
||||
const el = event.target.closest('[data-sim]');
|
||||
if (!el) return;
|
||||
const st = simFor(deptOf(el));
|
||||
if (el.dataset.sim === 'raise') {
|
||||
if (el.value === '') delete st.raises[el.dataset.id]; else st.raises[el.dataset.id] = Number(el.value);
|
||||
el.classList.toggle('sx-changed', el.value !== '');
|
||||
el.closest('tr')?.classList.toggle('sx-changed', el.value !== '');
|
||||
} else {
|
||||
const field = el.dataset.field;
|
||||
st.additions[Number(el.dataset.i)][field] = MONTH_FIELDS.includes(field) ? (el.value === '' ? '' : Number(el.value)) : el.value;
|
||||
}
|
||||
// 只更新提示,不整個重畫(避免打字到一半跳掉)。
|
||||
const wasStale = st.stale;
|
||||
markStale(st);
|
||||
const sim = el.closest('.sx-sim');
|
||||
const count = sim?.querySelector('[data-count]');
|
||||
const raiseCount = Object.keys(st.raises).length;
|
||||
if (count) count.textContent = [raiseCount ? `已調整 ${raiseCount} 人` : '', st.additions.length ? `加 ${st.additions.length} 人` : ''].filter(Boolean).join('、');
|
||||
if (st.stale && !wasStale) {
|
||||
const result = sim?.querySelector('.sx-result');
|
||||
if (result) {
|
||||
result.classList.add('is-stale');
|
||||
result.insertAdjacentHTML('beforebegin', '<div class="sx-stale" role="status">內容已改,請重新試算。下面是上一次試算的結果。</div>');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
async function load() {
|
||||
if (state.loading) return;
|
||||
state.loading = true;
|
||||
if (!state.data) root.innerHTML = '<div class="sx-sub">讀取中…</div>';
|
||||
try {
|
||||
const response = await fetch('/api/scope' + location.search, { cache: 'no-store' });
|
||||
if (response.status === 401) { location.href = '/api/auth/login'; return; }
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
if (onMeta) onMeta(null, data);
|
||||
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 {
|
||||
state.loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
load();
|
||||
return { reload: load };
|
||||
}
|
||||
|
||||
window.PMScope = { mount };
|
||||
})();
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
// 依權限從伺服器算好的模型裁出「這個人可以看的數字」。看不到的部門、組、個人薪資一律不送出。
|
||||
const round = (value) => Math.round(Number(value) || 0);
|
||||
|
||||
function personRow(p) {
|
||||
const isO = String(p.role || '').startsWith('O');
|
||||
return {
|
||||
employeeNumber: p.source === 'hr-sync' ? String(p.employeeNumber || '') : null,
|
||||
name: p.name || '', title: p.title || '', role: p.role || '', group: p.group || '未分組',
|
||||
months: { h1Start: p.h1Start || '', h1End: p.h1End || '', h2Start: p.h2Start || '', h2End: p.h2End || '' },
|
||||
salaryType: p.salaryType || '',
|
||||
salary: isO ? null : round(p.salaryType === 'hourly' ? p.hourlyRate : p.salary),
|
||||
dayrate: isO ? round(p.dayrate) : null,
|
||||
annualSalary: round(p.realSalaryTotal),
|
||||
cost: round(p.totalCost),
|
||||
invoiceCost: round(p.invoiceCost),
|
||||
partTime: Boolean(p.partTime),
|
||||
intern: Boolean(p.invoiceCost),
|
||||
isManager: Boolean(p.isManager),
|
||||
issue: p.calculationIssue || '',
|
||||
};
|
||||
}
|
||||
|
||||
// 部門倍率(和主看板一樣):夢境現實整間公司一個倍率,其他部門各自一個;已乘人薪倍率。沒有 A 成本就是 null。
|
||||
export function multiplierFor(model, dept) {
|
||||
const units = model.multiplierUnits || [];
|
||||
const company = model.deptCompany?.[dept];
|
||||
const own = units.find(u => !u.company && u.label === dept);
|
||||
const unit = own || units.find(u => u.company && u.label === company);
|
||||
if (!unit || !Number.isFinite(unit.multiplier)) return null;
|
||||
return { value: Math.round(unit.multiplier * (model.opMultiplier || 2) * 100) / 100, company: unit.company ? unit.label : null };
|
||||
}
|
||||
|
||||
// 發票佔比與三個指標(只有出發票的部門有)。
|
||||
export function invoiceBreakdown(model, dept) {
|
||||
const alloc = model.allocations?.deptData?.[dept];
|
||||
if (!alloc) return null;
|
||||
const annual = (model.invoice?.finalInvoiceTotal || 0) * (alloc.finalPct || 0);
|
||||
const ratio = v => (Number.isFinite(v) ? Math.round(v * 100) / 100 : null);
|
||||
return {
|
||||
annual: round(annual), share: alloc.finalPct || 0, h1: round(annual / 2), h2: round(annual - round(annual / 2)),
|
||||
indicators: {
|
||||
p: { value: alloc.m1 || 0, weight: model.allocations.wP },
|
||||
a: { value: alloc.m2 || 0, weight: model.allocations.wA },
|
||||
s: { value: alloc.m3 || 0, weight: model.allocations.wS },
|
||||
apRatio: ratio(alloc.costRatio), overallApRatio: ratio(model.allocations.overallRatio),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// 人數依職能分(實際人數,不是 FTE)。
|
||||
function headcountByKind(people) {
|
||||
const out = { A: 0, P: 0, G: 0, O: 0, parttime: 0, intern: 0, other: 0 };
|
||||
for (const p of people) {
|
||||
const role = String(p.role || '');
|
||||
if (p.invoiceCost || (!role.startsWith('O') && /\bintern\b/i.test(String(p.title || '')))) out.intern += 1;
|
||||
else if (role.startsWith('O')) out[p.partTime ? 'parttime' : 'O'] += 1;
|
||||
else if (/^[APG]/.test(role)) out[role[0]] += 1;
|
||||
else out.other += 1;
|
||||
}
|
||||
out.total = people.length;
|
||||
return out;
|
||||
}
|
||||
|
||||
function anchoredGroup(anchors, dept, group) {
|
||||
const g = anchors?.coda?.[dept]?.groups?.[group];
|
||||
return g ? { annual: round(g.value), h1: round(g.h1), h2: g.h2 === null ? null : round(g.h2) } : null;
|
||||
}
|
||||
|
||||
// 部長看得到的人員異動:誰離開、誰加入、哪個月生效。
|
||||
// 刻意不分離職或轉調,也不顯示轉調去哪裡,部長只需要知道編制什麼時候變。
|
||||
// 只掛在看得到整個部門的人身上;只看單一組別的人不給,免得看到別組的人。
|
||||
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));
|
||||
const invoiceTotal = model.invoice?.finalInvoiceTotal || 0;
|
||||
const depts = [];
|
||||
for (const dept of fullDepts) {
|
||||
const data = model.codaGroups[dept];
|
||||
if (!data) continue;
|
||||
const alloc = model.allocations?.deptData?.[dept];
|
||||
const anchoredDept = anchors?.coda?.[dept];
|
||||
const anchoredInvoice = anchors?.invoice?.[dept];
|
||||
const row = {
|
||||
dept, full: true,
|
||||
actualCoda: round(data.coda), avgDailyCoda: round(data.avgDailyCoda),
|
||||
anchoredCoda: anchoredDept ? { annual: round(anchoredDept.value), h1: round(anchoredDept.h1), h2: anchoredDept.h2 === null ? null : round(anchoredDept.h2) } : null,
|
||||
invoice: invoiceBreakdown(model, dept),
|
||||
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,
|
||||
anchoredCoda: anchoredGroup(anchors, dept, group), totalCost: round(model.staffCost?.groups?.[`${dept}|${group}`]),
|
||||
})).sort((a, b) => b.actualCoda - a.actualCoda),
|
||||
};
|
||||
if (permission.personDetail) {
|
||||
row.people = model.people.filter(p => (p.dept || '').trim() === dept).map(personRow)
|
||||
.sort((a, b) => a.group.localeCompare(b.group, 'zh-Hant') || b.cost - a.cost);
|
||||
}
|
||||
depts.push(row);
|
||||
}
|
||||
for (const [dept, group] of groupOnly) {
|
||||
const g = model.codaGroups?.[dept]?.groups?.[group];
|
||||
let row = depts.find(d => d.dept === dept && !d.full);
|
||||
if (!row) { row = { dept, full: false, groups: [] }; depts.push(row); }
|
||||
row.groups.push(g
|
||||
? { group, actualCoda: round(g.coda), avgDailyCoda: round(g.avgDailyCoda), headcount: g.people.length, anchoredCoda: anchoredGroup(anchors, dept, group), totalCost: round(model.staffCost?.groups?.[`${dept}|${group}`]) }
|
||||
: { group, missing: true });
|
||||
if (permission.personDetail && g) {
|
||||
row.people = [...(row.people || []), ...model.people.filter(p => (p.dept || '').trim() === dept && (p.group || '未分組') === group).map(personRow)];
|
||||
}
|
||||
}
|
||||
return {
|
||||
year,
|
||||
me: {
|
||||
employeeNumber: permission.employeeNumber,
|
||||
admin: permission.admin, company: permission.company,
|
||||
personDetail: permission.personDetail, simulate: permission.simulate,
|
||||
sources: permission.sources || [],
|
||||
},
|
||||
anchor: anchors?.active ? { half: anchors.active.half, at: anchors.active.at } : null,
|
||||
company: permission.admin || permission.company ? { invoiceTotal: round(invoiceTotal) } : null,
|
||||
depts,
|
||||
};
|
||||
}
|
||||
@@ -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,8 +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 { 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);
|
||||
@@ -22,11 +33,47 @@ const demoPath = resolve(root, 'seed/demo.json');
|
||||
// Local preview only: DEMO_DATA_FILE swaps in a fake roster. Production always reads the seed.
|
||||
const previewDataPath = !isProduction && process.env.DEMO_DATA_FILE ? resolve(root, process.env.DEMO_DATA_FILE) : demoPath;
|
||||
const costModelDataDir = process.env.COST_MODEL_DATA_DIR;
|
||||
const costOverridesPath = costModelDataDir ? resolve(costModelDataDir, 'cost-overrides.json') : null;
|
||||
const contractorsPath = costModelDataDir ? resolve(costModelDataDir, 'contractors.json') : null;
|
||||
const settingsPath = costModelDataDir ? resolve(costModelDataDir, 'board-settings.json') : null;
|
||||
// 定錨快照(新檔案)。沒有資料夾時(本機預覽)只存在記憶體。
|
||||
const anchorStore = createAnchorStore(costModelDataDir ? resolve(costModelDataDir, 'anchors.json') : null);
|
||||
// 所有存檔(成本覆寫、外包、設定、權限、定錨、封存、預排、登入狀態…)都存在 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;
|
||||
let currentYearState;
|
||||
async function getCurrentYear() {
|
||||
if (currentYearState === undefined) {
|
||||
currentYearState = { year: FIRST_YEAR, log: [] };
|
||||
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() }] };
|
||||
storage?.write('current-year.json', JSON.stringify(currentYearState));
|
||||
}
|
||||
|
||||
// 2028 起:在職月份每年各自設定(month-overrides-<年>.json),預設全年再依 HR 到職/離職限縮;
|
||||
// 職能等其他設定沿用 cost-overrides.json。
|
||||
const monthFields = new Set(['h1Start', 'h1End', 'h2Start', 'h2End']);
|
||||
const yearMonthCache = new Map();
|
||||
const yearMonthName = (year) => `month-overrides-${year}.json`;
|
||||
async function getYearMonths(year) {
|
||||
if (yearMonthCache.has(year)) return yearMonthCache.get(year);
|
||||
const text = storage?.read(yearMonthName(year));
|
||||
const raw = text != null ? JSON.parse(text) : {};
|
||||
yearMonthCache.set(year, raw);
|
||||
return raw;
|
||||
}
|
||||
async function saveYearMonths(year) {
|
||||
storage?.write(yearMonthName(year), JSON.stringify(yearMonthCache.get(year), null, 2));
|
||||
}
|
||||
// 定錨後修改的核心參數:先存成「下一次定錨才生效」(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,
|
||||
@@ -35,7 +82,11 @@ const oidc = {
|
||||
const oidcConfigured = Boolean(oidc.issuer && oidc.clientId && oidc.clientSecret);
|
||||
const hr = hrConfig(process.env.RESOURCE_SERVERS);
|
||||
const pendingLogins = new Map();
|
||||
const sessions = new Map();
|
||||
// 登入狀態跟其他資料一起存在資料庫裡,部署重新啟動後不用重新登入(本機預覽沒有資料夾就只放記憶體)。
|
||||
// 加密金鑰由執行期密鑰導出(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;
|
||||
let jwksCache;
|
||||
let persistedOverrides;
|
||||
@@ -68,6 +119,9 @@ async function hrRead(session, capability, path) {
|
||||
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']],
|
||||
@@ -78,9 +132,35 @@ const allowedStaticFiles = new Map([
|
||||
// A deployed board must never silently display sample records when the HR
|
||||
// integration is unavailable. It makes an outage indistinguishable from a
|
||||
// successful import and can lead to decisions based on synthetic values.
|
||||
async function loadBoard(session) {
|
||||
// 定錨後有人調動:生效月份前算原部門/組、之後算新部門/組(實際 CODA 按月拆分)。
|
||||
async function loadBoard(session, options) {
|
||||
const board = await loadBoardInput(session, options);
|
||||
if (board.status) return board;
|
||||
const splits = await anchorStore.transferSplits(await getCurrentYear());
|
||||
if (!splits.length) return board;
|
||||
return { payload: { ...board.payload, baseData: splitTransfers(board.payload.baseData, splits) } };
|
||||
}
|
||||
|
||||
// 看板資料一律套用預排異動(主看板、/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) {
|
||||
if (!session || !canAccess(session.claims)) return { status: 403, error: 'access_denied' };
|
||||
// scoped:呼叫端已確認過權限,回傳的資料會先依權限裁切才送出。
|
||||
if (!session || (!scoped && !canAccess(session.claims))) return { status: 403, error: 'access_denied' };
|
||||
if (!hr) return { status: 503, error: 'hr_not_configured' };
|
||||
return { payload: await getCostModel(session) };
|
||||
}
|
||||
@@ -95,6 +175,28 @@ async function loadBoard(session) {
|
||||
};
|
||||
}
|
||||
|
||||
// 這個人的權限(HR 主管+手動設定)。本機預覽沒有 HR:一律當最高管理者,
|
||||
// 或用 ?previewScope=dept:前製部,group:前製部|設計組,detail,simulate 模擬別人的範圍。
|
||||
async function getPermission(session, url) {
|
||||
const store = await permissionStore.load();
|
||||
if (!isProduction) {
|
||||
const spec = url?.searchParams.get('previewScope');
|
||||
if (!spec) return resolvePermissions('20150906', { supervisors: new Map(), organizations: [], store });
|
||||
const parts = spec.split(',').map(part => part.trim());
|
||||
return {
|
||||
employeeNumber: 'preview', admin: false, company: parts.includes('company'),
|
||||
depts: parts.filter(x => x.startsWith('dept:')).map(x => x.slice(5)),
|
||||
groups: parts.filter(x => x.startsWith('group:')).map(x => x.slice(6)),
|
||||
personDetail: parts.includes('detail'), simulate: parts.includes('simulate'), sources: ['本機預覽模擬'],
|
||||
};
|
||||
}
|
||||
if (session.permissionCache?.expiresAt > Date.now()) return session.permissionCache.value;
|
||||
const organizations = await getOrganizations(session);
|
||||
const value = resolvePermissions(session.claims?.employee_number, { supervisors: supervisorIndex(organizations), organizations, store });
|
||||
session.permissionCache = { value, expiresAt: Date.now() + 60_000 };
|
||||
return value;
|
||||
}
|
||||
|
||||
function sendJson(response, status, body) {
|
||||
response.writeHead(status, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
@@ -137,12 +239,12 @@ function cookie(name, value, maxAge) {
|
||||
function pruneExpired() {
|
||||
const now = Date.now();
|
||||
for (const [key, value] of pendingLogins) if (value.expiresAt <= now) pendingLogins.delete(key);
|
||||
for (const [key, value] of sessions) if (value.expiresAt <= now) sessions.delete(key);
|
||||
sessions.prune(now);
|
||||
}
|
||||
|
||||
function getSession(request) {
|
||||
pruneExpired();
|
||||
const sessionId = parseCookies(request).pm_board_session;
|
||||
const sessionId = parseCookies(request).leadboard_session;
|
||||
return sessionId ? sessions.get(sessionId) : undefined;
|
||||
}
|
||||
|
||||
@@ -164,6 +266,45 @@ 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();
|
||||
const response = await fetch(discovery.jwks_uri, { signal: AbortSignal.timeout(8000) });
|
||||
if (!response.ok) throw new Error(`OIDC keys failed (${response.status})`);
|
||||
jwksCache = await response.json();
|
||||
}
|
||||
return jwksCache;
|
||||
}
|
||||
|
||||
// 對外接口:伺服器用自己的系統帳號讀 HR(不依賴任何人的登入)。HR 失敗時沿用上一份結果。
|
||||
const externalSession = { claims: { employee_number: 'external-api' } };
|
||||
let externalCache = null;
|
||||
async function externalData() {
|
||||
try {
|
||||
const board = await loadBoard(externalSession, { scoped: true });
|
||||
if (board.status) throw new Error(board.error);
|
||||
const model = computeModel(board.payload);
|
||||
const year = Number(board.payload.reportYear || board.payload.globalParams?.reportYear || await getCurrentYear());
|
||||
const anchors = await anchorStore.evaluate(model, year);
|
||||
const organizations = isProduction && hr ? await getOrganizations(externalSession) : [];
|
||||
externalCache = buildExternal(model, anchors, { organizations, opMultiplier: Number(board.payload.globalParams?.opMultiplier) || 2 });
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError || !externalCache) throw error;
|
||||
console.error('External data refresh failed; serving the previous result', error.message);
|
||||
}
|
||||
return externalCache;
|
||||
}
|
||||
|
||||
async function validateIdToken(token, expectedNonce) {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 3) throw new Error('Invalid ID token');
|
||||
@@ -204,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);
|
||||
@@ -219,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) {
|
||||
@@ -228,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();
|
||||
@@ -263,22 +404,13 @@ async function finishLogin(request, response, url) {
|
||||
if (!tokenResponse.ok) return sendText(response, 401, '公司登入失敗,請重新嘗試。');
|
||||
const tokens = await tokenResponse.json();
|
||||
const claims = await validateIdToken(tokens.id_token, pending.nonce);
|
||||
if (!canAccess(claims)) {
|
||||
response.writeHead(403, {
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'Set-Cookie': cookie('pm_board_login', '', 0),
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
});
|
||||
response.end('此帳號沒有使用本系統的權限。');
|
||||
return;
|
||||
}
|
||||
// 通過公司登入的人都建立 session:白名單進主看板,其他人導到 /my(只看得到自己權限範圍的數字,沒權限就顯示「沒有權限」)。
|
||||
const sessionId = randomBytes(32).toString('base64url');
|
||||
sessions.set(sessionId, { claims, expiresAt: Date.now() + 8 * 60 * 60 * 1000,
|
||||
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, '/', [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) {
|
||||
@@ -351,32 +483,35 @@ 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']);
|
||||
|
||||
async function updateCostOverride(employeeNumber, update) {
|
||||
const year = await getCurrentYear();
|
||||
if (year > FIRST_YEAR && Object.keys(update).some(key => monthFields.has(key))) {
|
||||
const months = await getYearMonths(year);
|
||||
const monthUpdate = Object.fromEntries(Object.entries(update).filter(([key]) => monthFields.has(key)));
|
||||
months[employeeNumber] = { ...(months[employeeNumber] || {}), ...normalizeOverride(monthUpdate) };
|
||||
await saveYearMonths(year);
|
||||
update = Object.fromEntries(Object.entries(update).filter(([key]) => !monthFields.has(key)));
|
||||
if (!Object.keys(update).length) return;
|
||||
}
|
||||
const overrides = await getCostOverrides();
|
||||
const current = overrides.get(employeeNumber) || {};
|
||||
const next = normalizeOverride({ ...current, ...update });
|
||||
@@ -386,6 +521,12 @@ async function updateCostOverride(employeeNumber, update) {
|
||||
}
|
||||
|
||||
async function clearCostOverrideField(employeeNumber, field) {
|
||||
const year = await getCurrentYear();
|
||||
if (year > FIRST_YEAR && monthFields.has(field)) {
|
||||
const months = await getYearMonths(year);
|
||||
if (months[employeeNumber]) { delete months[employeeNumber][field]; await saveYearMonths(year); }
|
||||
return;
|
||||
}
|
||||
const overrides = await getCostOverrides();
|
||||
const current = overrides.get(employeeNumber);
|
||||
if (!current || !costOverrideFields.has(field)) return;
|
||||
@@ -401,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')));
|
||||
@@ -415,46 +553,72 @@ 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;
|
||||
const text = storage?.read('pending-settings.json');
|
||||
if (text != null) pendingSettings = JSON.parse(text);
|
||||
return pendingSettings;
|
||||
}
|
||||
|
||||
async function setPendingSettings(value) {
|
||||
pendingSettings = value;
|
||||
storage?.write('pending-settings.json', JSON.stringify(value));
|
||||
}
|
||||
|
||||
// 待生效的設定和目前設定差在哪裡(給畫面顯示)。
|
||||
async function pendingSummary() {
|
||||
const pending = await getPendingSettings();
|
||||
if (!pending?.settings) return null;
|
||||
const current = await getSettings();
|
||||
const params = Object.entries(pending.settings.params || {})
|
||||
.filter(([key, value]) => current.params?.[key] !== value)
|
||||
.map(([key, value]) => ({ key, from: current.params?.[key] ?? null, to: value }));
|
||||
const listChanged = (key) => JSON.stringify([...(pending.settings[key] || [])].sort()) !== JSON.stringify([...(current[key] || [])].sort());
|
||||
return {
|
||||
savedAt: pending.savedAt, by: pending.by, params,
|
||||
rdGroups: listChanged('rdGroups'), cgLeadGroups: listChanged('cgLeadGroups'),
|
||||
invoiceRoles: JSON.stringify(pending.settings.invoiceRoles || {}) !== JSON.stringify(current.invoiceRoles || {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function getCostModel(session) {
|
||||
if (session.costModelCache?.expiresAt > Date.now()) return session.costModelCache.payload;
|
||||
const [records, organizations, demo] = await Promise.all([
|
||||
@@ -469,28 +633,36 @@ async function getCostModel(session) {
|
||||
}
|
||||
});
|
||||
const overrides = await getCostOverrides();
|
||||
const year = await getCurrentYear();
|
||||
const yearMonths = year > FIRST_YEAR ? await getYearMonths(year) : {};
|
||||
// 第一年用原本的設定;之後的年份不沿用上一年的在職月份,改用當年的設定。
|
||||
const yearOverride = (override, months) => {
|
||||
if (year === FIRST_YEAR) return override;
|
||||
const base = Object.fromEntries(Object.entries(override || {}).filter(([key]) => !monthFields.has(key)));
|
||||
return { ...base, ...(months || {}) };
|
||||
};
|
||||
const supervisors = supervisorIndex(organizations);
|
||||
const people = records.map((person, index) => toCostPerson({
|
||||
...person,
|
||||
...splitOrganization(person, organizations),
|
||||
supervisorOf: supervisors.get(String(person.employeeNumber)) || [],
|
||||
}, salaryResults[index], overrides.get(person.employeeNumber), { year: 2027 }));
|
||||
}, salaryResults[index], yearOverride(overrides.get(person.employeeNumber), yearMonths[person.employeeNumber]), { year, fullYearDefault: year > FIRST_YEAR }));
|
||||
// Regular contractors have no HR counterpart. They are maintained on the board and kept
|
||||
// separate from the HR roster so their source is visible in every response.
|
||||
const contractors = await getContractors(demo);
|
||||
const payload = {
|
||||
source: 'hr-sync-2027-planning',
|
||||
reportYear: 2027,
|
||||
source: `hr-sync-${year}-planning`,
|
||||
reportYear: year,
|
||||
generatedAt: new Date().toISOString(),
|
||||
baseData: [...people, ...contractors],
|
||||
globalParams: applySettings({ ...demo.globalParams, reportYear: 2027, orgStructure: null }, await getSettings()),
|
||||
globalParams: applySettings({ ...demo.globalParams, reportYear: year, orgStructure: null }, await getSettings()),
|
||||
summary: {
|
||||
activeEmployees: people.length,
|
||||
readyForCalculation: people.filter(person => person.calculationReady).length,
|
||||
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 };
|
||||
@@ -511,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') {
|
||||
@@ -527,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 {}
|
||||
@@ -548,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>');
|
||||
@@ -628,7 +800,7 @@ const server = createServer(async (request, response) => {
|
||||
if (request.method === 'POST' && /^\/api\/hr\/cost-model\/employees\/[^/]+$/.test(url.pathname)) {
|
||||
const session = requireAuth(request, response, true);
|
||||
if (!session) return;
|
||||
if (!canAccess(session.claims)) return sendJson(response, 403, { error: 'access_denied' });
|
||||
if (!isTopAdmin(session.claims)) return sendJson(response, 403, { error: 'top_admin_only' });
|
||||
const employeeNumber = url.pathname.split('/')[5];
|
||||
if (!/^[a-zA-Z0-9_-]{1,40}$/.test(employeeNumber)) return sendJson(response, 400, { error: 'invalid_employee_number' });
|
||||
const roster = await getRoster(session);
|
||||
@@ -646,8 +818,18 @@ const server = createServer(async (request, response) => {
|
||||
if (request.method === 'PUT' && url.pathname === '/api/cost-model/settings') {
|
||||
const session = requireAuth(request, response, true);
|
||||
if (!session) return;
|
||||
if (isProduction && !canAccess(session.claims)) return sendJson(response, 403, { error: 'access_denied' });
|
||||
if (isProduction && !isTopAdmin(session.claims)) return sendJson(response, 403, { error: 'top_admin_only' });
|
||||
const body = await readJson(request, 100_000);
|
||||
// 已定錨:參數改成「下一次定錨才生效」,這半年的數字照舊。
|
||||
if (await anchorStore.hasAnchor(await getCurrentYear())) {
|
||||
try {
|
||||
await setPendingSettings({ settings: normalizeSettings(body), savedAt: new Date().toISOString(), by: session.claims?.employee_number || 'preview' });
|
||||
} catch (error) {
|
||||
if (error instanceof TypeError) return sendJson(response, 400, { error: 'invalid_settings' });
|
||||
throw error;
|
||||
}
|
||||
return sendJson(response, 200, { ok: true, pending: true });
|
||||
}
|
||||
let saved;
|
||||
try {
|
||||
saved = await saveSettings(body);
|
||||
@@ -662,7 +844,7 @@ const server = createServer(async (request, response) => {
|
||||
if (request.method === 'PUT' && url.pathname === '/api/cost-model/contractors') {
|
||||
const session = requireAuth(request, response, true);
|
||||
if (!session) return;
|
||||
if (isProduction && !canAccess(session.claims)) return sendJson(response, 403, { error: 'access_denied' });
|
||||
if (isProduction && !isTopAdmin(session.claims)) return sendJson(response, 403, { error: 'top_admin_only' });
|
||||
const body = await readJson(request, 400_000);
|
||||
let saved;
|
||||
try {
|
||||
@@ -678,7 +860,7 @@ const server = createServer(async (request, response) => {
|
||||
if (request.method === 'DELETE' && /^\/api\/hr\/cost-model\/employees\/[^/]+\/overrides\/[^/]+$/.test(url.pathname)) {
|
||||
const session = requireAuth(request, response, true);
|
||||
if (!session) return;
|
||||
if (!canAccess(session.claims)) return sendJson(response, 403, { error: 'access_denied' });
|
||||
if (!isTopAdmin(session.claims)) return sendJson(response, 403, { error: 'top_admin_only' });
|
||||
const [, , , , , employeeNumber, , field] = url.pathname.split('/');
|
||||
if (!/^[a-zA-Z0-9_-]{1,40}$/.test(employeeNumber) || !costOverrideFields.has(field)) return sendJson(response, 400, { error: 'invalid_override' });
|
||||
const roster = await getRoster(session);
|
||||
@@ -698,17 +880,23 @@ const server = createServer(async (request, response) => {
|
||||
}
|
||||
|
||||
// 定錨:查看任何有權限的人都可以;按定錨、改調動生效月份只有最高管理者。
|
||||
if (url.pathname === '/api/anchors' || url.pathname === '/api/anchors/transfers') {
|
||||
if (['/api/anchors', '/api/anchors/transfers', '/api/anchors/peak-reset', '/api/anchors/peak-restore', '/api/anchors/undo'].includes(url.pathname)) {
|
||||
const session = requireAuth(request, response, true);
|
||||
if (!session) return;
|
||||
const board = await loadBoard(session);
|
||||
if (board.status) return sendJson(response, board.status, { error: board.error });
|
||||
const model = computeModel(board.payload);
|
||||
const year = Number(board.payload.reportYear || board.payload.globalParams?.reportYear || 2027);
|
||||
const year = Number(board.payload.reportYear || board.payload.globalParams?.reportYear || await getCurrentYear());
|
||||
const topAdmin = !isProduction || isTopAdmin(session.claims);
|
||||
const by = session.claims?.employee_number || 'preview';
|
||||
if (request.method === 'GET' && url.pathname === '/api/anchors') {
|
||||
return sendJson(response, 200, { ...await anchorStore.evaluate(model, year), canAnchor: topAdmin });
|
||||
return sendJson(response, 200, { ...await anchorStore.evaluate(model, year), canAnchor: topAdmin, pendingSettings: await pendingSummary() });
|
||||
}
|
||||
if (request.method === 'DELETE' && url.pathname === '/api/anchors') {
|
||||
// 取消「下一次定錨才生效」的參數修改。
|
||||
if (!topAdmin) return sendJson(response, 403, { error: 'top_admin_only' });
|
||||
await setPendingSettings(null);
|
||||
return sendJson(response, 200, { ok: true });
|
||||
}
|
||||
if (request.method === 'POST') {
|
||||
if (!topAdmin) return sendJson(response, 403, { error: 'top_admin_only' });
|
||||
@@ -716,7 +904,25 @@ const server = createServer(async (request, response) => {
|
||||
try {
|
||||
if (url.pathname === '/api/anchors') {
|
||||
if (body.confirm !== true) return sendJson(response, 400, { error: 'confirmation_required' });
|
||||
return sendJson(response, 200, await anchorStore.anchor(model, { year, half: body.half, note: body.note, by }));
|
||||
// 定錨時先套用待生效的參數,再用新參數算出這次的快照。
|
||||
const pending = await getPendingSettings();
|
||||
let anchorModel = model;
|
||||
if (pending?.settings) {
|
||||
await saveSettings(pending.settings);
|
||||
await setPendingSettings(null);
|
||||
session.costModelCache = null;
|
||||
const refreshed = await loadBoard(session);
|
||||
if (refreshed.status) return sendJson(response, refreshed.status, { error: refreshed.error });
|
||||
anchorModel = computeModel(refreshed.payload);
|
||||
}
|
||||
return sendJson(response, 200, await anchorStore.anchor(anchorModel, { year, half: body.half, note: body.note, by }));
|
||||
}
|
||||
if (url.pathname === '/api/anchors/peak-reset') return sendJson(response, 200, await anchorStore.resetPeak({ year, kind: body.kind, key: String(body.key || ''), reason: body.reason, by }));
|
||||
if (url.pathname === '/api/anchors/peak-restore') return sendJson(response, 200, await anchorStore.restorePeak({ year, id: String(body.id || ''), by }));
|
||||
if (url.pathname === '/api/anchors/undo') {
|
||||
if (body.confirm !== true) return sendJson(response, 400, { error: 'confirmation_required' });
|
||||
if (await archiveStore.get(year)) return sendJson(response, 400, { error: 'year_archived' });
|
||||
return sendJson(response, 200, await anchorStore.undoAnchor({ year, reason: body.reason, by }));
|
||||
}
|
||||
return sendJson(response, 200, await anchorStore.setTransferMonth({ year, key: String(body.key || ''), month: Number(body.month), by }));
|
||||
} catch (error) {
|
||||
@@ -726,8 +932,222 @@ const server = createServer(async (request, response) => {
|
||||
}
|
||||
}
|
||||
|
||||
// 權限管理已經搬進主看板,舊網址導回看板並直接打開那個區塊(別人存的連結不會壞)。
|
||||
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', '/archive': 'archive.html' }[url.pathname]));
|
||||
// 登出(含公司帳號)會轉到公司登入伺服器,form-action 要允許它。
|
||||
const authOrigin = (() => { try { return oidc.issuer ? new URL(oidc.issuer).origin : ''; } catch { return ''; } })();
|
||||
response.writeHead(200, {
|
||||
'Content-Type': 'text/html; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Content-Security-Policy': `default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'${authOrigin ? ` ${authOrigin}` : ''}`,
|
||||
});
|
||||
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;
|
||||
const permission = await getPermission(session, url);
|
||||
if (!hasAnyScope(permission)) return sendJson(response, 403, { error: 'no_permission', employeeNumber: permission.employeeNumber, sources: permission.sources || [] });
|
||||
const board = await loadBoard(session, { scoped: true });
|
||||
if (board.status) return sendJson(response, board.status, { error: board.error });
|
||||
const model = computeModel(board.payload);
|
||||
const year = Number(board.payload.reportYear || board.payload.globalParams?.reportYear || await getCurrentYear());
|
||||
const anchors = await anchorStore.evaluate(model, 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、不套工號白名單),只讀。
|
||||
if (url.pathname === '/api/external/v1/invoice' || url.pathname === '/api/external/v1/coda') {
|
||||
if (request.method !== 'GET') return sendJson(response, 405, { error: 'method_not_allowed' });
|
||||
if (!oidcConfigured) return sendJson(response, 503, { error: 'auth_not_configured' });
|
||||
let caller;
|
||||
try {
|
||||
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;
|
||||
}
|
||||
console.log(JSON.stringify({ event: 'external_api', path: url.pathname, sub: caller.sub, actorType: caller.actorType, employeeNumber: caller.employeeNumber }));
|
||||
if (!await anchorStore.hasAnchor(await getCurrentYear())) return sendJson(response, 503, { error: 'not_anchored', message: '尚未定錨' });
|
||||
try {
|
||||
const data = await externalData();
|
||||
return sendJson(response, 200, url.pathname.endsWith('/invoice') ? data.invoice : data.coda);
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) return sendJson(response, error.status, { error: error.code, message: error.message });
|
||||
return sendJson(response, 503, { error: 'temporarily_unavailable' });
|
||||
}
|
||||
}
|
||||
|
||||
// 開始下一年:只有最高管理者,必須先封存目前年度。之後首頁、定錨、對外接口都改用新的年度。
|
||||
if (request.method === 'POST' && url.pathname === '/api/year/next') {
|
||||
const session = requireAuth(request, response, true);
|
||||
if (!session) return;
|
||||
if (isProduction && !isTopAdmin(session.claims)) return sendJson(response, 403, { error: 'top_admin_only' });
|
||||
const body = await readJson(request, 2_000);
|
||||
if (body.confirm !== true) return sendJson(response, 400, { error: 'confirmation_required' });
|
||||
const year = await getCurrentYear();
|
||||
if (!await archiveStore.get(year)) return sendJson(response, 400, { error: 'archive_required' });
|
||||
await startYear(year + 1, session.claims?.employee_number || 'preview');
|
||||
for (const s of sessions.values()) s.costModelCache = null;
|
||||
externalSession.costModelCache = null;
|
||||
externalCache = null;
|
||||
return sendJson(response, 200, { ok: true, year: year + 1 });
|
||||
}
|
||||
|
||||
// 年度封存:查看、封存都只有最高管理者。封存要在 H2 定錨之後,封存後唯讀。
|
||||
if (url.pathname === '/api/archive') {
|
||||
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 === 'GET') {
|
||||
const year = url.searchParams.get('year');
|
||||
if (year) {
|
||||
const archive = await archiveStore.get(year);
|
||||
return archive ? sendJson(response, 200, archive) : sendJson(response, 404, { error: 'not_archived' });
|
||||
}
|
||||
const store = await anchorStore.hasAnchor(await getCurrentYear());
|
||||
return sendJson(response, 200, { currentYear: await getCurrentYear(), years: await archiveStore.list(), anchored: store });
|
||||
}
|
||||
if (request.method === 'POST') {
|
||||
const body = await readJson(request, 4_000);
|
||||
if (body.confirm !== true || !String(body.note || '').trim()) return sendJson(response, 400, { error: 'confirmation_required' });
|
||||
const board = await loadBoard(session);
|
||||
if (board.status) return sendJson(response, board.status, { error: board.error });
|
||||
const model = computeModel(board.payload);
|
||||
const year = Number(board.payload.reportYear || board.payload.globalParams?.reportYear || await getCurrentYear());
|
||||
const anchors = await anchorStore.evaluate(model, year);
|
||||
if (anchors.active?.half !== 'H2') return sendJson(response, 400, { error: 'h2_anchor_required' });
|
||||
try {
|
||||
await archiveStore.save(buildArchive(model, anchors, { year, by: session.claims?.employee_number || 'preview', note: body.note, at: new Date().toISOString() }));
|
||||
} catch (error) {
|
||||
if (error instanceof RangeError) return sendJson(response, 400, { error: error.message });
|
||||
throw error;
|
||||
}
|
||||
return sendJson(response, 200, { ok: true, year });
|
||||
}
|
||||
}
|
||||
|
||||
// 部長模擬試算:只能模擬自己有模擬權限的部門;不存檔。
|
||||
if (request.method === 'POST' && url.pathname === '/api/simulate') {
|
||||
const session = requireAuth(request, response, true);
|
||||
if (!session) return;
|
||||
const permission = await getPermission(session, url);
|
||||
const body = await readJson(request, 60_000);
|
||||
const dept = typeof body.dept === 'string' ? body.dept.trim() : '';
|
||||
const allowed = permission.admin || (permission.simulate && permission.depts.includes(dept));
|
||||
if (!allowed) return sendJson(response, 403, { error: 'simulate_not_allowed' });
|
||||
const board = await loadBoard(session, { scoped: true });
|
||||
if (board.status) return sendJson(response, board.status, { error: board.error });
|
||||
const year = Number(board.payload.reportYear || board.payload.globalParams?.reportYear || await getCurrentYear());
|
||||
let simulatedPayload;
|
||||
try {
|
||||
simulatedPayload = applySimulation(board.payload, dept, { additions: body.additions, raises: body.raises });
|
||||
} catch (error) {
|
||||
if (error instanceof RangeError) return sendJson(response, 400, { error: error.message });
|
||||
throw error;
|
||||
}
|
||||
const before = computeModel(board.payload);
|
||||
if (!before.codaGroups?.[dept]) return sendJson(response, 400, { error: 'unknown dept' });
|
||||
const after = computeModel(simulatedPayload);
|
||||
const anchorsBefore = await anchorStore.evaluate(before, year, Date.now(), { persist: false });
|
||||
const anchorsAfter = await anchorStore.evaluate(after, year, Date.now(), { persist: false });
|
||||
return sendJson(response, 200, compareDept(before, after, anchorsBefore, anchorsAfter, dept));
|
||||
}
|
||||
|
||||
if (url.pathname === '/api/permissions') {
|
||||
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 === 'POST') {
|
||||
const body = await readJson(request, 8_000);
|
||||
try {
|
||||
await permissionStore.set({ employeeNumber: body.employeeNumber, grant: body.grant, denied: body.denied, by: session.claims?.employee_number || 'preview' });
|
||||
} catch (error) {
|
||||
if (error instanceof RangeError || error instanceof TypeError) return sendJson(response, 400, { error: error.message });
|
||||
throw error;
|
||||
}
|
||||
return sendJson(response, 200, { ok: true });
|
||||
}
|
||||
if (request.method === 'GET') {
|
||||
const store = await permissionStore.load();
|
||||
if (!isProduction || !hr) return sendJson(response, 200, { people: [], grants: store.grants, denied: store.denied, log: (store.log || []).slice(-200).reverse(), preview: true });
|
||||
const [records, organizations] = await Promise.all([getRoster(session), getOrganizations(session)]);
|
||||
const supervisors = supervisorIndex(organizations);
|
||||
const people = records.map(person => {
|
||||
const place = splitOrganization(person, organizations);
|
||||
const permission = resolvePermissions(person.employeeNumber, { supervisors, organizations, store });
|
||||
return {
|
||||
employeeNumber: String(person.employeeNumber), name: person.name, dept: place.departmentName || '', group: place.groupName || '',
|
||||
title: person.positionName || '', permission, hasScope: hasAnyScope(permission),
|
||||
};
|
||||
});
|
||||
return sendJson(response, 200, { people, grants: store.grants, denied: store.denied, log: (store.log || []).slice(-200).reverse() });
|
||||
}
|
||||
}
|
||||
|
||||
if (request.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) {
|
||||
if (!requireAuth(request, response)) return;
|
||||
const session = requireAuth(request, response);
|
||||
if (!session) return;
|
||||
// 不是最高管理者:去依權限的頁面(那裡只會拿到他可以看的數字)。
|
||||
if (isProduction && !canAccess(session.claims)) return redirect(response, '/my');
|
||||
const content = await readFile(resolve(root, 'index.html'));
|
||||
response.writeHead(200, {
|
||||
'Content-Type': 'text/html; charset=utf-8',
|
||||
@@ -757,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' } : {}) });
|
||||
}
|
||||
@@ -769,7 +1189,27 @@ const server = createServer(async (request, response) => {
|
||||
}
|
||||
});
|
||||
|
||||
// 部署重新啟動前先把登入狀態寫進檔案。
|
||||
for (const signal of ['SIGTERM', 'SIGINT']) {
|
||||
process.once(signal, () => {
|
||||
try { sessions.flush(); } catch (error) { console.error('session save failed', error.message); }
|
||||
process.exit(0);
|
||||
});
|
||||
}
|
||||
|
||||
server.listen(port, host, () => {
|
||||
console.log(`Cost model preview listening on http://${host}:${port}`);
|
||||
if (restoredSessions) console.log(`Restored ${restoredSessions} signed-in session(s).`);
|
||||
if (isProduction && !oidcConfigured) console.warn('Company login is not configured; protected routes are closed.');
|
||||
});
|
||||
|
||||
// 每 6 小時自動重算一次(最新 HR + 最近一次定錨),更新最高點與對外接口的結果。網站不用開著。
|
||||
if (isProduction && hr) {
|
||||
setInterval(async () => {
|
||||
try {
|
||||
if (await anchorStore.hasAnchor(await getCurrentYear())) await externalData();
|
||||
} catch (error) {
|
||||
console.error('Scheduled recalculation failed:', error.message);
|
||||
}
|
||||
}, 6 * 60 * 60 * 1000).unref();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
// 登入狀態存檔:sessions.json(存在 COST_MODEL_DATA_DIR/leadboard.db 的 documents 表;STORAGE_BACKEND=json 時是同名檔案,不進 Git)。部署重新啟動後,大家不用重新登入。
|
||||
// - 檔案裡只存 session id 的 SHA-256,不存瀏覽器 cookie 的原始值;檔案權限 600。
|
||||
// - 只存登入需要的欄位;HR 名單、權限、成本等暫存(*Cache)不存。
|
||||
// - 過期的不載入、不存。
|
||||
// - 每一筆登入資料(含 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 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 current() {
|
||||
const time = now();
|
||||
const out = {};
|
||||
for (const [id, session] of map) {
|
||||
if (!(session.expiresAt > time)) continue;
|
||||
out[id] = Object.fromEntries(KEPT.filter(field => session[field] !== undefined).map(field => [field, session[field]]));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// 同步寫檔:關機時也能寫完。內容沒變就不寫。
|
||||
function flush() {
|
||||
if (timer) { clearTimeout(timer); timer = null; }
|
||||
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 (!file || timer) return;
|
||||
timer = setTimeout(() => { timer = null; try { flush(); } catch (error) { console.error('session save failed', error.message); } }, saveDelay);
|
||||
timer.unref?.();
|
||||
}
|
||||
|
||||
function load() {
|
||||
if (!file) return 0;
|
||||
let data;
|
||||
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();
|
||||
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 = '';
|
||||
if (legacy) flush();
|
||||
else lastWritten = createHash('sha256').update(JSON.stringify(current())).digest('hex');
|
||||
return map.size;
|
||||
}
|
||||
|
||||
return {
|
||||
load,
|
||||
flush,
|
||||
// HR 換新 token 會直接改 session 物件;定時檢查有沒有變,有變才寫。
|
||||
startAutosave(interval = 30_000) {
|
||||
const handle = setInterval(schedule, interval);
|
||||
handle.unref?.();
|
||||
return handle;
|
||||
},
|
||||
get: (id) => map.get(hash(id)),
|
||||
set(id, session) { map.set(hash(id), session); schedule(); return this; },
|
||||
delete(id) { const removed = map.delete(hash(id)); if (removed) schedule(); return removed; },
|
||||
prune() {
|
||||
const time = now();
|
||||
let removed = false;
|
||||
for (const [key, session] of map) if (!(session.expiresAt > time)) { map.delete(key); removed = true; }
|
||||
if (removed) schedule();
|
||||
},
|
||||
values: () => map.values(),
|
||||
get size() { return map.size; },
|
||||
};
|
||||
}
|
||||
+25
-1
@@ -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 } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
// 部長模擬試算:在自己部門加人(O/P/A/實習/工讀)或幫現有的人調薪,伺服器算出
|
||||
// 實際 CODA、平均日 CODA、定錨 CODA、發票各會變多少。不存檔、不影響正式數字。
|
||||
import { PART_TIME_HOURS_PER_DAY } from './cost-model.js';
|
||||
import { multiplierFor } from './scope-view.js';
|
||||
|
||||
export const SIM_KINDS = Object.freeze(['P', 'A', 'O', 'intern', 'parttime']);
|
||||
const MAX_ADDITIONS = 30;
|
||||
const MAX_RAISES = 100;
|
||||
|
||||
const text = (value, max = 80) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
|
||||
const money = (value) => {
|
||||
const number = Number(value);
|
||||
if (!Number.isFinite(number) || number < 0 || number > 10_000_000) throw new RangeError('amount out of range');
|
||||
return number;
|
||||
};
|
||||
const month = (value, min, max) => {
|
||||
if (value === '' || value === null || value === undefined) return '';
|
||||
const number = Number(value);
|
||||
if (!Number.isInteger(number) || number < min || number > max) throw new RangeError('month out of range');
|
||||
return number;
|
||||
};
|
||||
|
||||
// 把一筆「新增的人」轉成計算核心看得懂的資料。
|
||||
export function simulatedPerson(input, { dept, company }, index) {
|
||||
const kind = text(input.kind, 10);
|
||||
if (!SIM_KINDS.includes(kind)) throw new RangeError('unknown kind');
|
||||
const salaryType = text(input.salaryType, 10);
|
||||
const amount = money(input.amount);
|
||||
const months = {
|
||||
h1Start: month(input.h1Start, 1, 6), h1End: month(input.h1End, 1, 6),
|
||||
h2Start: month(input.h2Start, 7, 12), h2End: month(input.h2End, 7, 12),
|
||||
};
|
||||
if ((months.h1Start === '') !== (months.h1End === '') || (months.h2Start === '') !== (months.h2End === '')) throw new RangeError('months incomplete');
|
||||
if (months.h1Start !== '' && months.h1Start > months.h1End) throw new RangeError('months reversed');
|
||||
if (months.h2Start !== '' && months.h2Start > months.h2End) throw new RangeError('months reversed');
|
||||
const base = {
|
||||
row: `sim-${index}`, source: 'simulation', name: text(input.name) || `模擬 ${index + 1}`,
|
||||
dept, group: text(input.group) || '', company, isManager: false, weeklyWorkDays: 5,
|
||||
calculationReady: true, calculationIssue: '', ...months,
|
||||
};
|
||||
if (kind === 'O' || kind === 'parttime') {
|
||||
// 工讀當 O:日薪 = 時薪 × 8。外包可以填日薪或時薪。
|
||||
let dayrate;
|
||||
if (salaryType === 'daily') dayrate = amount;
|
||||
else if (salaryType === 'hourly') dayrate = amount * PART_TIME_HOURS_PER_DAY;
|
||||
else throw new RangeError('O needs a daily or hourly rate');
|
||||
return { ...base, role: 'O - 外包', title: kind === 'parttime' ? '工讀生' : '外包', partTime: kind === 'parttime', dayrate, salary: 0, hourlyRate: 0, salaryType: 'daily' };
|
||||
}
|
||||
const role = kind === 'P' ? 'P - 製作' : 'A - 藝術家';
|
||||
const title = kind === 'intern' ? 'Intern' : (text(input.title) || (kind === 'P' ? 'Producer' : 'Artist'));
|
||||
if (salaryType === 'monthly') return { ...base, role, title, salary: amount, hourlyRate: 0, salaryType: 'monthly' };
|
||||
if (salaryType === 'hourly') return { ...base, role, title, salary: 0, hourlyRate: amount, salaryType: 'hourly' };
|
||||
if (salaryType === 'daily') return { ...base, role, title, salary: 0, hourlyRate: amount / 8, salaryType: 'hourly' };
|
||||
throw new RangeError('unknown salary type');
|
||||
}
|
||||
|
||||
// 依模擬內容做出一份新的輸入資料(不動原本的資料)。
|
||||
export function applySimulation(payload, dept, { additions = [], raises = [] } = {}) {
|
||||
if (!Array.isArray(additions) || additions.length > MAX_ADDITIONS) throw new RangeError('too many additions');
|
||||
if (!Array.isArray(raises) || raises.length > MAX_RAISES) throw new RangeError('too many raises');
|
||||
const baseData = JSON.parse(JSON.stringify(payload.baseData));
|
||||
const inDept = baseData.filter(p => (p.dept || '').trim() === dept);
|
||||
const company = inDept.find(p => p.company)?.company || '';
|
||||
for (const raise of raises) {
|
||||
const key = text(String(raise.employeeNumber ?? ''), 40);
|
||||
const person = inDept.find(p => String(p.employeeNumber || '') === key && p.source === 'hr-sync' && !String(p.role || '').startsWith('O'));
|
||||
if (!person) throw new RangeError('raise target not in department');
|
||||
const amount = money(raise.amount);
|
||||
if (person.salaryType === 'hourly') person.hourlyRate = amount; else person.salary = amount;
|
||||
}
|
||||
additions.forEach((input, index) => baseData.push(simulatedPerson(input, { dept, company }, index)));
|
||||
return { ...payload, baseData };
|
||||
}
|
||||
|
||||
// 前後比較:只回傳這個部門的數字。
|
||||
export function compareDept(before, after, anchorsBefore, anchorsAfter, dept) {
|
||||
const pick = (model, anchors) => {
|
||||
const coda = model.codaGroups?.[dept] || { coda: 0, avgDailyCoda: 0, groups: {} };
|
||||
const alloc = model.allocations?.deptData?.[dept];
|
||||
return {
|
||||
actualCoda: coda.coda, avgDailyCoda: coda.avgDailyCoda,
|
||||
groups: Object.fromEntries(Object.entries(coda.groups).map(([g, v]) => [g, { actualCoda: v.coda, avgDailyCoda: v.avgDailyCoda, headcount: v.people.length }])),
|
||||
invoice: alloc ? model.invoice.finalInvoiceTotal * (alloc.finalPct || 0) : null,
|
||||
invoiceShare: alloc ? alloc.finalPct || 0 : null,
|
||||
multiplier: multiplierFor(model, dept)?.value ?? null,
|
||||
anchoredCoda: anchors?.coda?.[dept]?.value ?? null,
|
||||
anchoredInvoice: anchors?.invoice?.[dept]?.annual ?? null,
|
||||
};
|
||||
};
|
||||
const a = pick(before, anchorsBefore);
|
||||
const b = pick(after, anchorsAfter);
|
||||
const delta = (x, y) => (x === null || y === null ? null : Math.round(y - x));
|
||||
const groups = [...new Set([...Object.keys(a.groups), ...Object.keys(b.groups)])].map(group => ({
|
||||
group,
|
||||
before: { actualCoda: Math.round(a.groups[group]?.actualCoda || 0), avgDailyCoda: Math.round(a.groups[group]?.avgDailyCoda || 0), headcount: a.groups[group]?.headcount || 0 },
|
||||
after: { actualCoda: Math.round(b.groups[group]?.actualCoda || 0), avgDailyCoda: Math.round(b.groups[group]?.avgDailyCoda || 0), headcount: b.groups[group]?.headcount || 0 },
|
||||
}));
|
||||
const rows = ['actualCoda', 'avgDailyCoda', 'anchoredCoda', 'invoice', 'anchoredInvoice'].map(key => ({
|
||||
key, before: a[key] === null ? null : Math.round(a[key]), after: b[key] === null ? null : Math.round(b[key]), delta: delta(a[key], b[key]),
|
||||
}));
|
||||
// 倍率(兩位小數)與發票佔比(0–1):不四捨五入成整數。
|
||||
for (const key of ['multiplier', 'invoiceShare']) {
|
||||
rows.push({ key, before: a[key], after: b[key], delta: a[key] === null || b[key] === null ? null : b[key] - a[key] });
|
||||
}
|
||||
return { dept, rows, groups, anchored: Boolean(anchorsBefore?.active) };
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
---
|
||||
name: leadboard-external-api
|
||||
description: 讀取 MoonShine LeadBoard 對外接口的年度發票(含 H1/H2 半年定錨)與 CODA(實際 CODA、定錨 CODA;夢想創造、夢境現實)彙整數字,並正確解讀欄位、版本與算法。當使用者要查部門發票目標、H1/H2 目標、部門或組別的實際/定錨 CODA、平均日 CODA、研發部成本,或要串接 LeadBoard 數字時使用。
|
||||
---
|
||||
|
||||
# LeadBoard 對外接口
|
||||
|
||||
LeadBoard(https://leadboard-vibe.moonshine-studio.net/)是 MoonShine 的人力成本與目標系統。
|
||||
(原名 PM Board,2026-11 改名;對外接口的代號也已同步改為 leadboard。)
|
||||
這個接口提供**彙整後**的年度發票與 CODA 數字,給公司內部其他系統讀取。
|
||||
|
||||
> **狀態(2026-11-12)**:接口程式已上線(網址見第 2 節),但**第一次定錨前一律回 503「尚未定錨」**。第一次正式定錨預計在 2027 年 1 月,之後才有數字。
|
||||
> 正式依據是專案內的 `EXTERNAL-API-SPEC.md`;本 skill 與它不一致時,以規格文件為準。
|
||||
|
||||
## 1. 什麼時候用
|
||||
|
||||
- 查「某部門今年的發票目標是多少」「H1/H2 目標」「為什麼發票變多」。
|
||||
- 查「某部門/某組的實際 CODA、平均日 CODA、定錨 CODA」。
|
||||
- 查「夢想創造或夢境現實的實際 CODA 合計」「研發部成本」。
|
||||
- 要把這些數字串進其他系統、報表、儀表板。
|
||||
|
||||
不要用這個接口找個人資料:接口**沒有**姓名、薪資、個人 CODA,也沒有個別人事異動明細。被問到時直接說明不提供。
|
||||
|
||||
## 2. 存取
|
||||
|
||||
- 只有讀取(GET),兩支網址:
|
||||
- `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 的 `leadboard` provider 簽發(RS256)。
|
||||
- `iss`:Authentik 的 leadboard provider
|
||||
- `aud`(audience):`leadboard-api`
|
||||
- `scope`:要含 `leadboard:read`
|
||||
- 效期 300 秒,過期要重新換發。
|
||||
- 誰能拿到 token:Authentik 只把 `leadboard:read` 發給群組 `leadboard-read`。
|
||||
vibe 站台(例如 morning)在自己的 `vibe.yaml` 宣告 `auth.resource_servers.leadboard`,
|
||||
平台負責換 token;因為是代表登入者呼叫,**實際操作的使用者**要在 `leadboard-read` 群組,
|
||||
不在群組的人整張 token 會被拒。非 vibe 的系統要接,由 RD 個別建立服務帳號。
|
||||
- 這兩支網址不看 LeadBoard 的工號白名單,只看 token。每次呼叫都會記錄呼叫者(`sub`、工號)。
|
||||
- 金鑰或 token 不可寫進程式碼、文件或對話,只放在環境變數或密鑰管理工具。
|
||||
|
||||
技術細節(JWKS、`iss`、401/403 怎麼判斷、伺服器怎麼讀 HR)見專案內的 `AUTHENTIK-HANDOFF.md`。
|
||||
|
||||
## 3. 資料內容
|
||||
|
||||
金額單位:新台幣元,四捨五入到整數。只提供**當年度**。
|
||||
|
||||
### 3.1 年度發票(`/invoice`,只有夢想創造)
|
||||
|
||||
- `invoiceTotal`:年度發票總額 = 四個部門 `annual` 加總。
|
||||
- `departments[]`:前製部、廣告部、視效部、動畫部,每筆有 `company`、`deptCode`(HR 部門代碼)、`dept`,以及:
|
||||
|
||||
| 欄位 | 意思 |
|
||||
|---|---|
|
||||
| `anchorAnnual` | 年初定錨分配到的全年金額(含部門調動移轉後的調整) |
|
||||
| `increase` | 定錨後本部門的增加金額(只增不減、以半年最高點為準) |
|
||||
| `annual` | 全年 = `anchorAnnual` + `increase` |
|
||||
| `h1.target` / `h1.settled` | 1–6 月目標;`settled: true` 表示已結算、不再變動 |
|
||||
| `h2.target` / `h2.provisional` | 7–12 月目標 = 全年 − H1 結算;`provisional: true` 表示 7 月定錨前的暫定值 |
|
||||
|
||||
- `rdDeptCost`:夢想創造研發部成本(年薪 × 人薪倍率,不除產出率)。研發部不分發票。
|
||||
- 夢境現實不承擔發票,沒有發票資料。
|
||||
|
||||
### 3.2 CODA(`/coda`)
|
||||
|
||||
回應是 `companies[]`,每間公司一筆:`company`、`actualCoda`(公司實際 CODA 合計)、`departments[]`。
|
||||
|
||||
**兩種 CODA(名詞固定)**
|
||||
|
||||
| | 實際 CODA(`actualCoda`) | 定錨 CODA(`anchoredCoda`) |
|
||||
|---|---|---|
|
||||
| 用途 | 每天看、判斷案子划不划算、定價 | 半年的目標,不因減人而下降 |
|
||||
| 怎麼算 | 即時計算,資料一變就跟著變 | 1 月、7 月與發票一起定錨,半年內只取最高點 |
|
||||
| 會不會降 | 會 | 半年內不會;下次定錨重算才可能降 |
|
||||
| 有沒有平均日 | 有(`avgDailyCoda`) | 沒有,只有總額 |
|
||||
|
||||
**定價一律看實際 CODA 的 `avgDailyCoda`。**
|
||||
|
||||
每個部門(`departments[]`)與組別(`groups[]`)的欄位:
|
||||
|
||||
| 欄位 | 意思 |
|
||||
|---|---|
|
||||
| `deptCode` / `dept` | HR 部門代碼、部門名稱 |
|
||||
| `groupCode` / `group` | (組別才有)HR 組別代碼、組名全名,例如「前製部_導演組」 |
|
||||
| `actualCoda` | 實際 CODA |
|
||||
| `avgDailyCoda` | 實際 CODA 的平均日 CODA |
|
||||
| `anchoredCoda.annual` | 定錨 CODA 全年 |
|
||||
| `anchoredCoda.h1` / `h1Settled` | H1 定錨 CODA(=全年 ÷ 2);`h1Settled: true` 表示已結算 |
|
||||
| `anchoredCoda.h2` / `h2Provisional` | H2 定錨 CODA(=最新全年 − H1 結算);`h2Provisional: true` 表示 7 月定錨前的暫定值 |
|
||||
|
||||
`anchoredCoda` 可能是 `null`(該單位沒有定錨資料,例如定錨後才新成立的組)。
|
||||
|
||||
| 公司 | 公司層級 | 部門層級 | 組別層級 |
|
||||
|---|---|---|---|
|
||||
| 夢想創造 | 實際 CODA 合計(前製、廣告、視效、動畫四部門) | 四部門:實際、平均日、定錨 | 四部門底下每組:實際、平均日、定錨 |
|
||||
| 夢境現實 | 實際 CODA 合計(分攤後加總) | 互動技術部、互動美術部:實際、平均日、定錨 | 不提供 |
|
||||
|
||||
- 部門實際 CODA = 各組加總;部門定錨 CODA = 各組定錨加總。
|
||||
- **不提供全公司定錨 CODA**:調動時原單位不降、新單位增加,加總會重複計算。
|
||||
- 組別數字已扣研發減免、CG Lead 承擔,但**不標示**哪組是研發組或 CG Lead 組。
|
||||
- 夢境現實的「專案與場館營運部」不列出(CODA 已分攤到另外兩個部門)。
|
||||
|
||||
### 3.3 共同欄位(兩支網址每次回應都有)
|
||||
|
||||
| 欄位 | 意思 |
|
||||
|---|---|
|
||||
| `year` | 年度 |
|
||||
| `half` | 目前所在半年(`H1` / `H2`) |
|
||||
| `dataVersion` | 資料版本(v1、v2…),每次定錨加一號 |
|
||||
| `anchoredAt` | 最近一次定錨時間 |
|
||||
| `calcVersion` | 計算版本,算法改變時才變(目前是 3) |
|
||||
| `calcChangelog[]` | 計算版本異動紀錄(`calcVersion`、`date`、`change`、`reason`) |
|
||||
| `generatedAt` | 這份數字算出來的時間 |
|
||||
|
||||
## 4. 數字怎麼來(解讀時要知道的規則)
|
||||
|
||||
計算版本:
|
||||
|
||||
| 版本 | 生效 | 內容 |
|
||||
|---|---|---|
|
||||
| 1 | 2026-10-28 | 初版(含夢境現實 CODA 分攤;指標 3 為 P 輕重) |
|
||||
| 2 | 2027-01 | 發票半年定錨、只增不減;部門調動依生效月份移轉發票 |
|
||||
| 3 | 2027-01 | 實際 CODA 與定錨 CODA;實習生 × 1 只進發票;工讀以外包計(日薪=時薪×8);管理職以 HR 組織主管為準 |
|
||||
|
||||
### 4.1 年度發票
|
||||
|
||||
```
|
||||
年度發票總額 = 內部人力成本 ÷ 毛利率 + 常態型外包成本 + 專案委外 + 員旅
|
||||
```
|
||||
|
||||
**年初分配(一年一次,在 1 月定錨時)**:部門佔比 = 三個指標加權(目前 P 25%/A 40%/P 輕重 35%)。
|
||||
|
||||
- 指標 1:部門 P 成本佔比。
|
||||
- 指標 2:部門 A 成本佔比。
|
||||
- 指標 3(P 輕重):P 成本 × (P 成本 ÷ A 成本),A 成本含常態型外包,再換算佔比。
|
||||
|
||||
**半年定錨、只增不減**:
|
||||
|
||||
- 一年兩個定錨點:1 月(H1)、7 月(H2)。定錨就是發布,只有負責人能操作。核心參數半年內鎖定。
|
||||
- 定錨後只看**自己部門**的變化,別的部門加人減人不影響你:
|
||||
|
||||
```
|
||||
部門全年 = 定錨全年 +(目前本部門成本 − 定錨時本部門成本)÷ 毛利率
|
||||
```
|
||||
|
||||
外包增減照「成本 × 外包倍率」,不除毛利率。
|
||||
- **只增不減**:半年內以最高點為準;加人、加薪往上,減人、減薪不會讓目標下降。
|
||||
- H1 目標 = H1 最高點 ÷ 2;H2 目標 = H2 最高點 − H1 結算。7 月重新定錨時,H1 期間的減少可以反映到 H2。
|
||||
- 部門間調動:從生效月份起,金額從原部門移到新部門,總額不變。
|
||||
- 實習生以 × 1 計入發票,但不進 CODA。
|
||||
- 範例:年初全年 10 萬 → H1 5 萬;H1 加人加薪全年變 12 萬 → H1 6 萬;H2 前又加人變 14 萬 → H2 = 14 − 6 = 8 萬。
|
||||
|
||||
### 4.2 CODA
|
||||
|
||||
```
|
||||
部門 CODA = 部門 P 成本 + A 成本(年薪 × 人薪倍率,不含外包、營運支援、實習生,不用產出率)
|
||||
平均日 CODA = 實際 CODA ÷ 年工作天數(目前 250)÷ 人數(在職月數折算)
|
||||
```
|
||||
|
||||
- 組別 CODA:依 A 成本比例分到組;研發組減 35%、CG Lead 組承擔 85%,減下來的金額再分給一般組。
|
||||
- 人數:組別只算 A;部門算 A + 常態型外包。兩者不同是刻意的設計。
|
||||
- 工讀生以外包計(日薪 = 時薪 × 8)。管理職以 HR 組織的主管為準。
|
||||
- 夢境現實:專案與場館營運部 + 公司無部門的 P(執行長),按互動技術部、互動美術部各自 CODA 比例分攤。
|
||||
- 實際 CODA:部門調動依生效月份拆分到前後單位。
|
||||
- 定錨 CODA:與發票一起在 1 月、7 月定錨,半年內只取最高點;調動時原單位不降、新單位照實增加,半年到期一起重算。
|
||||
|
||||
## 5. 使用守則
|
||||
|
||||
1. **看版本再比較**:比較兩份數字前,先看 `dataVersion`、`calcVersion`。`calcVersion` 不同時,先讀 `calcChangelog` 說明差異,不要直接相減下結論。
|
||||
2. **注意時間**:回答時附上 `generatedAt`。
|
||||
3. **分清楚兩種 CODA**:問「定價」「划不划算」用實際 CODA 的 `avgDailyCoda`;問「半年目標」用 `anchoredCoda`。回答時要講明是哪一種。
|
||||
4. **暫定值**:`h2.provisional` 或 `anchoredCoda.h2Provisional` 為 true 時,要說明這是 7 月定錨前的暫定數字。
|
||||
5. **不要自己重算或推測個人數字**:例如不要用部門金額反推個人薪資。
|
||||
6. **發票變多的原因**:只能說明 `increase` 的金額,不能說明是誰造成的(接口不提供明細);需要明細請洽 LeadBoard 負責人。
|
||||
7. **錯誤處理**(錯誤回應格式:`{ "error": "<代碼>" }`):
|
||||
|
||||
| 狀況 | 回應 | 怎麼處理 |
|
||||
|---|---|---|
|
||||
| 尚未定錨 | 503 `not_anchored` | 告知還沒有正式數字(第一次定錨在 2027 年 1 月),不要用其他來源代替 |
|
||||
| 沒帶 token | 401 `token_required` | 帶上 `Authorization: Bearer <token>` |
|
||||
| token 無效(簽章、`iss`、`aud` 不對) | 401 `invalid_token` | 確認 token 是 leadboard provider 簽發、`aud` 是 `leadboard-api`;仍失敗找 RD |
|
||||
| token 過期 | 401 `token_expired` | 重新換發 token |
|
||||
| token 有效但缺 `leadboard:read` | 403 `insufficient_scope` | 先確認操作者在 `leadboard-read` 群組,否則找 RD 開通 |
|
||||
| 不是 GET | 405 `method_not_allowed` | 只用 GET |
|
||||
| 伺服器暫時算不出來 | 503 `temporarily_unavailable` | 稍後再試 |
|
||||
| HR 暫時無法連線 | 照常回傳上一份 | 以 `generatedAt` 判斷資料時間 |
|
||||
|
||||
## 6. 回應範例(格式參考,數字為試算值)
|
||||
|
||||
`/invoice`:
|
||||
|
||||
```json
|
||||
{
|
||||
"year": 2027, "half": "H1", "dataVersion": "v1",
|
||||
"anchoredAt": "2027-01-04T10:15:00+08:00", "calcVersion": 3,
|
||||
"generatedAt": "2027-03-02T16:00:00+08:00",
|
||||
"calcChangelog": [ { "calcVersion": 3, "date": "2027-01", "change": "…", "reason": "…" } ],
|
||||
"company": "夢想創造", "invoiceTotal": 199261986,
|
||||
"departments": [
|
||||
{ "company": "夢想創造", "deptCode": "HR部門代碼", "dept": "前製部",
|
||||
"anchorAnnual": 33981798, "increase": 88889, "annual": 34070687,
|
||||
"h1": { "target": 17035344, "settled": false },
|
||||
"h2": { "target": 17035343, "provisional": true } }
|
||||
],
|
||||
"rdDeptCost": { "company": "夢想創造", "deptCode": "HR部門代碼", "dept": "研發部", "cost": 44289600 }
|
||||
}
|
||||
```
|
||||
|
||||
`/coda`(共同欄位同上,省略):
|
||||
|
||||
```json
|
||||
{
|
||||
"year": 2027, "half": "H1", "dataVersion": "v1", "calcVersion": 3,
|
||||
"companies": [
|
||||
{ "company": "夢想創造", "actualCoda": 98500000,
|
||||
"departments": [
|
||||
{ "deptCode": "HR部門代碼", "dept": "前製部",
|
||||
"actualCoda": 21000000, "avgDailyCoda": 5600,
|
||||
"anchoredCoda": { "annual": 21000000, "h1": 10500000, "h1Settled": false, "h2": 10500000, "h2Provisional": true },
|
||||
"groups": [
|
||||
{ "groupCode": "HR組別代碼", "group": "前製部_導演組",
|
||||
"actualCoda": 6200000, "avgDailyCoda": 6100,
|
||||
"anchoredCoda": { "annual": 6200000, "h1": 3100000, "h1Settled": false, "h2": 3100000, "h2Provisional": true } }
|
||||
] }
|
||||
] },
|
||||
{ "company": "夢境現實", "actualCoda": 30200000,
|
||||
"departments": [
|
||||
{ "deptCode": "HR部門代碼", "dept": "互動技術部", "actualCoda": 16100000, "avgDailyCoda": 5200,
|
||||
"anchoredCoda": { "annual": 16100000, "h1": 8050000, "h1Settled": false, "h2": 8050000, "h2Provisional": true } }
|
||||
] }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## 7. 聯絡
|
||||
|
||||
- 數字、規則、定錨:LeadBoard 負責人 walkdoggo.yeh
|
||||
- 帳號、權限、連線:RD
|
||||
@@ -1,166 +0,0 @@
|
||||
---
|
||||
name: pm-board-external-api
|
||||
description: 讀取 MoonShine PM Board 對外接口的年度發票(含 H1/H2 半年定錨)與 CODA(夢想創造、夢境現實)彙整數字,並正確解讀欄位、版本與算法。當使用者要查部門發票目標、H1/H2 目標、部門或組別的總 CODA/平均日 CODA、研發部成本,或要串接 PM Board 數字時使用。
|
||||
---
|
||||
|
||||
# PM Board 對外接口
|
||||
|
||||
PM Board(https://pm-board-vibe.moonshine-studio.net/)是 MoonShine 的人力成本與目標系統。
|
||||
這個接口提供**彙整後**的年度發票與 CODA 數字,給公司內部其他系統讀取。
|
||||
|
||||
> **狀態(2026-10-29)**:規格與認證方式都已確認(RD 2026-10-29 交接完成),接口程式尚未上線。正式網址以上線後 RD 提供的為準。
|
||||
> 正式依據是專案內的 `EXTERNAL-API-SPEC.md`;本 skill 與它不一致時,以規格文件為準。
|
||||
|
||||
## 1. 什麼時候用
|
||||
|
||||
- 查「某部門今年的發票目標是多少」「H1/H2 目標」「為什麼發票變多」。
|
||||
- 查「某部門/某組的平均日 CODA、總 CODA」。
|
||||
- 查「夢想創造或夢境現實的總 CODA」「研發部成本」。
|
||||
- 要把這些數字串進其他系統、報表、儀表板。
|
||||
|
||||
不要用這個接口找個人資料:接口**沒有**姓名、薪資、個人 CODA,也沒有個別人事異動明細。被問到時直接說明不提供。
|
||||
|
||||
## 2. 存取
|
||||
|
||||
- 只有讀取(GET),兩支網址(草案,實作時定案):
|
||||
- `GET /api/external/v1/invoice`:年度發票
|
||||
- `GET /api/external/v1/coda`:CODA
|
||||
- 認證:`Authorization: Bearer <token>`,token 由 Authentik 的 `PM Board` provider 簽發。
|
||||
- `aud`(audience):`pm-board-api`
|
||||
- `scope`:要含 `pm-board:read`
|
||||
- 效期 300 秒,過期要重新換發。
|
||||
- 誰能拿到 token:Authentik 只把 `pm-board:read` 發給群組 `pm-board-read`。
|
||||
vibe 站台(例如 morning)在自己的 `vibe.yaml` 宣告 `auth.resource_servers.pm-board`,
|
||||
平台負責換 token;因為是代表登入者呼叫,**實際操作的使用者**要在 `pm-board-read` 群組,
|
||||
不在群組的人整張 token 會被拒。非 vibe 的系統要接,由 RD 個別建立服務帳號。
|
||||
- 金鑰或 token 不可寫進程式碼、文件或對話,只放在環境變數或密鑰管理工具。
|
||||
|
||||
技術細節(JWKS、`iss`、401/403 怎麼判斷、伺服器怎麼讀 HR)見專案內的 `AUTHENTIK-HANDOFF.md`。
|
||||
|
||||
## 3. 資料內容
|
||||
|
||||
金額單位:新台幣元,四捨五入到整數。只提供**當年度**。
|
||||
|
||||
### 3.1 年度發票(只有夢想創造)
|
||||
|
||||
- `invoiceTotal`:年度發票總額 = 四個部門 `annual` 加總。
|
||||
- `departments[]`:前製部、廣告部、視效部、動畫部,每筆有:
|
||||
|
||||
| 欄位 | 意思 |
|
||||
|---|---|
|
||||
| `anchorAnnual` | 年初定錨分配到的全年金額(含部門調動移轉後的調整) |
|
||||
| `increase` | 定錨後本部門的增加金額(只增不減、以半年最高點為準) |
|
||||
| `annual` | 全年 = `anchorAnnual` + `increase` |
|
||||
| `h1.target` / `h1.settled` | 1–6 月目標;`settled: true` 表示已結算、不再變動 |
|
||||
| `h2.target` / `h2.provisional` | 7–12 月目標 = 全年 − H1 結算;`provisional: true` 表示 7 月定錨前的暫定值 |
|
||||
|
||||
- `rdDeptCost`:夢想創造研發部成本(年薪 × 人薪倍率,不除產出率)。研發部不分發票。
|
||||
- 夢境現實不承擔發票,沒有發票資料。
|
||||
|
||||
### 3.2 CODA
|
||||
|
||||
| 公司 | 公司層級 | 部門層級 | 組別層級 |
|
||||
|---|---|---|---|
|
||||
| 夢想創造 | 實際 CODA(前製、廣告、視效、動畫四部門合計) | 四部門:`actualCoda`、`avgDailyCoda`、`anchoredCoda` | 四部門底下每組:`actualCoda`、`avgDailyCoda`、`anchoredCoda` |
|
||||
| 夢境現實 | 實際 CODA(分攤後加總) | 互動技術部、互動美術部:`actualCoda`、`avgDailyCoda`、`anchoredCoda` | 不提供 |
|
||||
|
||||
- **實際 CODA**(`actualCoda`):即時計算,會隨人員、薪資變動升降。定價看它的平均日 CODA。
|
||||
- **定錨 CODA**(`anchoredCoda`):與發票一起在 1 月、7 月定錨,半年內只增不減;欄位 `annual`、`h1`、`h1Settled`、`h2`、`h2Provisional`。部門定錨=各組定錨加總。沒有平均日,也不提供全公司定錨總額。
|
||||
|
||||
- 每筆部門/組別都附公司名稱、HR 部門代碼(組別另附 HR 組別代碼)、名稱;組名是全名,例如「前製部_導演組」。
|
||||
- 組別數字已扣研發減免、CG Lead 承擔,但**不標示**哪組是研發組或 CG Lead 組。
|
||||
- 夢境現實的「專案與場館營運部」不列出(CODA 已分攤到另外兩個部門)。
|
||||
|
||||
### 3.3 共同欄位(每次回應都有)
|
||||
|
||||
| 欄位 | 意思 |
|
||||
|---|---|
|
||||
| `year` | 年度 |
|
||||
| `half` | 目前所在半年(`H1` / `H2`) |
|
||||
| `dataVersion` | 資料版本(v1、v2…),每次定錨加一號 |
|
||||
| `anchoredAt` | 最近一次定錨時間 |
|
||||
| `calcVersion` | 計算版本,算法改變時才變 |
|
||||
| `calcChangelog[]` | 計算版本異動紀錄(日期、內容、原因) |
|
||||
| `generatedAt` | 這份數字算出來的時間(約每 6 小時重算一次) |
|
||||
|
||||
## 4. 數字怎麼來(解讀時要知道的規則)
|
||||
|
||||
### 4.1 年度發票
|
||||
|
||||
```
|
||||
年度發票總額 = 內部人力成本 ÷ 毛利率 + 常態型外包成本 + 專案委外 + 員旅
|
||||
```
|
||||
|
||||
**年初分配(一年一次,在 1 月定錨時)**:部門佔比 = 三個指標加權(目前 P 25%/A 40%/P 輕重 35%)。
|
||||
|
||||
- 指標 1:部門 P 成本佔比。
|
||||
- 指標 2:部門 A 成本佔比。
|
||||
- 指標 3(P 輕重):P 成本 × (P 成本 ÷ A 成本),A 成本含常態型外包,再換算佔比。
|
||||
|
||||
**半年定錨、只增不減(計算版本 2,2027 年 1 月第一次定錨起生效)**:
|
||||
|
||||
- 一年兩個定錨點:1 月(H1)、7 月(H2)。定錨就是發布,只有負責人能操作。核心參數半年內鎖定。
|
||||
- 定錨後只看**自己部門**的變化,別的部門加人減人不影響你:
|
||||
|
||||
```
|
||||
部門全年 = 定錨全年 +(目前本部門成本 − 定錨時本部門成本)÷ 毛利率
|
||||
```
|
||||
|
||||
外包增減照「成本 × 外包倍率」,不除毛利率。
|
||||
- **只增不減**:半年內以最高點為準;加人、加薪往上,減人、減薪不會讓目標下降。
|
||||
- H1 目標 = H1 最高點 ÷ 2;H2 目標 = H2 最高點 − H1 結算。7 月重新定錨時,H1 期間的減少可以反映到 H2。
|
||||
- 部門間調動:從生效月份起,金額從原部門移到新部門,總額不變。
|
||||
- 範例:年初全年 10 萬 → H1 5 萬;H1 加人加薪全年變 12 萬 → H1 6 萬;H2 前又加人變 14 萬 → H2 = 14 − 6 = 8 萬。
|
||||
|
||||
### 4.2 CODA
|
||||
|
||||
```
|
||||
部門 CODA = 部門 P 成本 + A 成本(年薪 × 人薪倍率,不含外包、營運支援、實習生,不用產出率)
|
||||
平均日 CODA = CODA ÷ 年工作天數(目前 250)÷ 人數(在職月數折算)
|
||||
```
|
||||
|
||||
- 組別 CODA:依 A 成本比例分到組;研發組減 35%、CG Lead 組承擔 85%,減下來的金額再分給一般組。
|
||||
- 人數:組別只算 A;部門算 A + 常態型外包。兩者不同是刻意的設計。
|
||||
- 夢境現實:專案與場館營運部 + 公司無部門的 P(執行長),按互動技術部、互動美術部各自 CODA 比例分攤。
|
||||
- 實際 CODA 不套用定錨;部門調動依生效月份按月拆分。
|
||||
- 定錨 CODA 與發票同時定錨,半年內只增不減;H1=全年÷2,H2=最新全年−H1 結算;調動時原單位不降、新單位照實增加。
|
||||
- 被問「CODA」時先確認是哪一種;問定價、日費一律用實際 CODA 的平均日 CODA。
|
||||
|
||||
## 5. 使用守則
|
||||
|
||||
1. **看版本再比較**:比較兩份數字前,先看 `dataVersion`、`calcVersion`。`calcVersion` 不同時,先讀 `calcChangelog` 說明差異,不要直接相減下結論。
|
||||
2. **注意時間**:回答時附上 `generatedAt`;資料最多每 6 小時更新,不需要更頻繁地讀取。
|
||||
3. **H2 暫定值**:`h2.provisional` 為 true 時,要說明這是 7 月定錨前的暫定數字。
|
||||
4. **不要自己重算或推測個人數字**:例如不要用部門金額反推個人薪資。
|
||||
5. **發票變多的原因**:只能說明 `increase` 的金額,不能說明是誰造成的(接口不提供明細);需要明細請洽 PM Board 負責人。
|
||||
6. **錯誤處理**:
|
||||
|
||||
| 狀況 | 回應 | 怎麼處理 |
|
||||
|---|---|---|
|
||||
| 尚未定錨 | 503「尚未定錨」 | 告知還沒有正式數字,不要用其他來源代替 |
|
||||
| 沒帶 token、token 無效或過期 | 401 | 重新換發 token;仍失敗找 RD |
|
||||
| token 有效但缺 `pm-board:read` | 403 | 先確認操作者在 `pm-board-read` 群組,否則找 RD 開通 |
|
||||
| HR 暫時無法連線 | 照常回傳上一份 | 以 `generatedAt` 判斷資料時間 |
|
||||
|
||||
## 6. 回應範例(格式參考,數字為 2026-10-28 試算值)
|
||||
|
||||
```json
|
||||
{
|
||||
"year": 2027, "half": "H1", "dataVersion": "v1",
|
||||
"anchoredAt": "2027-01-04T10:15:00+08:00", "calcVersion": 2,
|
||||
"generatedAt": "2027-03-02T16:00:00+08:00",
|
||||
"company": "夢想創造", "invoiceTotal": 199261986,
|
||||
"departments": [
|
||||
{ "company": "夢想創造", "deptCode": "HR部門代碼", "dept": "前製部",
|
||||
"anchorAnnual": 33981798, "increase": 88889, "annual": 34070687,
|
||||
"h1": { "target": 17035344, "settled": false },
|
||||
"h2": { "target": 17035343, "provisional": true } }
|
||||
],
|
||||
"rdDeptCost": { "company": "夢想創造", "deptCode": "HR部門代碼", "dept": "研發部", "cost": 44289600 }
|
||||
}
|
||||
```
|
||||
|
||||
## 7. 聯絡
|
||||
|
||||
- 數字、規則、定錨:PM Board 負責人 walkdoggo.yeh
|
||||
- 帳號、權限、連線:RD
|
||||
+96
@@ -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),
|
||||
};
|
||||
}
|
||||
@@ -77,3 +77,40 @@ test('anchor store: H1 once, H2 after H1, H2 stores the H1 settlement', async ()
|
||||
assert.equal(h2.invoice.X.h2, 300);
|
||||
assert.equal(h2.coda.X.h1, 500);
|
||||
});
|
||||
|
||||
test('change list, peak reset with restore, and undoing the latest anchor', async () => {
|
||||
const store = createAnchorStore(null);
|
||||
const m = model(base, coda(500, 500, 400));
|
||||
await store.anchor(m, { year: 2027, half: 'H1', note: 'jan', by: 't' });
|
||||
const raised = model([person('a', 'X', 'g1', 'A - 藝術家', 110), base[1], base[2], person('d', 'Y', 'h1', 'A - 藝術家', 50)], coda(550, 500, 450));
|
||||
const ev = await store.evaluate(raised, 2027);
|
||||
assert.deepEqual(ev.changes.map(c => c.type).sort(), ['cost', 'new']);
|
||||
assert.equal(ev.changes.find(c => c.type === 'new').invoiceDelta, Math.round(600 / 0.8));
|
||||
const peak = ev.invoice.X.peak;
|
||||
assert.ok(peak > 0);
|
||||
await assert.rejects(store.resetPeak({ year: 2027, kind: 'invoice', key: 'X', reason: ' ', by: 't' }), /reason/);
|
||||
const { id } = await store.resetPeak({ year: 2027, kind: 'invoice', key: 'X', reason: '打錯', by: 't' });
|
||||
assert.equal((await store.evaluate(m, 2027)).invoice.X.peak, 0);
|
||||
await store.restorePeak({ year: 2027, id, by: 't' });
|
||||
assert.equal((await store.evaluate(m, 2027)).invoice.X.peak, peak);
|
||||
await store.undoAnchor({ year: 2027, reason: '按錯', by: 't' });
|
||||
const after = await store.evaluate(m, 2027);
|
||||
assert.equal(after.active, null);
|
||||
await store.anchor(m, { year: 2027, half: 'H1', note: 'again', by: 't' });
|
||||
assert.equal((await store.evaluate(m, 2027)).active.version, 2);
|
||||
});
|
||||
|
||||
test('actual CODA split by transfer month; snapshots and change lists merge the two parts back', async () => {
|
||||
const { splitTransfers, mergedPeople } = await import('../anchor-calc.js');
|
||||
const p = { employeeNumber: 'b', name: 'b', dept: 'Y', group: 'h1', role: 'A - 藝術家', h1Start: 1, h1End: 6, h2Start: 7, h2End: 12, row: 'b', monthlyCost: months(100), totalCost: 1200 };
|
||||
const parts = splitTransfers([p], [{ key: 'hr:b', from: { dept: 'X', group: 'g2' }, month: 4 }]);
|
||||
assert.equal(parts.length, 2);
|
||||
assert.deepEqual([parts[0].dept, parts[0].h1Start, parts[0].h1End, parts[0].h2Start], ['X', 1, 3, '']);
|
||||
assert.deepEqual([parts[1].dept, parts[1].h1Start, parts[1].h1End, parts[1].h2Start, parts[1].h2End], ['Y', 4, 6, 7, 12]);
|
||||
const merged = mergedPeople([{ ...parts[0], monthlyCost: [100, 100, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0], totalCost: 300 }, { ...parts[1], monthlyCost: [0, 0, 0, 100, 100, 100, 100, 100, 100, 100, 100, 100], totalCost: 900 }]);
|
||||
const e = merged.get('hr:b');
|
||||
assert.equal(e.person.dept, 'Y');
|
||||
assert.equal(e.pa.reduce((a, b) => a + b, 0), 1200);
|
||||
const people = [p];
|
||||
assert.equal(splitTransfers(people, []), people);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { computeModel } from '../calc-engine.js';
|
||||
import { createAnchorStore } from '../anchor-store.js';
|
||||
import { buildArchive, createArchiveStore } from '../archive-store.js';
|
||||
|
||||
test('a year archive keeps department and group figures only and cannot be overwritten', async () => {
|
||||
const data = JSON.parse(await readFile(new URL('../seed/demo.json', import.meta.url), 'utf8'));
|
||||
const model = computeModel(data);
|
||||
const anchors = createAnchorStore(null);
|
||||
await anchors.anchor(model, { year: 2027, half: 'H1', note: 'jan', by: 't' });
|
||||
await anchors.anchor(model, { year: 2027, half: 'H2', note: 'jul', by: 't' });
|
||||
const archive = buildArchive(model, await anchors.evaluate(model, 2027), { year: 2027, by: 't', note: 'year end', at: 'now' });
|
||||
const text = JSON.stringify(archive);
|
||||
for (const p of model.people) if (p.name) assert.ok(!text.includes(`"${p.name}"`));
|
||||
assert.deepEqual(archive.anchors.map(a => a.half), ['H1', 'H2']);
|
||||
const store = createArchiveStore(null);
|
||||
await store.save(archive);
|
||||
assert.deepEqual(await store.list(), [2027]);
|
||||
await assert.rejects(store.save(archive), /already archived/);
|
||||
assert.equal((await store.get(2027)).note, 'year end');
|
||||
});
|
||||
@@ -39,3 +39,58 @@ test('interns count salary × 1 in the invoice only, never in CODA; 工讀生 co
|
||||
assert.equal(withPartTime.coda[dept], without.coda[dept]);
|
||||
assert.ok(withPartTime.invoice.totalO > 0);
|
||||
});
|
||||
|
||||
test('a group that is both 研發 and CG Lead gets both reductions; groups still add up to the department', async () => {
|
||||
const synthetic = JSON.parse(await readFile(new URL('../seed/demo.json', import.meta.url), 'utf8'));
|
||||
const dept = Object.keys(computeModel(synthetic).coda)[0];
|
||||
const person = (name, group, salary) => ({ name, title: 'Artist', role: 'A - 藝術家', dept, group, company: '夢想創造', salary, h1Start: 1, h1End: 6, h2Start: 7, h2End: 12 });
|
||||
const globalParams = { ...synthetic.globalParams, rdGroups: [`${dept}|R`], cgLeadGroups: [`${dept}|R`], rdReductionPct: 0.35, cgLeadReductionPct: 0.85 };
|
||||
const model = computeModel({ baseData: [person('a', 'R', 50000), person('b', 'N', 50000)], globalParams });
|
||||
const groups = model.codaGroups[dept].groups;
|
||||
const initial = model.codaGroups[dept].coda / 2;
|
||||
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 === '業務部'));
|
||||
});
|
||||
|
||||
@@ -142,3 +142,10 @@ test('hire and leave dates inside the report year limit the active months', asyn
|
||||
assert.equal(person.h1Start, 5);
|
||||
assert.equal(person.employmentBounded, true);
|
||||
});
|
||||
|
||||
test('after the first year the default months are the full year', () => {
|
||||
const person = toCostPerson({ employeeNumber: 'Y1' }, { salaryType: 'monthly', amount: 50000 }, { role: 'A - 藝術家' }, { year: 2028, fullYearDefault: true });
|
||||
assert.deepEqual([person.h1Start, person.h1End, person.h2Start, person.h2End], [1, 6, 7, 12]);
|
||||
const first = toCostPerson({ employeeNumber: 'Y1' }, { salaryType: 'monthly', amount: 50000 }, { role: 'A - 藝術家' }, { year: 2027 });
|
||||
assert.equal(first.h2Start, '');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { generateKeyPairSync, sign } from 'node:crypto';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { computeModel } from '../calc-engine.js';
|
||||
import { createAnchorStore } from '../anchor-store.js';
|
||||
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/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: '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] });
|
||||
|
||||
test('bearer tokens: valid passes; wrong audience, expired, missing scope and no token are refused', async () => {
|
||||
const ok = await verifyApiToken(token({}), { issuer, getKeys });
|
||||
assert.equal(ok.actorType, 'service');
|
||||
const status = async (auth) => { try { await verifyApiToken(auth, { issuer, getKeys }); return 200; } catch (e) { assert.ok(e instanceof ApiError); return e.status; } };
|
||||
assert.equal(await status(undefined), 401);
|
||||
assert.equal(await status(token({ aud: 'other' })), 401);
|
||||
assert.equal(await status(token({ exp: 1 })), 401);
|
||||
assert.equal(await status(token({ iss: 'https://evil.test/' })), 401);
|
||||
assert.equal(await status(token({ scope: 'openid' })), 403);
|
||||
assert.equal(await status(token({}, 'unknown')), 401);
|
||||
});
|
||||
|
||||
test('external data: 503 before the first anchor; afterwards totals add up and no personal data is included', async () => {
|
||||
const data = JSON.parse(await readFile(new URL('../seed/demo.json', import.meta.url), 'utf8'));
|
||||
const model = computeModel(data);
|
||||
const store = createAnchorStore(null);
|
||||
assert.throws(() => buildExternal(model, { active: null }), e => e.status === 503 && e.code === 'not_anchored');
|
||||
await store.anchor(model, { year: 2027, half: 'H1', note: 'test', by: 't' });
|
||||
const anchors = await store.evaluate(model, 2027);
|
||||
const { invoice, coda } = buildExternal(model, anchors);
|
||||
assert.equal(invoice.dataVersion, 'v1');
|
||||
assert.equal(invoice.calcVersion, 3);
|
||||
assert.equal(invoice.invoiceTotal, invoice.departments.reduce((s, d) => s + d.annual, 0));
|
||||
for (const d of invoice.departments) assert.equal(d.h1.target + d.h2.target, d.annual);
|
||||
const text = JSON.stringify({ invoice, coda });
|
||||
for (const p of model.people) if (p.name) assert.ok(!text.includes(`"${p.name}"`), p.name);
|
||||
assert.ok(!text.includes('salary'));
|
||||
assert.equal(coda.companies[0].company, '夢想創造');
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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: [] })), []);
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createPermissionStore, hasAnyScope, resolvePermissions } from '../permissions.js';
|
||||
import { buildScopedView, invoiceBreakdown } from '../scope-view.js';
|
||||
import { computeModel } from '../calc-engine.js';
|
||||
import { readFileSync } from 'node:fs';
|
||||
const seedData = JSON.parse(readFileSync(new URL('../seed/demo.json', import.meta.url), 'utf8'));
|
||||
|
||||
const organizations = [
|
||||
{ deptCode: 'C', deptName: '公司', levelName: '公司' },
|
||||
{ deptCode: 'D1', deptName: '前製部', levelName: '部', upperDeptCode: 'C' },
|
||||
{ deptCode: 'G1', deptName: '設計組', levelName: '組', upperDeptCode: 'D1' },
|
||||
{ deptCode: 'D2', deptName: '動畫部', levelName: '部', upperDeptCode: 'C' },
|
||||
];
|
||||
const supervisors = new Map([
|
||||
['100', [{ deptCode: 'D1', deptName: '前製部', levelName: '部' }]],
|
||||
['200', [{ deptCode: 'G1', deptName: '設計組', levelName: '組' }]],
|
||||
['20240407', [{ deptCode: 'D2', deptName: '動畫部', levelName: '部' }]],
|
||||
]);
|
||||
|
||||
test('HR supervisors get department or group scopes; defaults for company viewers and the paused account', async () => {
|
||||
const store = await createPermissionStore(null).load();
|
||||
const head = resolvePermissions('100', { supervisors, organizations, store });
|
||||
assert.deepEqual(head.depts, ['前製部']);
|
||||
assert.equal(head.personDetail, true);
|
||||
assert.equal(head.simulate, true);
|
||||
const lead = resolvePermissions('200', { supervisors, organizations, store });
|
||||
assert.deepEqual(lead.groups, ['前製部|設計組']);
|
||||
assert.equal(lead.personDetail, false);
|
||||
assert.equal(resolvePermissions('20120201', { supervisors, organizations, store }).company, true);
|
||||
assert.equal(hasAnyScope(resolvePermissions('20240407', { supervisors, organizations, store })), false);
|
||||
assert.equal(hasAnyScope(resolvePermissions('999', { supervisors, organizations, store })), false);
|
||||
assert.equal(resolvePermissions('20150906', { supervisors, organizations, store }).admin, true);
|
||||
});
|
||||
|
||||
test('HR scopes disappear with the HR role; manual grants stay until removed', async () => {
|
||||
const permissions = createPermissionStore(null);
|
||||
await permissions.set({ employeeNumber: '200', grant: { personDetail: true }, by: 'admin' });
|
||||
const store = await permissions.load();
|
||||
const noLongerLead = resolvePermissions('200', { supervisors: new Map(), organizations, store });
|
||||
assert.deepEqual(noLongerLead.groups, []);
|
||||
assert.equal(noLongerLead.personDetail, true);
|
||||
await permissions.set({ employeeNumber: '200', grant: null, by: 'admin' });
|
||||
assert.equal(resolvePermissions('200', { supervisors: new Map(), organizations, store: await permissions.load() }).personDetail, false);
|
||||
await assert.rejects(permissions.set({ employeeNumber: '20150906', grant: {}, by: 'admin' }));
|
||||
});
|
||||
|
||||
test('the scoped view only contains what the person may see', () => {
|
||||
const person = (name, dept, group, salary) => ({ name, dept, group, role: 'A - 藝術家', salary, totalCost: salary * 12 });
|
||||
const model = {
|
||||
people: [person('a', '前製部', '設計組', 100), person('b', '前製部', '概念組', 200), person('c', '動畫部', '動畫組', 300)],
|
||||
invoice: { finalInvoiceTotal: 1000 },
|
||||
allocations: { deptData: { 前製部: { finalPct: 0.4 }, 動畫部: { finalPct: 0.6 } } },
|
||||
codaGroups: {
|
||||
前製部: { coda: 30, avgDailyCoda: 1, groups: { 設計組: { coda: 10, avgDailyCoda: 1, people: ['a'] }, 概念組: { coda: 20, avgDailyCoda: 2, people: ['b'] } } },
|
||||
動畫部: { coda: 40, avgDailyCoda: 3, groups: { 動畫組: { coda: 40, avgDailyCoda: 3, people: ['c'] } } },
|
||||
},
|
||||
};
|
||||
const lead = buildScopedView(model, null, { employeeNumber: '200', depts: [], groups: ['前製部|設計組'], personDetail: false });
|
||||
const text = JSON.stringify(lead);
|
||||
assert.equal(lead.depts.length, 1);
|
||||
assert.equal(lead.depts[0].full, false);
|
||||
assert.deepEqual(lead.depts[0].groups.map(g => g.group), ['設計組']);
|
||||
assert.ok(!text.includes('動畫部') && !text.includes('概念組') && !text.includes('"salary"'));
|
||||
assert.equal(lead.company, null);
|
||||
const head = buildScopedView(model, null, { employeeNumber: '100', depts: ['前製部'], groups: [], personDetail: true });
|
||||
assert.equal(head.depts[0].invoice.annual, 400);
|
||||
assert.equal(head.depts[0].people.length, 2);
|
||||
assert.ok(!JSON.stringify(head).includes('動畫部'));
|
||||
});
|
||||
|
||||
test('department viewers get multiplier, invoice share with H1/H2, three indicators, headcount by kind and total cost', () => {
|
||||
const model = computeModel(seedData);
|
||||
const dept = Object.keys(model.codaGroups)[0];
|
||||
const head = buildScopedView(model, null, { employeeNumber: '100', depts: [dept], groups: [], personDetail: false });
|
||||
const row = head.depts[0];
|
||||
const multiplier = model.multiplierUnits.find(u => u.label === dept);
|
||||
assert.equal(row.multiplier.value, Math.round(multiplier.multiplier * model.opMultiplier * 100) / 100);
|
||||
assert.equal(row.headcount.total, model.people.filter(p => (p.dept || '').trim() === dept).length);
|
||||
assert.ok(row.totalCost > 0);
|
||||
assert.ok(row.groups.every(g => typeof g.totalCost === 'number'));
|
||||
const group = row.groups[0].group;
|
||||
const lead = buildScopedView(model, null, { employeeNumber: '200', depts: [], groups: [`${dept}|${group}`], personDetail: false });
|
||||
assert.equal(lead.depts[0].groups[0].totalCost, row.groups[0].totalCost);
|
||||
assert.equal(lead.depts[0].totalCost, undefined);
|
||||
assert.equal(lead.depts[0].multiplier, undefined);
|
||||
// 出發票的部門:佔比、上下半年、三個指標。
|
||||
const invoiceModel = { invoice: { finalInvoiceTotal: 1001 }, allocations: { wP: 0.25, wA: 0.4, wS: 0.35, overallRatio: 2.5, deptData: { X: { finalPct: 0.5, m1: 0.4, m2: 0.6, m3: 0.5, costRatio: 3 } } } };
|
||||
const breakdown = invoiceBreakdown(invoiceModel, 'X');
|
||||
assert.equal(breakdown.annual, 501);
|
||||
assert.equal(breakdown.h1 + breakdown.h2, breakdown.annual);
|
||||
assert.equal(breakdown.indicators.a.value, 0.6);
|
||||
assert.equal(breakdown.indicators.s.weight, 0.35);
|
||||
assert.equal(breakdown.indicators.apRatio, 3);
|
||||
assert.equal(invoiceBreakdown(invoiceModel, 'Y'), null);
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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), []);
|
||||
});
|
||||
+188
-14
@@ -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);
|
||||
});
|
||||
|
||||
@@ -319,3 +339,157 @@ test('RD / CG flags and parameters saved on the board persist across restarts',
|
||||
assert.equal(globalParams.cgLeadReductionPct, 0.8);
|
||||
assert.equal(typeof globalParams.opMultiplier, 'number');
|
||||
});
|
||||
|
||||
// 假的公司登入伺服器:登入的人由 who.employee 決定。
|
||||
async function fakeProvider(t, who) {
|
||||
const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
|
||||
const key = { ...publicKey.export({ format: 'jwk' }), kid: 'test-key' };
|
||||
const state = { nonce: null, issuer: null };
|
||||
const provider = createServer((req, res) => {
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
if (req.url === '/.well-known/openid-configuration') {
|
||||
return res.end(JSON.stringify({ authorization_endpoint: `${state.issuer}/authorize`, token_endpoint: `${state.issuer}/token`, jwks_uri: `${state.issuer}/keys`, end_session_endpoint: `${state.issuer}/end-session` }));
|
||||
}
|
||||
if (req.url === '/keys') return res.end(JSON.stringify({ keys: [key] }));
|
||||
if (req.url === '/token' && req.method === 'POST') {
|
||||
let body = '';
|
||||
req.on('data', chunk => { body += chunk; });
|
||||
req.on('end', () => {
|
||||
const form = new URLSearchParams(body);
|
||||
if (form.get('grant_type') !== 'authorization_code') return res.end(JSON.stringify({ access_token: 'hr-token', expires_in: 300 }));
|
||||
const encode = value => Buffer.from(JSON.stringify(value)).toString('base64url');
|
||||
const signed = `${encode({ alg: 'RS256', kid: key.kid })}.${encode({
|
||||
iss: state.issuer, aud: 'test-client', exp: Math.floor(Date.now() / 1000) + 300,
|
||||
nonce: state.nonce, employee_number: who.employee, name: `User ${who.employee}`,
|
||||
})}`;
|
||||
res.end(JSON.stringify({ id_token: `${signed}.${sign('RSA-SHA256', Buffer.from(signed), privateKey).toString('base64url')}`,
|
||||
access_token: 'login-token', refresh_token: 'refresh-token', expires_in: 3600 }));
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (req.url === '/employees?status=ACTIVE') return res.end(JSON.stringify([
|
||||
{ employeeNumber: '20150906', name: 'Admin', departmentCode: 'G1', status: 'ACTIVE' },
|
||||
{ employeeNumber: '30000001', name: 'Staff', departmentCode: 'G1', status: 'ACTIVE' },
|
||||
]));
|
||||
if (req.url === '/organizations?flat=1') return res.end(JSON.stringify([
|
||||
{ deptCode: 'C1', deptName: 'Test company', levelName: '公司' },
|
||||
{ deptCode: 'D1', deptName: '製作部', upperDeptCode: 'C1', levelName: '部' },
|
||||
{ deptCode: 'G1', deptName: '製作組', upperDeptCode: 'D1', levelName: '組' },
|
||||
]));
|
||||
res.writeHead(404).end();
|
||||
});
|
||||
await new Promise(resolve => provider.listen(0, '127.0.0.1', resolve));
|
||||
state.issuer = `http://127.0.0.1:${provider.address().port}`;
|
||||
t.after(() => provider.close());
|
||||
return state;
|
||||
}
|
||||
|
||||
async function signIn(base, provider) {
|
||||
const login = await fetch(`${base}/api/auth/login`, { redirect: 'manual' });
|
||||
const authorize = new URL(login.headers.get('location'));
|
||||
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: `leadboard_login=${loginState}` },
|
||||
});
|
||||
const cookie = callback.headers.getSetCookie().find(value => value.startsWith('leadboard_session='))?.split(';')[0];
|
||||
return { callback, cookie };
|
||||
}
|
||||
|
||||
test('login flow: any company account gets in; only the top admin reaches the board and admin functions', async (t) => {
|
||||
const dataDir = await mkdtemp(join(tmpdir(), 'pm-board-login-'));
|
||||
t.after(() => rm(dataDir, { recursive: true, force: true }));
|
||||
const who = { employee: '30000001' };
|
||||
const provider = await fakeProvider(t, who);
|
||||
const port = '18086';
|
||||
const base = `http://127.0.0.1:${port}`;
|
||||
const env = { PORT: port, HOST: '127.0.0.1', NODE_ENV: 'production',
|
||||
OIDC_ISSUER: provider.issuer, OIDC_CLIENT_ID: 'test-client', OIDC_CLIENT_SECRET: 'test-secret', COST_MODEL_DATA_DIR: dataDir,
|
||||
RESOURCE_SERVERS: JSON.stringify({ 'hr-sync': { audience: 'hr-sync-api', base_url: provider.issuer,
|
||||
required_scopes: ['hr-sync-api', 'employee_number'], scopes: ['hr:read', 'hr:salary:read'] } }) };
|
||||
let child = start(env);
|
||||
t.after(() => child.kill());
|
||||
await waitFor(`${base}/api/health`);
|
||||
|
||||
// 一般同仁:登得進來,被帶到 /my;主看板、管理功能、全公司資料都擋住。
|
||||
const staff = await signIn(base, provider);
|
||||
assert.equal(staff.callback.status, 302);
|
||||
assert.equal(staff.callback.headers.get('location'), '/my');
|
||||
const headers = { cookie: staff.cookie };
|
||||
assert.equal((await fetch(`${base}/my`, { headers })).status, 200);
|
||||
for (const page of ['/', '/permissions', '/archive']) {
|
||||
const response = await fetch(`${base}${page}`, { headers, redirect: 'manual' });
|
||||
assert.equal(response.status, 302, page);
|
||||
assert.equal(response.headers.get('location'), '/my', page);
|
||||
}
|
||||
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'], ['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}`);
|
||||
}
|
||||
const scope = await fetch(`${base}/api/scope`, { headers });
|
||||
assert.equal(scope.status, 403);
|
||||
assert.equal((await scope.json()).error, 'no_permission');
|
||||
assert.equal((await fetch(`${base}/api/simulate`, { method: 'POST', headers: { ...headers, 'content-type': 'application/json' }, body: JSON.stringify({ dept: '製作部' }) })).status, 403);
|
||||
// /my 的登出可以轉到公司登入伺服器(form-action 有允許)。
|
||||
assert.match((await fetch(`${base}/my`, { headers })).headers.get('content-security-policy'), new RegExp(`form-action 'self' ${provider.issuer.replace(/[.]/g, '\\.')}`));
|
||||
|
||||
// 最高管理者:進主看板。
|
||||
who.employee = '20150906';
|
||||
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);
|
||||
// 權限管理搬進主看板後,舊網址導回看板並直接打開那個區塊。
|
||||
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 = 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);
|
||||
assert.equal((await fetch(`${base}/`, { headers: { cookie: admin.cookie }, redirect: 'manual' })).status, 200);
|
||||
assert.equal((await fetch(`${base}/my`, { headers, redirect: 'manual' })).status, 200);
|
||||
|
||||
// 登出後,重新啟動也不會復活。
|
||||
assert.equal((await fetch(`${base}/api/auth/logout`, { method: 'POST', redirect: 'manual', headers: { cookie: staff.cookie, origin: `https://127.0.0.1:${port}` } })).status, 302);
|
||||
child.kill('SIGTERM');
|
||||
await new Promise(resolve => child.once('exit', resolve));
|
||||
child = start(env);
|
||||
await waitFor(`${base}/api/health`);
|
||||
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');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
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, 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, 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, 'REFRESH-TOKEN-VALUE');
|
||||
assert.equal(restarted.get('old-cookie'), undefined);
|
||||
|
||||
// 登出後重新啟動,也不會回來。
|
||||
restarted.delete('raw-cookie-value');
|
||||
restarted.flush();
|
||||
assert.equal(createSessionStore(path, { now: () => clock, secret: SECRET }).load(), 0);
|
||||
|
||||
// 過期的不載入。
|
||||
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, secret: SECRET }).load(), 0);
|
||||
});
|
||||
|
||||
test('without a data folder (local preview) sessions stay in memory only', () => {
|
||||
const store = createSessionStore(null);
|
||||
store.set('a', { claims: {}, expiresAt: Date.now() + 1000 });
|
||||
assert.equal(store.load(), 0);
|
||||
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'));
|
||||
});
|
||||
@@ -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, []);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { computeModel } from '../calc-engine.js';
|
||||
import { applySimulation, compareDept, simulatedPerson } from '../simulate.js';
|
||||
|
||||
const seed = JSON.parse(await readFile(new URL('../seed/demo.json', import.meta.url), 'utf8'));
|
||||
const dept = Object.keys(computeModel(seed).codaGroups).find(d => computeModel(seed).codaGroups[d].coda > 0);
|
||||
|
||||
test('simulated people: 工讀 is O with day rate = hourly × 8; interns are A with the Intern title', () => {
|
||||
const where = { dept: 'X', company: 'C' };
|
||||
const partTime = simulatedPerson({ kind: 'parttime', salaryType: 'hourly', amount: 200, h1Start: 1, h1End: 6 }, where, 0);
|
||||
assert.equal(partTime.role, 'O - 外包');
|
||||
assert.equal(partTime.dayrate, 1600);
|
||||
const intern = simulatedPerson({ kind: 'intern', salaryType: 'monthly', amount: 30000, h1Start: 1, h1End: 6 }, where, 1);
|
||||
assert.equal(intern.title, 'Intern');
|
||||
assert.throws(() => simulatedPerson({ kind: 'A', salaryType: 'monthly', amount: 1, h1Start: 7, h1End: 6 }, where, 2));
|
||||
assert.throws(() => simulatedPerson({ kind: 'boss', salaryType: 'monthly', amount: 1 }, where, 3));
|
||||
});
|
||||
|
||||
test('adding an artist raises the department CODA; an O does not; the original data is untouched', () => {
|
||||
const before = JSON.stringify(seed);
|
||||
const base = computeModel(seed);
|
||||
const withA = computeModel(applySimulation(seed, dept, { additions: [{ kind: 'A', salaryType: 'monthly', amount: 50000, h1Start: 1, h1End: 6, h2Start: 7, h2End: 12 }] }));
|
||||
const withO = computeModel(applySimulation(seed, dept, { additions: [{ kind: 'O', salaryType: 'daily', amount: 3000, h1Start: 1, h1End: 6 }] }));
|
||||
assert.ok(withA.codaGroups[dept].coda > base.codaGroups[dept].coda);
|
||||
assert.equal(withO.codaGroups[dept].coda, base.codaGroups[dept].coda);
|
||||
assert.equal(JSON.stringify(seed), before);
|
||||
const result = compareDept(base, withA, null, null, dept);
|
||||
assert.ok(result.rows.find(r => r.key === 'actualCoda').delta > 0);
|
||||
assert.equal(result.anchored, false);
|
||||
});
|
||||
|
||||
test('the comparison includes the multiplier, the invoice share and group headcount', () => {
|
||||
const base = computeModel(seed);
|
||||
const group = Object.keys(base.codaGroups[dept].groups)[0];
|
||||
const after = computeModel(applySimulation(seed, dept, { additions: [{ kind: 'A', group, salaryType: 'monthly', amount: 50000, h1Start: 1, h1End: 6, h2Start: 7, h2End: 12 }] }));
|
||||
const result = compareDept(base, after, null, null, dept);
|
||||
const multiplier = result.rows.find(r => r.key === 'multiplier');
|
||||
assert.ok(multiplier.before > 0 && multiplier.after > 0);
|
||||
assert.ok(result.rows.some(r => r.key === 'invoiceShare'));
|
||||
const g = result.groups.find(x => x.group === group);
|
||||
assert.equal(g.after.headcount - g.before.headcount, 1);
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
Reference in New Issue
Block a user