Compare commits
47
Commits
+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 scope-ui.js i18n.js 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 permissions.html archive.html 2022_Moonshine_Logo_MS_logo_w_EN.png ./
|
||||
COPY --chown=node:node package.json server.js access.js hr-sync.js hr-org.js cost-model.js contractor-store.js settings-store.js calc-core.js scope-ui.js i18n.js buttons.css english-names.js plans.js calc-engine.js anchor-calc.js anchor-store.js permissions.js scope-view.js simulate.js external-api.js archive-store.js session-store.js storage.js db.js import-json.js data-store.js index.html my.html archive.html 2022_Moonshine_Logo_MS_logo_w_EN.png ./
|
||||
COPY --chown=node:node seed ./seed
|
||||
COPY --chown=node:node fonts ./fonts
|
||||
RUN mkdir -p /app/data && chown node:node /app/data
|
||||
|
||||
@@ -27,6 +27,7 @@ button { font:inherit; border:1px solid var(--line); background:var(--card); col
|
||||
button:focus-visible, a:focus-visible, input:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }
|
||||
.warn { color:var(--warn); }
|
||||
</style>
|
||||
<link rel="stylesheet" href="/buttons.css">
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
|
||||
+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;
|
||||
}
|
||||
}
|
||||
+34
-5
@@ -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);
|
||||
|
||||
+377
-10
@@ -1808,8 +1808,67 @@
|
||||
.nav-item svg { width: 15px; height: 15px; }
|
||||
.sidebar-account .user-sub, .sidebar-account small { display: none; }
|
||||
}
|
||||
/* 權限管理:版面沿用原本獨立頁的設計,顏色改吃看板的變數;選擇器全部鎖在 #permissions 底下,不影響其他區塊。 */
|
||||
#permissions {
|
||||
--card: var(--surface); --raised: var(--wash-2); --text: var(--text-main);
|
||||
--muted: var(--text-muted); --dim: var(--text-dim); --bg: var(--surface);
|
||||
--accent: var(--accent-primary-text); --accent-soft: color-mix(in srgb, var(--accent-primary-text) 16%, transparent);
|
||||
--warn: var(--accent-warning); --warn-soft: color-mix(in srgb, var(--accent-warning) 16%, transparent);
|
||||
--good: var(--accent-success); --good-soft: color-mix(in srgb, var(--accent-success) 16%, transparent);
|
||||
}
|
||||
#permissions .lead { color:var(--muted); font-size:.88rem; margin:0 0 20px; max-width:760px; }
|
||||
#permissions .rules { display:grid; grid-template-columns:repeat(auto-fit, minmax(220px, 1fr)); gap:10px; margin-bottom:22px; }
|
||||
#permissions .rule { background:var(--card); border:1px solid var(--line); border-radius:12px; padding:12px 14px; font-size:.82rem; color:var(--muted); }
|
||||
#permissions .rule b { display:block; color:var(--text); font-size:.9rem; margin-bottom:2px; }
|
||||
#permissions .toolbar { display:flex; gap:10px; flex-wrap:wrap; align-items:center; margin-bottom:12px; }
|
||||
#permissions .search { flex:1; min-width:220px; font:inherit; padding:9px 12px; border:1px solid var(--line); border-radius:10px; background:var(--card); color:var(--text); }
|
||||
#permissions .tabs { display:flex; gap:6px; flex-wrap:wrap; }
|
||||
#permissions .tab { font:inherit; font-size:.82rem; border:1px solid var(--line); background:var(--card); color:var(--muted); border-radius:99px; padding:5px 12px; cursor:pointer; }
|
||||
#permissions .tab[aria-pressed="true"] { background:var(--text); color:var(--bg); border-color:var(--text); }
|
||||
#permissions .tab .n { opacity:.7; margin-left:4px; font-variant-numeric:tabular-nums; }
|
||||
#permissions .list { background:var(--card); border:1px solid var(--line); border-radius:14px; overflow:hidden; }
|
||||
#permissions .row { display:grid; grid-template-columns: minmax(170px, 1.1fr) minmax(130px, .8fr) minmax(220px, 1.6fr) 72px; gap:14px; align-items:center; padding:12px 16px; border-top:1px solid var(--line); }
|
||||
#permissions .row:first-child { border-top:0; }
|
||||
#permissions .who b { display:block; font-size:.95rem; }
|
||||
#permissions .who span, #permissions .where span { color:var(--dim); font-size:.78rem; }
|
||||
#permissions .where { font-size:.86rem; }
|
||||
#permissions .chips { display:flex; flex-wrap:wrap; gap:5px; }
|
||||
#permissions .chip { font-size:.75rem; padding:2px 9px; border-radius:99px; background:var(--raised); border:1px solid var(--line); color:var(--muted); white-space:nowrap; }
|
||||
#permissions .chip.hr { background:var(--accent-soft); border-color:transparent; color:var(--accent); }
|
||||
#permissions .chip.manual { background:var(--good-soft); border-color:transparent; color:var(--good); }
|
||||
#permissions .chip.warn { background:var(--warn-soft); border-color:transparent; color:var(--warn); }
|
||||
#permissions .chip.admin { background:var(--text); color:var(--bg); border-color:transparent; }
|
||||
#permissions .chip.old { opacity:.55; text-decoration:line-through; }
|
||||
#permissions .none { color:var(--dim); font-size:.78rem; }
|
||||
#permissions .act { text-align:right; }
|
||||
#permissions .btn { font:inherit; font-size:.82rem; border:1px solid var(--line); background:var(--card); color:var(--text); border-radius:10px; padding:6px 12px; cursor:pointer; }
|
||||
#permissions .btn:hover { background:var(--raised); }
|
||||
#permissions .btn.primary { background:var(--accent); border-color:var(--accent); color:var(--surface); }
|
||||
#permissions .editor { grid-column:1 / -1; display:grid; gap:14px; padding:14px; margin-top:4px; background:var(--raised); border:1px solid var(--line); border-radius:12px; }
|
||||
#permissions .editor h4 { margin:0 0 8px; font-size:.85rem; color:var(--muted); font-weight:600; }
|
||||
#permissions .toggles { display:grid; grid-template-columns:repeat(auto-fit, minmax(210px, 1fr)); gap:8px; }
|
||||
#permissions .toggle { display:flex; gap:8px; align-items:flex-start; font-size:.85rem; cursor:pointer; }
|
||||
#permissions .toggle small { display:block; color:var(--dim); font-size:.75rem; }
|
||||
#permissions .pick { display:flex; flex-wrap:wrap; gap:6px 14px; font-size:.82rem; }
|
||||
#permissions .pick label { display:inline-flex; gap:5px; align-items:center; white-space:nowrap; }
|
||||
#permissions .actions { display:flex; gap:8px; justify-content:flex-end; align-items:center; }
|
||||
#permissions .status { color:var(--good); font-size:.8rem; margin-right:auto; }
|
||||
#permissions .empty { padding:28px 16px; text-align:center; color:var(--dim); font-size:.85rem; }
|
||||
#permissions .log { background:var(--card); border:1px solid var(--line); border-radius:14px; overflow:hidden; }
|
||||
#permissions .log-row { display:grid; grid-template-columns:150px minmax(130px,1fr) minmax(220px,2fr) minmax(130px,1fr); gap:12px; align-items:center; padding:10px 16px; border-top:1px solid var(--line); font-size:.82rem; }
|
||||
#permissions .log-row:first-child { border-top:0; }
|
||||
#permissions .log-row time, #permissions .log-row .by { color:var(--dim); font-variant-numeric:tabular-nums; }
|
||||
#permissions .change { display:flex; flex-wrap:wrap; gap:5px; align-items:center; }
|
||||
#permissions .arrow { color:var(--dim); }
|
||||
@media (max-width: 820px) {
|
||||
#permissions .row, #permissions .log-row { grid-template-columns:1fr 1fr; }
|
||||
#permissions .row > .chips, #permissions .log-row > .change { grid-column:1 / -1; }
|
||||
#permissions .where br { display:none; }
|
||||
#permissions .where span:not(:empty)::before { content:' · '; }
|
||||
}
|
||||
</style>
|
||||
|
||||
<link rel="stylesheet" href="/buttons.css">
|
||||
</head>
|
||||
|
||||
<body class="mode-admin">
|
||||
@@ -1835,7 +1894,7 @@
|
||||
<button type="button" class="nav-item" id="nav-coda" onclick="showView('coda')"><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"></circle><circle cx="12" cy="12" r="5"></circle><circle cx="12" cy="12" r="1"></circle></svg>部門 CODA</button>
|
||||
<button type="button" class="nav-item" id="nav-group" onclick="showView('group')"><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3l9 5-9 5-9-5z"></path><path d="M3 13l9 5 9-5"></path></svg>組別分析</button>
|
||||
<button type="button" class="nav-item" id="nav-simulate" onclick="showView('simulate')"><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="3" width="14" height="18" rx="2"></rect><path d="M8 7h8M8 11h2M12 11h2M16 11h0M8 15h2M12 15h2M8 19h0"></path></svg>模擬試算</button>
|
||||
<a class="nav-item" id="nav-permissions" href="/permissions"><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="11" width="14" height="9" rx="2"></rect><path d="M8 11V8a4 4 0 0 1 8 0v3"></path></svg>權限管理</a>
|
||||
<button type="button" class="nav-item" id="nav-permissions" onclick="showView('permissions')"><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="11" width="14" height="9" rx="2"></rect><path d="M8 11V8a4 4 0 0 1 8 0v3"></path></svg>權限管理</button>
|
||||
</nav>
|
||||
|
||||
<div class="nav-group sidebar-account" style="gap: 0.5rem;">
|
||||
@@ -2023,6 +2082,30 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- PERMISSIONS VIEW -->
|
||||
<div id="permissions" class="view">
|
||||
<div style="margin-bottom: 2rem;">
|
||||
<h1 style="margin-bottom: 0.5rem;">權限管理</h1>
|
||||
<p class="lead">HR 的主管會自動帶入權限;HR 拿掉主管身分,這些權限就自動消失。這裡加的是「手動」權限,要在這裡拿掉。只有最高管理者能改核心參數、按定錨、刪資料、管理權限。</p>
|
||||
</div>
|
||||
<div class="rules">
|
||||
<div class="rule"><b>部主管(HR)</b>看部門、個人明細(含薪資)、部門模擬試算</div>
|
||||
<div class="rule"><b>組主管(HR)</b>看自己組的實際 CODA、平均日 CODA、定錨 CODA</div>
|
||||
<div class="rule"><b>手動加權限</b>全公司檢視、其他部門或組、個人明細、模擬</div>
|
||||
</div>
|
||||
<div class="toolbar">
|
||||
<input class="search" id="perm-q" type="search" placeholder="搜尋姓名、工號、部門、組" oninput="permDraw()" aria-label="搜尋">
|
||||
<div class="tabs" id="perm-tabs" role="group" aria-label="篩選"></div>
|
||||
</div>
|
||||
<div class="list" id="perm-rows"><div class="empty">讀取中…</div></div>
|
||||
<details style="margin-top:1.5rem;">
|
||||
<summary style="cursor:pointer; font-size:.9rem; color:var(--text-muted);">修改紀錄</summary>
|
||||
<p class="lead" style="margin-top:.75rem;">權限每次儲存都會留下紀錄:什麼時候、誰改的、改了誰、改前改後。紀錄不能刪除(最多保留最近 2000 筆,這裡顯示最近 200 筆)。</p>
|
||||
<div class="log" id="perm-log"></div>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<!-- PARAMETERS VIEW -->
|
||||
<div id="params" class="view">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
|
||||
@@ -2753,6 +2836,59 @@
|
||||
renderInvoiceRoles();
|
||||
}
|
||||
|
||||
|
||||
// ---- CODA 分配規則(核心參數):來源部門的整包 CODA 依各接收部門的 CODA 比例分下去 ----
|
||||
// 沒設定過時用 calc-core 的內建預設;第一次編輯就把內建預設一起寫成明確設定,才不會被默默換掉。
|
||||
function effectiveCodaShareRules() {
|
||||
return Array.isArray(globalParams.codaShareRules) ? globalParams.codaShareRules : codaShareRules();
|
||||
}
|
||||
function saveCodaShareRules(rules) {
|
||||
globalParams.codaShareRules = rules;
|
||||
saveAndRefresh();
|
||||
renderInvoiceRoles();
|
||||
}
|
||||
function removeCodaShareRule(index) {
|
||||
saveCodaShareRules(effectiveCodaShareRules().filter((rule, i) => i !== index));
|
||||
}
|
||||
function addCodaShareRule() {
|
||||
const from = document.getElementById('coda-share-from').value;
|
||||
const to = [...document.querySelectorAll('.coda-share-to:checked')].map(input => input.value).filter(name => name !== from);
|
||||
if (!from || !to.length) { alert('請選擇來源部門,並勾選至少一個接收部門。'); return; }
|
||||
const map = deptCompanyMap(isSimMode ? simData : baseData);
|
||||
const rules = effectiveCodaShareRules().filter(rule => !(rule.from || []).includes(from));
|
||||
rules.push({ company: shortCompanyName(map.get(from) || ''), from: [from], to,
|
||||
noDeptP: document.getElementById('coda-share-nodeptp').checked });
|
||||
saveCodaShareRules(rules);
|
||||
}
|
||||
function codaShareCard() {
|
||||
const depts = Object.keys(globalParams.orgStructure || {});
|
||||
const known = new Set(depts);
|
||||
const warn = name => known.has(name) ? escapeHtml(name)
|
||||
: `<span style="color:var(--accent-warning);" title="目前名單上沒有這個部門">${escapeHtml(name)}</span>`;
|
||||
const rules = effectiveCodaShareRules();
|
||||
const rows = rules.map((rule, index) => `
|
||||
<div class="ir-row">
|
||||
<span class="ir-name">${(rule.from || []).map(warn).join('、')}</span>
|
||||
<span class="ir-cost" style="white-space:normal;">分給 ${(rule.to || []).map(warn).join('、')}${rule.noDeptP ? ',並含該公司沒有部門的 P' : ''}</span>
|
||||
<span class="ir-src"><button type="button" class="link-button" style="color:var(--accent-danger);" onclick="removeCodaShareRule(${index})">刪除</button></span>
|
||||
</div>`).join('') || '<div class="ir-empty">目前沒有分配規則,每個部門的 CODA 都算自己的。</div>';
|
||||
const options = depts.map(d => `<option value="${escapeHtml(d)}">${escapeHtml(d)}</option>`).join('');
|
||||
const boxes = depts.map(d => `<label style="font-size:.8rem;display:inline-flex;align-items:center;gap:4px;margin-right:10px;white-space:nowrap;"><input type="checkbox" class="coda-share-to" value="${escapeHtml(d)}">${escapeHtml(d)}</label>`).join('');
|
||||
return `
|
||||
<div class="card ir-card" style="margin-top:1.5rem;">
|
||||
<div class="card-head"><h2><span class="dot" style="background:var(--dot-amber)"></span>CODA 分配規則</h2></div>
|
||||
<p style="font-size:.8rem;color:var(--text-dim);margin:.25rem 0 .75rem;">把來源部門的整包 CODA,依各接收部門自己的 CODA 比例分下去。來源部門的 CODA 會歸零,也不顯示部門倍率,等於只算成本、不談指標。這裡不影響發票分配,發票看的是上面的「發票承擔設定」。</p>
|
||||
<div class="ir-grid"><section class="ir-company">${rows}</section></div>
|
||||
<div style="display:grid;grid-template-columns:minmax(160px,1fr) minmax(260px,3fr) auto;gap:.5rem;align-items:start;margin-top:.75rem;">
|
||||
<select id="coda-share-from" aria-label="來源部門"><option value="">來源部門…</option>${options}</select>
|
||||
<div><div style="font-size:.75rem;color:var(--text-dim);margin-bottom:.25rem;">分給(可複選)</div>${boxes}
|
||||
<label style="font-size:.8rem;display:inline-flex;align-items:center;gap:4px;margin-top:.35rem;"><input type="checkbox" id="coda-share-nodeptp">含該公司沒有部門的 P</label>
|
||||
</div>
|
||||
<button type="button" class="btn-primary" onclick="addCodaShareRule()">+ 加入</button>
|
||||
</div>
|
||||
<div class="card-foot"><span>同一個來源部門只會有一條規則,重複加入會覆蓋舊的。</span></div>
|
||||
</div>`;
|
||||
}
|
||||
function renderInvoiceRoles() {
|
||||
const container = document.getElementById('invoice-roles');
|
||||
if (!container) return;
|
||||
@@ -2822,7 +2958,7 @@
|
||||
${bearDepts.length ? '' : '<div style="color:var(--accent-danger); font-weight:600; margin:0.25rem 0 0.5rem;">目前沒有任何「承擔發票」的部門,發票無法分配。</div>'}
|
||||
<div class="ir-grid">${companyBlocks}</div>
|
||||
<div class="card-foot"><span>新部門自動套用所屬公司的預設;部門可以個別改。</span>${stale.length ? `<span style="color:var(--accent-warning);">已失效的部門設定:${stale.map(d => `${escapeHtml(d)} <button type="button" class="link-button" onclick='setInvoiceRole("dept", ${escapeHtml(JSON.stringify(d))}, "")'>移除</button>`).join('、')}</span>` : ''}</div>
|
||||
</div>`;
|
||||
</div>${codaShareCard()}`;
|
||||
}
|
||||
|
||||
// --- 定錨(發票+定錨 CODA)。數字全部由伺服器算,這裡只顯示。 ---
|
||||
@@ -4596,6 +4732,7 @@
|
||||
if (viewId === 'group') renderGroup();
|
||||
if (viewId === 'org-structure') renderOrgStructure();
|
||||
if (viewId === 'plans') loadPlans().then(renderPlans);
|
||||
if (viewId === 'permissions') permLoad();
|
||||
if (viewId === 'simulate') { if (window.__simulateView) window.__simulateView.reload(); else window.__simulateView = PMScope.mount(document.getElementById('simulate-content'), { mode: 'simulate' }); }
|
||||
document.querySelector('main').scrollTo({ top: 0, left: 0, behavior: 'instant' });
|
||||
}
|
||||
@@ -5086,17 +5223,177 @@
|
||||
let contractorSignature = null;
|
||||
let contractorSaveTimer = null;
|
||||
|
||||
// ---- 預排異動(預計離職、預計新進):只有最高管理者 ----
|
||||
|
||||
// ---- 權限管理:原本是獨立的 /permissions 頁,搬進來變成一個區塊 ----
|
||||
// 整包包在函式裡,只對外露出 perm 開頭的幾個名字,避免和看板既有的 state、filter、draw 撞名。
|
||||
(function () {
|
||||
let state = { people: [], grants: {}, denied: [], log: [] };
|
||||
let filter = 'scoped';
|
||||
let editing = null;
|
||||
let message = {};
|
||||
let logShown = 20;
|
||||
|
||||
const kindOf = (p) => {
|
||||
const x = p.permission;
|
||||
if (x.admin) return 'admin';
|
||||
if (x.denied || state.denied.includes(p.employeeNumber)) return 'denied';
|
||||
if (x.company) return 'company';
|
||||
if (x.hr?.depts?.length) return 'dept';
|
||||
if (x.hr?.groups?.length) return 'group';
|
||||
if (state.grants[p.employeeNumber]) return 'manual';
|
||||
return 'none';
|
||||
};
|
||||
const FILTERS = [
|
||||
['scoped', '有權限', p => kindOf(p) !== 'none'],
|
||||
['dept', '部長', p => kindOf(p) === 'dept'],
|
||||
['group', '組長', p => kindOf(p) === 'group'],
|
||||
['company', '全公司檢視', p => kindOf(p) === 'company'],
|
||||
['manual', '有手動權限', p => Boolean(state.grants[p.employeeNumber])],
|
||||
['denied', '暫不開放', p => kindOf(p) === 'denied'],
|
||||
['all', '全部', () => true],
|
||||
];
|
||||
|
||||
function chips(p) {
|
||||
const x = p.permission;
|
||||
if (x.admin) return '<span class="chip admin">最高管理者</span>';
|
||||
if (x.denied) return '<span class="chip warn">暫不開放</span>';
|
||||
const g = state.grants[p.employeeNumber] || {};
|
||||
const out = [];
|
||||
if (x.company) out.push(['manual', '全公司檢視']);
|
||||
(x.hr?.depts || []).forEach(d => out.push(['hr', `部門 ${d}`]));
|
||||
(x.hr?.groups || []).forEach(k => out.push(['hr', `組 ${k.split('|')[1]}`]));
|
||||
(g.depts || []).forEach(d => out.push(['manual', `部門 ${d}`]));
|
||||
(g.groups || []).forEach(k => out.push(['manual', `組 ${k.split('|')[1]}`]));
|
||||
if (x.personDetail) out.push([x.hr?.depts?.length ? 'hr' : 'manual', '個人明細']);
|
||||
if (x.simulate) out.push([x.hr?.depts?.length ? 'hr' : 'manual', '模擬']);
|
||||
return out.length ? out.map(([c, t]) => `<span class="chip ${c}">${escapeHtml(t)}</span>`).join('') : '<span class="none">沒有權限</span>';
|
||||
}
|
||||
|
||||
function options() {
|
||||
const depts = [...new Set(state.people.map(p => p.dept).filter(Boolean))].sort((a, b) => a.localeCompare(b, 'zh-Hant'));
|
||||
const groups = [...new Set(state.people.filter(p => p.dept && p.group).map(p => `${p.dept}|${p.group}`))].sort((a, b) => a.localeCompare(b, 'zh-Hant'));
|
||||
return { depts, groups };
|
||||
}
|
||||
|
||||
function editor(p) {
|
||||
const g = state.grants[p.employeeNumber] || {};
|
||||
const { depts, groups } = options();
|
||||
const toggle = (name, label, hint, checked) => `<label class="toggle"><input type="checkbox" name="${name}" ${checked ? 'checked' : ''}><span>${label}<small>${hint}</small></span></label>`;
|
||||
return `<div class="editor" id="perm-editor">
|
||||
<div><h4>手動權限</h4><div class="toggles">
|
||||
${toggle('company', '全公司檢視', '各部門、各組數字,不含個人薪資', g.company)}
|
||||
${toggle('personDetail', '個人明細', '可看範圍內每個人的薪資與成本', g.personDetail)}
|
||||
${toggle('simulate', '部門模擬', '可在看得到的部門做模擬試算', g.simulate)}
|
||||
${toggle('denied', '暫不開放', '先不讓他看任何東西', state.denied.includes(p.employeeNumber))}
|
||||
</div></div>
|
||||
<div><h4>另外可以看的部門</h4><div class="pick">${depts.map(d => `<label><input type="checkbox" name="depts" value="${escapeHtml(d)}" ${(g.depts || []).includes(d) ? 'checked' : ''}>${escapeHtml(d)}</label>`).join('') || '<span class="none">沒有部門資料</span>'}</div></div>
|
||||
<div><h4>另外可以看的組</h4><div class="pick">${groups.map(k => `<label><input type="checkbox" name="groups" value="${escapeHtml(k)}" ${(g.groups || []).includes(k) ? 'checked' : ''}>${escapeHtml(k.replace('|', ' · '))}</label>`).join('') || '<span class="none">沒有組資料</span>'}</div></div>
|
||||
<div class="actions"><span class="status" role="status">${escapeHtml(message[p.employeeNumber] || '')}</span>
|
||||
<button type="button" class="btn" onclick="permCancel()">取消</button>
|
||||
<button type="button" class="btn primary" onclick="permSave('${escapeHtml(p.employeeNumber)}')">儲存</button></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function draw() {
|
||||
const box = document.getElementById('perm-rows');
|
||||
if (!box) return;
|
||||
const q = (document.getElementById('perm-q').value || '').trim();
|
||||
document.getElementById('perm-tabs').innerHTML = FILTERS.map(([key, label, test]) =>
|
||||
`<button type="button" class="tab" aria-pressed="${filter === key}" onclick="permFilter('${key}')">${label}<span class="n">${state.people.filter(test).length}</span></button>`).join('');
|
||||
const test = FILTERS.find(f => f[0] === filter)[2];
|
||||
const rows = state.people.filter(test).filter(p => !q || [p.employeeNumber, p.name, p.dept, p.group].some(v => String(v || '').includes(q)));
|
||||
box.innerHTML = rows.map(p => `<div class="row">
|
||||
<div class="who"><b>${escapeHtml(p.name)}</b><span>${escapeHtml(p.employeeNumber)} ${escapeHtml(p.title)}</span></div>
|
||||
<div class="where">${escapeHtml(p.dept || '—')}<br><span>${escapeHtml(p.group || '')}</span></div>
|
||||
<div class="chips">${chips(p)}</div>
|
||||
<div class="act">${p.permission.admin ? '' : `<button type="button" class="btn" onclick="permEdit('${escapeHtml(p.employeeNumber)}')" aria-expanded="${editing === p.employeeNumber}">${editing === p.employeeNumber ? '收起' : '調整'}</button>`}</div>
|
||||
${editing === p.employeeNumber ? editor(p) : ''}
|
||||
</div>`).join('') || '<div class="empty">沒有符合的人</div>';
|
||||
}
|
||||
|
||||
function grantChips(entry) {
|
||||
if (!entry) return [];
|
||||
const out = [];
|
||||
if (entry.denied) out.push(['warn', '暫不開放']);
|
||||
const g = entry.grant || {};
|
||||
if (g.company) out.push(['manual', '全公司檢視']);
|
||||
(g.depts || []).forEach(d => out.push(['manual', `部門 ${d}`]));
|
||||
(g.groups || []).forEach(k => out.push(['manual', `組 ${String(k).split('|')[1] || k}`]));
|
||||
if (g.personDetail) out.push(['manual', '個人明細']);
|
||||
if (g.simulate) out.push(['manual', '模擬']);
|
||||
return out;
|
||||
}
|
||||
|
||||
function drawLog() {
|
||||
const box = document.getElementById('perm-log');
|
||||
if (!box) return;
|
||||
const log = state.log || [];
|
||||
if (!log.length) { box.innerHTML = '<div class="empty">還沒有修改紀錄。</div>'; return; }
|
||||
const names = new Map(state.people.map(p => [String(p.employeeNumber), p.name]));
|
||||
const who = id => names.get(String(id)) ? `${escapeHtml(names.get(String(id)))}(${escapeHtml(id)})` : escapeHtml(id);
|
||||
const chipHtml = (list, cls = '') => list.length ? list.map(([c, t]) => `<span class="chip ${c} ${cls}">${escapeHtml(t)}</span>`).join('') : '<span class="none">沒有手動權限</span>';
|
||||
box.innerHTML = log.slice(0, logShown).map(e => {
|
||||
const before = grantChips(e.before);
|
||||
const after = grantChips(e.after);
|
||||
const keys = list => new Set(list.map(([, t]) => t));
|
||||
const a = keys(after);
|
||||
const b = keys(before);
|
||||
const removed = before.filter(([, t]) => !a.has(t));
|
||||
const added = after.filter(([, t]) => !b.has(t));
|
||||
const kept = after.filter(([, t]) => b.has(t));
|
||||
const change = !removed.length && !added.length ? '<span class="none">沒有變更(重新儲存)</span>'
|
||||
: `${removed.length ? `${chipHtml(removed, 'old')}<span class="arrow">→</span>` : ''}${added.length ? chipHtml(added) : '<span class="none">移除</span>'}${kept.length ? `<span class="none">(保留:${kept.map(([, t]) => escapeHtml(t)).join('、')})</span>` : ''}`;
|
||||
return `<div class="log-row"><time datetime="${escapeHtml(e.at)}">${escapeHtml(new Date(e.at).toLocaleString('zh-TW', { hour12: false }))}</time>
|
||||
<div><b>${who(e.employeeNumber)}</b></div>
|
||||
<div class="change">${change}</div>
|
||||
<div class="by">由 ${who(e.by)}</div></div>`;
|
||||
}).join('') + (log.length > logShown ? `<div class="log-row" style="display:block;"><button type="button" class="btn" onclick="permMoreLog()">再顯示 ${Math.min(50, log.length - logShown)} 筆</button></div>` : '');
|
||||
}
|
||||
|
||||
window.permFilter = (key) => { filter = key; draw(); };
|
||||
window.permEdit = (id) => { editing = editing === id ? null : id; draw(); };
|
||||
window.permCancel = () => { editing = null; draw(); };
|
||||
window.permMoreLog = () => { logShown += 50; drawLog(); };
|
||||
window.permDraw = draw;
|
||||
|
||||
window.permSave = async (id) => {
|
||||
const box = document.getElementById('perm-editor');
|
||||
const on = name => box.querySelector(`[name=${name}]`).checked;
|
||||
const picked = name => [...box.querySelectorAll(`[name=${name}]:checked`)].map(i => i.value);
|
||||
const grant = { company: on('company'), personDetail: on('personDetail'), simulate: on('simulate'), depts: picked('depts'), groups: picked('groups'), note: '權限頁設定' };
|
||||
const empty = !grant.company && !grant.personDetail && !grant.simulate && !grant.depts.length && !grant.groups.length;
|
||||
const response = await fetch('/api/permissions', { method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ employeeNumber: id, grant: empty ? null : grant, denied: on('denied') }) });
|
||||
message[id] = response.ok ? '已儲存' : `儲存失敗(${response.status})`;
|
||||
await window.permLoad();
|
||||
};
|
||||
|
||||
window.permLoad = async () => {
|
||||
const box = document.getElementById('perm-rows');
|
||||
if (!box) return;
|
||||
const response = await fetch('/api/permissions', { cache: 'no-store' });
|
||||
if (!response.ok) { box.innerHTML = '<div class="empty">只有最高管理者可以管理權限。</div>'; return; }
|
||||
state = await response.json();
|
||||
drawLog();
|
||||
if (state.preview && !state.people.length) { box.innerHTML = '<div class="empty">本機預覽沒有 HR 名單。</div>'; return; }
|
||||
draw();
|
||||
};
|
||||
})();
|
||||
|
||||
// ---- 預排異動(預計離職、預計新進、預計轉調):只有最高管理者 ----
|
||||
let planState = null;
|
||||
const PLAN_STATUS = {
|
||||
pending: ['等待 HR', 'var(--text-muted)'],
|
||||
overdue: ['時間到了 HR 還沒改', 'var(--accent-danger)'],
|
||||
conflict: ['HR 調到別的單位,請確認', 'var(--accent-warning)'],
|
||||
manager_pending: ['部門已調,主管職還沒處理', 'var(--accent-warning)'],
|
||||
};
|
||||
const PLAN_REASON = {
|
||||
hr_left: 'HR 名單上已經沒有這個人',
|
||||
hr_leave_date: 'HR 已填離職日',
|
||||
hr_joined: 'HR 名單已出現',
|
||||
expired: '時間過了 HR 一直沒改,自動移除',
|
||||
hr_transferred: 'HR 已經調到目標單位',
|
||||
};
|
||||
async function loadPlans() {
|
||||
try {
|
||||
@@ -5109,8 +5406,10 @@
|
||||
}
|
||||
function updatePlanBanner() {
|
||||
const overdue = planState?.status?.overdue || 0;
|
||||
const conflicts = planState?.status?.conflicts || 0;
|
||||
const managerPending = planState?.status?.managerPending || 0;
|
||||
let note = document.getElementById('plan-overdue-banner');
|
||||
if (!overdue) { if (note) note.remove(); return; }
|
||||
if (!overdue && !conflicts && !managerPending) { if (note) note.remove(); return; }
|
||||
if (!note) {
|
||||
note = document.createElement('button');
|
||||
note.id = 'plan-overdue-banner';
|
||||
@@ -5119,12 +5418,16 @@
|
||||
note.style.cssText = 'display:block;margin:.5rem 0;padding:.5rem .75rem;border-radius:10px;border:1px solid var(--accent-danger);background:none;color:var(--accent-danger);cursor:pointer;font-size:.85rem;text-align:left;';
|
||||
document.getElementById('data-source-banner').after(note);
|
||||
}
|
||||
note.textContent = `預排異動:有 ${overdue} 筆時間到了 HR 還沒更新,寬限期過後會自動移除 →`;
|
||||
note.textContent = [overdue ? `有 ${overdue} 筆時間到了 HR 還沒更新,寬限期過後會自動移除` : '',
|
||||
conflicts ? `有 ${conflicts} 筆 HR 調到別的單位,要你確認` : '',
|
||||
managerPending ? `有 ${managerPending} 筆部門已經調了但主管職還沒處理` : ''].filter(Boolean).join(';');
|
||||
note.textContent = `預排異動:${note.textContent} →`;
|
||||
}
|
||||
function planSummaryLine() {
|
||||
const st = planState?.status;
|
||||
if (!st || (!st.departures.length && !st.hires.length)) return '';
|
||||
return `<div style="width:100%;font-size:.75rem;color:var(--accent-warning);">這次定錨包含預排異動:預計離職 ${st.departures.length} 位、預計新進 ${st.hires.length} 位(在「預排異動」頁可以檢查)。</div>`;
|
||||
const transfers = st?.transfers?.length || 0;
|
||||
if (!st || (!st.departures.length && !st.hires.length && !transfers)) return '';
|
||||
return `<div style="width:100%;font-size:.75rem;color:var(--accent-warning);">這次定錨包含預排異動:預計離職 ${st.departures.length} 位、預計新進 ${st.hires.length} 位、預計轉調 ${transfers} 位(在「預排異動」頁可以檢查)。</div>`;
|
||||
}
|
||||
function planStatusPill(status, autoRemoveAfter) {
|
||||
const [label, color] = PLAN_STATUS[status] || [status, 'var(--text-muted)'];
|
||||
@@ -5141,7 +5444,7 @@
|
||||
<thead><tr><th style="${cell}">時間</th><th style="${cell}">類型</th><th style="${cell}">名稱</th><th style="${cell}">月份</th><th style="${cell}">原因</th></tr></thead>
|
||||
<tbody>${history.map(h => `<tr>
|
||||
<td style="${cell}">${escapeHtml(String(h.at || '').slice(0, 10))}</td>
|
||||
<td style="${cell}">${h.kind === 'hire' ? '預計新進' : '預計離職'}</td>
|
||||
<td style="${cell}">${h.kind === 'hire' ? '預計新進' : h.kind === 'transfer' ? '預計轉調' : '預計離職'}</td>
|
||||
<td style="${cell}">${escapeHtml(h.label)}${h.matched ? `<div style="font-size:.75rem;color:var(--text-dim);">對到 ${escapeHtml(h.matched)}</div>` : ''}</td>
|
||||
<td style="${cell}">${escapeHtml(h.month)}</td>
|
||||
<td style="${cell}">${escapeHtml(PLAN_REASON[h.reason] || h.reason)}</td>
|
||||
@@ -5156,6 +5459,7 @@
|
||||
const st = planState.status;
|
||||
const hrPeople = baseData.filter(p => p.source === 'hr-sync').sort((a, b) => (a.dept || '').localeCompare(b.dept || '', 'zh-Hant') || (a.name || '').localeCompare(b.name || '', 'zh-Hant'));
|
||||
const planned = new Set(planState.plans.departures.map(d => d.employeeNumber));
|
||||
const moving = new Set((planState.plans.transfers || []).map(t => String(t.employeeNumber)));
|
||||
const depts = [...new Set(baseData.filter(p => p.source !== 'planned' && p.dept).map(p => p.dept))].sort((a, b) => a.localeCompare(b, 'zh-Hant'));
|
||||
const groups = [...new Set(baseData.filter(p => p.group).map(p => p.group))].sort();
|
||||
const year = globalParams.reportYear || 2027;
|
||||
@@ -5215,6 +5519,38 @@
|
||||
<input id="plan-hire-note" type="text" maxlength="200" placeholder="備註(只有你看得到)">
|
||||
<button type="button" class="btn-primary" onclick="addHire()">+ 加入</button>
|
||||
</div>
|
||||
</section>
|
||||
<section class="card" style="padding:1.25rem;margin-top:1.5rem;">
|
||||
<h2 style="font-size:1.1rem;margin:0 0 .25rem;">預計轉調</h2>
|
||||
<p style="font-size:.8rem;color:var(--text-dim);margin:0 0 .75rem;">填「生效月份」。${year} 年 1 月起就整年算新單位;生效月份在年度中間,成本會按月拆成兩段(前段原單位、後段新單位)。目標部門可以填 HR 還沒有的新部門。主管職預設轉調後卸任,可以指定原單位由誰接任,模擬就會照你設定的組織算。HR 把人調到目標單位、主管職也處理好之後,系統才會自動移除這一筆;只調了部門沒處理主管,會一直留著提醒;HR 要是調到別的地方,會標成「請確認」。主管職的設定只影響數字和模擬,不影響任何人在看板上看得到什麼,權限一律以 HR 為準。</p>
|
||||
<table style="width:100%;border-collapse:collapse;font-size:.9rem;">
|
||||
<thead><tr><th style="${cell}">姓名</th><th style="${cell}">HR 目前部門/組</th><th style="${cell}">調到</th><th style="${cell}">生效月份</th><th style="${cell}">主管職</th><th style="${cell}">備註</th><th style="${cell}">狀態</th><th style="${cell}"></th></tr></thead>
|
||||
<tbody>${(st.transfers || []).length ? st.transfers.map(t => `<tr>
|
||||
<td style="${cell}">${escapeHtml(t.name || '(不在 HR 名單)')} <span style="color:var(--text-dim);font-size:.8rem;">${escapeHtml(t.employeeNumber)}</span></td>
|
||||
<td style="${cell}">${escapeHtml([t.dept, shortGroupName(t.dept, t.group || '')].filter(Boolean).join(' / ')) || '—'}</td>
|
||||
<td style="${cell}">${escapeHtml([t.toDept, t.toGroup].filter(Boolean).join(' / '))}</td>
|
||||
<td style="${cell}">${escapeHtml(t.effectiveMonth)}</td>
|
||||
<td style="${cell}">${t.leads.length ? `${t.keepManager ? '保留' : '卸任'}(HR 目前:${escapeHtml(t.leads.join('、'))})` : t.keepManager ? '保留' : '—'}${t.successorEmployeeNumber ? `<div style="font-size:.75rem;color:var(--text-dim);">接任:${escapeHtml(t.successorName || t.successorEmployeeNumber)}${t.successorIsManager ? '' : '(HR 還沒設定)'}</div>` : ''}</td>
|
||||
<td style="${cell}">${escapeHtml(t.note)}</td>
|
||||
<td style="${cell}">${planStatusPill(t.status, t.autoRemoveAfter)}</td>
|
||||
<td style="${cell}"><button type="button" onclick="removePlan('transfers','${escapeHtml(t.employeeNumber)}')" style="background:none;border:none;color:var(--accent-danger);cursor:pointer;">刪除</button></td>
|
||||
</tr>`).join('') : `<tr><td colspan="8" style="${cell}color:var(--text-dim);">目前沒有預計轉調。</td></tr>`}</tbody>
|
||||
</table>
|
||||
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(170px,1fr));gap:.5rem;margin-top:.75rem;">
|
||||
<select id="plan-tr-person" aria-label="選擇人員">
|
||||
<option value="">選擇人員…</option>
|
||||
${hrPeople.filter(p => !moving.has(String(p.employeeNumber))).map(p => `<option value="${escapeHtml(p.employeeNumber)}">${escapeHtml(p.dept || '未歸部門')}|${escapeHtml(p.name)}(${escapeHtml(p.employeeNumber)})</option>`).join('')}
|
||||
</select>
|
||||
<input id="plan-tr-dept" type="text" list="plan-dept-list" maxlength="80" placeholder="調到哪個部門">
|
||||
<datalist id="plan-dept-list">${depts.map(d => `<option value="${escapeHtml(d)}">`).join('')}</datalist>
|
||||
<input id="plan-tr-group" type="text" list="plan-group-list" maxlength="80" placeholder="組別(可不填)">
|
||||
<label style="font-size:.8rem;color:var(--text-dim);">生效月份<input id="plan-tr-month" type="month" min="${year - 1}-01" max="${year + 1}-12" style="width:100%;"></label>
|
||||
|
||||
<select id="plan-tr-manager" aria-label="主管職"><option value="drop">轉調後卸任主管職</option><option value="keep">保留主管職</option></select>
|
||||
<select id="plan-tr-successor" aria-label="原單位接任主管"><option value="">原單位接任主管…(可不填)</option>${hrPeople.map(p => `<option value="${escapeHtml(p.employeeNumber)}">${escapeHtml(p.dept || '未歸部門')}|${escapeHtml(p.name)}</option>`).join('')}</select>
|
||||
<input id="plan-tr-note" type="text" maxlength="200" placeholder="備註(只有你看得到)">
|
||||
<button type="button" class="btn-primary" onclick="addTransfer()">+ 加入</button>
|
||||
</div>
|
||||
</section>${planHistory(st.history)}`;
|
||||
}
|
||||
async function savePlans(next) {
|
||||
@@ -5252,9 +5588,29 @@
|
||||
const plans = planState.plans;
|
||||
savePlans({ ...plans, hires: [...plans.hires, hire] });
|
||||
}
|
||||
|
||||
function addTransfer() {
|
||||
const value = id => document.getElementById(id).value;
|
||||
const employeeNumber = value('plan-tr-person');
|
||||
const toDept = value('plan-tr-dept').trim();
|
||||
const effectiveMonth = value('plan-tr-month');
|
||||
if (!employeeNumber || !toDept || !effectiveMonth) { alert('請選擇人員,並填目標部門和生效月份。'); return; }
|
||||
const person = baseData.find(p => String(p.employeeNumber) === employeeNumber);
|
||||
const toGroup = value('plan-tr-group').trim();
|
||||
if (person && person.dept === toDept && (person.group || '') === toGroup) { alert('這個人已經在目標單位了。'); return; }
|
||||
const keepManager = value('plan-tr-manager') === 'keep';
|
||||
const successorEmployeeNumber = value('plan-tr-successor');
|
||||
const leads = (person?.supervisorOf || []).map(unit => unit.deptName).filter(Boolean);
|
||||
if (leads.length && !keepManager && !successorEmployeeNumber
|
||||
&& !confirm(`${person.name} 目前是 ${leads.join('、')} 的主管。轉調後這些單位會沒有主管,而且你還沒指定接任者。要繼續嗎?`)) return;
|
||||
const plans = planState.plans;
|
||||
savePlans({ ...plans, transfers: [...(plans.transfers || []),
|
||||
{ employeeNumber, toDept, toGroup, fromDept: person?.dept || '', effectiveMonth,
|
||||
keepManager, successorEmployeeNumber, note: value('plan-tr-note') }] });
|
||||
}
|
||||
function removePlan(kind, key) {
|
||||
const plans = planState.plans;
|
||||
const next = { ...plans, [kind]: plans[kind].filter(item => (kind === 'departures' ? item.employeeNumber : item.id) !== key) };
|
||||
const next = { ...plans, [kind]: (plans[kind] || []).filter(item => (kind === 'hires' ? item.id : item.employeeNumber) !== key) };
|
||||
savePlans(next);
|
||||
}
|
||||
|
||||
@@ -5308,7 +5664,9 @@
|
||||
});
|
||||
const roles = globalParams.invoiceRoles || {};
|
||||
return { rdGroups: [...(globalParams.rdGroups || [])], cgLeadGroups: [...(globalParams.cgLeadGroups || [])], params,
|
||||
invoiceRoles: { companies: { ...(roles.companies || {}) }, depts: { ...(roles.depts || {}) } } };
|
||||
invoiceRoles: { companies: { ...(roles.companies || {}) }, depts: { ...(roles.depts || {}) } },
|
||||
// 還沒有編輯介面,原樣送回去,才不會被其他設定的存檔洗掉。
|
||||
...(Array.isArray(globalParams.codaShareRules) ? { codaShareRules: globalParams.codaShareRules } : {}) };
|
||||
}
|
||||
|
||||
function scheduleSettingsSave() {
|
||||
@@ -5469,6 +5827,14 @@
|
||||
saveAndRefresh();
|
||||
}
|
||||
|
||||
// 從網址帶進來的區塊(例如舊的 /permissions 會導成 /?view=permissions)。
|
||||
function openViewFromUrl() {
|
||||
const wanted = new URLSearchParams(location.search).get('view');
|
||||
if (!wanted) return;
|
||||
const target = document.getElementById(wanted);
|
||||
if (target && target.classList.contains('view')) showView(wanted);
|
||||
}
|
||||
|
||||
window.onload = async () => {
|
||||
applyPreviewUI();
|
||||
try {
|
||||
@@ -5476,6 +5842,7 @@
|
||||
if (!await loadBootstrapData()) return;
|
||||
bootApp();
|
||||
loadPlans();
|
||||
openViewFromUrl();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
const banner = document.getElementById('data-source-banner');
|
||||
|
||||
@@ -40,6 +40,7 @@ h1 { font-size:1.5rem; margin:0; }
|
||||
button:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }
|
||||
@media (max-width: 600px) { .bar { justify-content:flex-start; } #year { text-align:left !important; } }
|
||||
</style>
|
||||
<link rel="stylesheet" href="/buttons.css">
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
|
||||
@@ -1,252 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-Hant">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>MoonShine LeadBoard · 權限管理</title>
|
||||
<link rel="icon" href="/2022_Moonshine_Logo_MS_logo_w_EN.png">
|
||||
<style>
|
||||
:root {
|
||||
--bg:#f5f4f0; --card:#ffffff; --raised:#fbfaf7; --text:#1d2025; --muted:#646b75; --dim:#8a9099; --line:#e6e2da;
|
||||
--accent:#4a63e0; --accent-soft:rgba(74,99,224,.1); --warn:#b4540a; --warn-soft:rgba(180,84,10,.1); --good:#2f7d4f; --good-soft:rgba(47,125,79,.1); --on-accent:#fff;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root { --bg:#141619; --card:#1c1f24; --raised:#22262c; --text:#eceef1; --muted:#a6acb5; --dim:#7d848d; --line:#2e333a;
|
||||
--accent:#8fa2ff; --accent-soft:rgba(143,162,255,.14); --warn:#f0a35a; --warn-soft:rgba(240,163,90,.14); --good:#6fcf97; --good-soft:rgba(111,207,151,.14); --on-accent:#141619; }
|
||||
}
|
||||
* { box-sizing:border-box; }
|
||||
body { margin:0; background:var(--bg); color:var(--text); font:15px/1.55 -apple-system, "PingFang TC", "Noto Sans TC", "Microsoft JhengHei", sans-serif; }
|
||||
main { max-width:1080px; margin:0 auto; padding:28px 20px 80px; }
|
||||
a.back { color:var(--muted); text-decoration:none; font-size:.85rem; }
|
||||
a.back:hover { color:var(--text); }
|
||||
h1 { font-size:1.6rem; margin:6px 0 6px; letter-spacing:.01em; }
|
||||
.lead { color:var(--muted); font-size:.88rem; margin:0 0 20px; max-width:760px; }
|
||||
.rules { display:grid; grid-template-columns:repeat(auto-fit, minmax(220px, 1fr)); gap:10px; margin-bottom:22px; }
|
||||
.rule { background:var(--card); border:1px solid var(--line); border-radius:12px; padding:12px 14px; font-size:.82rem; color:var(--muted); }
|
||||
.rule b { display:block; color:var(--text); font-size:.9rem; margin-bottom:2px; }
|
||||
.toolbar { display:flex; gap:10px; flex-wrap:wrap; align-items:center; margin-bottom:12px; }
|
||||
.search { flex:1; min-width:220px; font:inherit; padding:9px 12px; border:1px solid var(--line); border-radius:10px; background:var(--card); color:var(--text); }
|
||||
.tabs { display:flex; gap:6px; flex-wrap:wrap; }
|
||||
.tab { font:inherit; font-size:.82rem; border:1px solid var(--line); background:var(--card); color:var(--muted); border-radius:99px; padding:5px 12px; cursor:pointer; }
|
||||
.tab[aria-pressed="true"] { background:var(--text); color:var(--bg); border-color:var(--text); }
|
||||
.tab .n { opacity:.7; margin-left:4px; font-variant-numeric:tabular-nums; }
|
||||
.list { background:var(--card); border:1px solid var(--line); border-radius:14px; overflow:hidden; }
|
||||
.row { display:grid; grid-template-columns: minmax(170px, 1.1fr) minmax(130px, .8fr) minmax(220px, 1.6fr) 72px; gap:14px; align-items:center; padding:12px 16px; border-top:1px solid var(--line); }
|
||||
.row:first-child { border-top:0; }
|
||||
.who b { display:block; font-size:.95rem; }
|
||||
.who span, .where span { color:var(--dim); font-size:.78rem; }
|
||||
.where { font-size:.86rem; }
|
||||
.chips { display:flex; flex-wrap:wrap; gap:5px; }
|
||||
.chip { font-size:.75rem; padding:2px 9px; border-radius:99px; background:var(--raised); border:1px solid var(--line); color:var(--muted); white-space:nowrap; }
|
||||
.chip.hr { background:var(--accent-soft); border-color:transparent; color:var(--accent); }
|
||||
.chip.manual { background:var(--good-soft); border-color:transparent; color:var(--good); }
|
||||
.chip.warn { background:var(--warn-soft); border-color:transparent; color:var(--warn); }
|
||||
.chip.admin { background:var(--text); color:var(--bg); border-color:transparent; }
|
||||
.none { color:var(--dim); font-size:.8rem; }
|
||||
.btn { font:inherit; font-size:.82rem; border:1px solid var(--line); background:var(--card); color:var(--text); border-radius:8px; padding:6px 14px; cursor:pointer; white-space:nowrap; }
|
||||
.btn:hover { background:var(--raised); }
|
||||
.btn.primary { background:var(--accent); border-color:var(--accent); color:var(--on-accent); }
|
||||
button:focus-visible, input:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }
|
||||
.editor { grid-column:1 / -1; background:var(--raised); border:1px solid var(--line); border-radius:12px; padding:14px 16px; display:grid; gap:14px; }
|
||||
.editor h4 { margin:0 0 6px; font-size:.8rem; color:var(--muted); font-weight:500; }
|
||||
.toggles { display:flex; flex-wrap:wrap; gap:8px; }
|
||||
.toggle { display:flex; gap:8px; align-items:flex-start; border:1px solid var(--line); background:var(--card); border-radius:10px; padding:8px 12px; cursor:pointer; font-size:.86rem; min-width:180px; }
|
||||
.toggle small { display:block; color:var(--dim); font-size:.74rem; }
|
||||
.toggle input { margin-top:3px; }
|
||||
.pick { display:flex; flex-wrap:wrap; gap:6px; max-height:180px; overflow:auto; }
|
||||
.pick label { font-size:.8rem; border:1px solid var(--line); background:var(--card); border-radius:99px; padding:3px 10px; cursor:pointer; display:flex; gap:5px; align-items:center; }
|
||||
.pick label:has(input:checked) { background:var(--accent-soft); border-color:var(--accent); color:var(--accent); }
|
||||
.pick input { margin:0; }
|
||||
.actions { display:flex; gap:8px; justify-content:flex-end; align-items:center; }
|
||||
.status { font-size:.8rem; color:var(--muted); margin-right:auto; }
|
||||
.empty { padding:28px; text-align:center; color:var(--dim); }
|
||||
.history { margin-top:28px; }
|
||||
.history h2 { font-size:1.05rem; margin:0 0 4px; }
|
||||
.history .lead { margin-bottom:10px; }
|
||||
.log { background:var(--card); border:1px solid var(--line); border-radius:14px; overflow:hidden; }
|
||||
.log-row { display:grid; grid-template-columns: 150px minmax(140px, .9fr) minmax(220px, 2fr) minmax(170px, .7fr); gap:12px; padding:10px 16px; border-top:1px solid var(--line); font-size:.85rem; align-items:start; }
|
||||
.log-row:first-child { border-top:0; }
|
||||
.log-row time { color:var(--dim); font-variant-numeric:tabular-nums; }
|
||||
.log-row .by { color:var(--muted); }
|
||||
.change { display:flex; flex-wrap:wrap; gap:4px; align-items:center; }
|
||||
.change .arrow { color:var(--dim); margin:0 2px; }
|
||||
.chip.old { text-decoration:line-through; opacity:.7; }
|
||||
.more { display:block; margin:10px auto 0; }
|
||||
@media (max-width: 760px) { .log-row { grid-template-columns: 1fr; gap:4px; } }
|
||||
@media (max-width: 760px) {
|
||||
.row { grid-template-columns: 1fr auto; gap:8px 12px; }
|
||||
.row > .who { grid-column:1; grid-row:1; }
|
||||
.row > .act { grid-column:2; grid-row:1; }
|
||||
.row > .where, .row > .chips { grid-column:1 / -1; }
|
||||
.where br { display:none; } .where span:not(:empty)::before { content:' · '; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<a href="/" class="back">← 回到 LeadBoard</a>
|
||||
<h1>權限管理</h1>
|
||||
<p class="lead">HR 的主管會自動帶入權限;HR 拿掉主管身分,這些權限就自動消失。這裡加的是「手動」權限,要在這裡拿掉。只有最高管理者能改核心參數、按定錨、刪資料、管理權限。</p>
|
||||
<div class="rules">
|
||||
<div class="rule"><b>部主管(HR)</b>看部門、個人明細(含薪資)、部門模擬試算</div>
|
||||
<div class="rule"><b>組主管(HR)</b>看自己組的實際 CODA、平均日 CODA、定錨 CODA</div>
|
||||
<div class="rule"><b>手動加權限</b>全公司檢視、其他部門或組、個人明細、模擬</div>
|
||||
</div>
|
||||
<div class="toolbar">
|
||||
<input class="search" id="q" type="search" placeholder="搜尋姓名、工號、部門、組" oninput="draw()" aria-label="搜尋">
|
||||
<div class="tabs" id="tabs" role="group" aria-label="篩選"></div>
|
||||
</div>
|
||||
<div class="list" id="rows"><div class="empty">讀取中…</div></div>
|
||||
<section class="history" aria-labelledby="history-title">
|
||||
<h2 id="history-title">修改紀錄</h2>
|
||||
<p class="lead">權限頁每次儲存都會留下紀錄:什麼時候、誰改的、改了誰、改前改後。紀錄不能刪除(最多保留最近 2000 筆,這裡顯示最近 200 筆)。</p>
|
||||
<div class="log" id="log"><div class="empty">讀取中…</div></div>
|
||||
</section>
|
||||
</main>
|
||||
<script>
|
||||
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
let state = { people: [], grants: {}, denied: [] };
|
||||
let filter = 'scoped';
|
||||
let editing = null;
|
||||
let message = {};
|
||||
|
||||
const kindOf = p => {
|
||||
const x = p.permission;
|
||||
if (x.admin) return 'admin';
|
||||
if (x.denied || state.denied.includes(p.employeeNumber)) return 'denied';
|
||||
if (x.company) return 'company';
|
||||
if (x.hr?.depts?.length) return 'dept';
|
||||
if (x.hr?.groups?.length) return 'group';
|
||||
if (state.grants[p.employeeNumber]) return 'manual';
|
||||
return 'none';
|
||||
};
|
||||
const FILTERS = [
|
||||
['scoped', '有權限', p => kindOf(p) !== 'none'],
|
||||
['dept', '部長', p => kindOf(p) === 'dept'],
|
||||
['group', '組長', p => kindOf(p) === 'group'],
|
||||
['company', '全公司檢視', p => kindOf(p) === 'company'],
|
||||
['manual', '有手動權限', p => Boolean(state.grants[p.employeeNumber])],
|
||||
['denied', '暫不開放', p => kindOf(p) === 'denied'],
|
||||
['all', '全部', () => true],
|
||||
];
|
||||
|
||||
function chips(p) {
|
||||
const x = p.permission;
|
||||
if (x.admin) return '<span class="chip admin">最高管理者</span>';
|
||||
if (x.denied) return '<span class="chip warn">暫不開放</span>';
|
||||
const g = state.grants[p.employeeNumber] || {};
|
||||
const out = [];
|
||||
if (x.company) out.push(['manual', '全公司檢視']);
|
||||
(x.hr?.depts || []).forEach(d => out.push(['hr', `部門 ${d}`]));
|
||||
(x.hr?.groups || []).forEach(k => out.push(['hr', `組 ${k.split('|')[1]}`]));
|
||||
(g.depts || []).forEach(d => out.push(['manual', `部門 ${d}`]));
|
||||
(g.groups || []).forEach(k => out.push(['manual', `組 ${k.split('|')[1]}`]));
|
||||
if (x.personDetail) out.push([x.hr?.depts?.length ? 'hr' : 'manual', '個人明細']);
|
||||
if (x.simulate) out.push([x.hr?.depts?.length ? 'hr' : 'manual', '模擬']);
|
||||
return out.length ? out.map(([c, t]) => `<span class="chip ${c}">${esc(t)}</span>`).join('') : '<span class="none">沒有權限</span>';
|
||||
}
|
||||
|
||||
function options() {
|
||||
const depts = [...new Set(state.people.map(p => p.dept).filter(Boolean))].sort((a, b) => a.localeCompare(b, 'zh-Hant'));
|
||||
const groups = [...new Set(state.people.filter(p => p.dept && p.group).map(p => `${p.dept}|${p.group}`))].sort((a, b) => a.localeCompare(b, 'zh-Hant'));
|
||||
return { depts, groups };
|
||||
}
|
||||
|
||||
function editor(p) {
|
||||
const g = state.grants[p.employeeNumber] || {};
|
||||
const { depts, groups } = options();
|
||||
const toggle = (name, label, hint, checked) => `<label class="toggle"><input type="checkbox" name="${name}" ${checked ? 'checked' : ''}><span>${label}<small>${hint}</small></span></label>`;
|
||||
return `<div class="editor" id="editor">
|
||||
<div><h4>手動權限</h4><div class="toggles">
|
||||
${toggle('company', '全公司檢視', '各部門、各組數字,不含個人薪資', g.company)}
|
||||
${toggle('personDetail', '個人明細', '可看範圍內每個人的薪資與成本', g.personDetail)}
|
||||
${toggle('simulate', '部門模擬', '可在看得到的部門做模擬試算', g.simulate)}
|
||||
${toggle('denied', '暫不開放', '先不讓他看任何東西', state.denied.includes(p.employeeNumber))}
|
||||
</div></div>
|
||||
<div><h4>另外可以看的部門</h4><div class="pick">${depts.map(d => `<label><input type="checkbox" name="depts" value="${esc(d)}" ${(g.depts || []).includes(d) ? 'checked' : ''}>${esc(d)}</label>`).join('') || '<span class="none">沒有部門資料</span>'}</div></div>
|
||||
<div><h4>另外可以看的組</h4><div class="pick">${groups.map(k => `<label><input type="checkbox" name="groups" value="${esc(k)}" ${(g.groups || []).includes(k) ? 'checked' : ''}>${esc(k.replace('|', ' · '))}</label>`).join('') || '<span class="none">沒有組資料</span>'}</div></div>
|
||||
<div class="actions"><span class="status" role="status">${esc(message[p.employeeNumber] || '')}</span>
|
||||
<button type="button" class="btn" onclick="editing=null;draw()">取消</button>
|
||||
<button type="button" class="btn primary" onclick="save('${esc(p.employeeNumber)}')">儲存</button></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function draw() {
|
||||
const q = document.getElementById('q').value.trim();
|
||||
document.getElementById('tabs').innerHTML = FILTERS.map(([key, label, test]) =>
|
||||
`<button type="button" class="tab" aria-pressed="${filter === key}" onclick="filter='${key}';draw()">${label}<span class="n">${state.people.filter(test).length}</span></button>`).join('');
|
||||
const test = FILTERS.find(f => f[0] === filter)[2];
|
||||
const rows = state.people.filter(test).filter(p => !q || [p.employeeNumber, p.name, p.dept, p.group].some(v => String(v || '').includes(q)));
|
||||
document.getElementById('rows').innerHTML = rows.map(p => `<div class="row">
|
||||
<div class="who"><b>${esc(p.name)}</b><span>${esc(p.employeeNumber)} ${esc(p.title)}</span></div>
|
||||
<div class="where">${esc(p.dept || '—')}<br><span>${esc(p.group || '')}</span></div>
|
||||
<div class="chips">${chips(p)}</div>
|
||||
<div class="act">${p.permission.admin ? '' : `<button type="button" class="btn" onclick="editing=editing==='${esc(p.employeeNumber)}'?null:'${esc(p.employeeNumber)}';draw()" aria-expanded="${editing === p.employeeNumber}">${editing === p.employeeNumber ? '收起' : '調整'}</button>`}</div>
|
||||
${editing === p.employeeNumber ? editor(p) : ''}
|
||||
</div>`).join('') || '<div class="empty">沒有符合的人</div>';
|
||||
}
|
||||
|
||||
async function save(id) {
|
||||
const box = document.getElementById('editor');
|
||||
const on = name => box.querySelector(`[name=${name}]`).checked;
|
||||
const picked = name => [...box.querySelectorAll(`[name=${name}]:checked`)].map(i => i.value);
|
||||
const grant = { company: on('company'), personDetail: on('personDetail'), simulate: on('simulate'), depts: picked('depts'), groups: picked('groups'), note: '權限頁設定' };
|
||||
const empty = !grant.company && !grant.personDetail && !grant.simulate && !grant.depts.length && !grant.groups.length;
|
||||
const response = await fetch('/api/permissions', { method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ employeeNumber: id, grant: empty ? null : grant, denied: on('denied') }) });
|
||||
message[id] = response.ok ? '已儲存' : `儲存失敗(${response.status})`;
|
||||
await load();
|
||||
}
|
||||
|
||||
// 修改紀錄:每一筆的改前、改後轉成標籤。
|
||||
let logShown = 20;
|
||||
function grantChips(entry) {
|
||||
if (!entry) return [];
|
||||
const out = [];
|
||||
if (entry.denied) out.push(['warn', '暫不開放']);
|
||||
const g = entry.grant || {};
|
||||
if (g.company) out.push(['manual', '全公司檢視']);
|
||||
(g.depts || []).forEach(d => out.push(['manual', `部門 ${d}`]));
|
||||
(g.groups || []).forEach(k => out.push(['manual', `組 ${String(k).split('|')[1] || k}`]));
|
||||
if (g.personDetail) out.push(['manual', '個人明細']);
|
||||
if (g.simulate) out.push(['manual', '模擬']);
|
||||
return out;
|
||||
}
|
||||
function drawLog() {
|
||||
const log = state.log || [];
|
||||
const box = document.getElementById('log');
|
||||
if (!log.length) { box.innerHTML = '<div class="empty">還沒有修改紀錄。</div>'; return; }
|
||||
const names = new Map(state.people.map(p => [String(p.employeeNumber), p.name]));
|
||||
const who = id => names.get(String(id)) ? `${esc(names.get(String(id)))}(${esc(id)})` : esc(id);
|
||||
const chipHtml = (list, cls = '') => list.length ? list.map(([c, t]) => `<span class="chip ${c} ${cls}">${esc(t)}</span>`).join('') : '<span class="none">沒有手動權限</span>';
|
||||
box.innerHTML = log.slice(0, logShown).map(e => {
|
||||
const before = grantChips(e.before);
|
||||
const after = grantChips(e.after);
|
||||
const keys = list => new Set(list.map(([, t]) => t));
|
||||
const a = keys(after);
|
||||
const b = keys(before);
|
||||
const removed = before.filter(([, t]) => !a.has(t));
|
||||
const added = after.filter(([, t]) => !b.has(t));
|
||||
const kept = after.filter(([, t]) => b.has(t));
|
||||
const change = !removed.length && !added.length ? '<span class="none">沒有變更(重新儲存)</span>'
|
||||
: `${removed.length ? `${chipHtml(removed, 'old')}<span class="arrow">→</span>` : ''}${added.length ? chipHtml(added) : '<span class="none">移除</span>'}${kept.length ? `<span class="none">(保留:${kept.map(([, t]) => esc(t)).join('、')})</span>` : ''}`;
|
||||
return `<div class="log-row"><time datetime="${esc(e.at)}">${esc(new Date(e.at).toLocaleString('zh-TW', { hour12: false }))}</time>
|
||||
<div><b>${who(e.employeeNumber)}</b></div>
|
||||
<div class="change">${change}</div>
|
||||
<div class="by">由 ${who(e.by)}</div></div>`;
|
||||
}).join('') + (log.length > logShown ? `<div class="log-row" style="display:block;"><button type="button" class="btn more" onclick="logShown+=50;drawLog()">再顯示 ${Math.min(50, log.length - logShown)} 筆</button></div>` : '');
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const response = await fetch('/api/permissions', { cache: 'no-store' });
|
||||
if (response.status === 401) { location.href = '/api/auth/login'; return; }
|
||||
if (!response.ok) { document.getElementById('rows').innerHTML = '<div class="empty">只有最高管理者可以管理權限。</div>'; return; }
|
||||
state = await response.json();
|
||||
drawLog();
|
||||
if (state.preview && !state.people.length) { document.getElementById('rows').innerHTML = '<div class="empty">本機預覽沒有 HR 名單。</div>'; return; }
|
||||
draw();
|
||||
}
|
||||
load();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,11 +1,16 @@
|
||||
// 預排異動(第一部分:預計離職、預計新進)。存在 COST_MODEL_DATA_DIR/planned-changes.json(不進 Git),
|
||||
// 預排異動(預計離職、預計新進、預計轉調)。存在 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])$/;
|
||||
@@ -48,13 +53,27 @@ export function normalizePlans(input = {}) {
|
||||
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 REASONS = ['hr_left', 'hr_leave_date', 'hr_joined', 'expired', 'manual'];
|
||||
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'].includes(entry.kind) || !REASONS.includes(entry.reason)) return [];
|
||||
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, history };
|
||||
return { departures, hires, transfers, history };
|
||||
}
|
||||
|
||||
const addMonths = (month, n) => {
|
||||
@@ -85,6 +104,13 @@ function matchHires(hires, hrPeople) {
|
||||
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');
|
||||
@@ -107,13 +133,29 @@ export function reconcilePlans(plans, people, now = new Date()) {
|
||||
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, history: [...(plans.history || []), ...removed].slice(-100) }, 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)) return people;
|
||||
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;
|
||||
@@ -131,7 +173,38 @@ export function applyPlans(people, plans, { year, fullYearDefault = false } = {}
|
||||
}, { 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 });
|
||||
}
|
||||
return out;
|
||||
// 預計轉調:生效月份在報表年度之後先不套用;在之前就整年算新單位;年度中間則按月拆成兩段。
|
||||
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 已完成/過期未完成)。
|
||||
@@ -146,8 +219,27 @@ export function planStatus(plans, people, now = new Date()) {
|
||||
});
|
||||
const hires = (plans.hires || []).map((plan) => ({ ...plan, status: thisMonth > plan.startMonth ? 'overdue' : 'pending',
|
||||
autoRemoveAfter: addMonths(plan.startMonth, GRACE_MONTHS) }));
|
||||
return { departures, hires, history: [...(plans.history || [])].reverse().slice(0, 30),
|
||||
overdue: [...departures, ...hires].filter(p => p.status === 'overdue').length };
|
||||
// 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) {
|
||||
@@ -157,7 +249,7 @@ export function createPlanStore(source) {
|
||||
return {
|
||||
async load() {
|
||||
if (state) return state;
|
||||
state = { departures: [], hires: [], history: [] };
|
||||
state = { departures: [], hires: [], transfers: [], history: [] };
|
||||
const text = file ? file.read() : null;
|
||||
if (text !== null) state = normalizePlans(JSON.parse(text));
|
||||
return state;
|
||||
|
||||
+12
-1
@@ -161,6 +161,14 @@
|
||||
// 區塊:沿用主看板的底色(CODA 藍、發票琥珀、組別綠灰),前後深淺交錯。
|
||||
const block = (kind, title, body) => `<div class="sx-block b-${kind}"><div class="sx-bh"><span class="sx-dot"></span>${title}</div>${body}</div>`;
|
||||
|
||||
|
||||
// 人員異動:只給姓名和生效月份。不分離職或轉調,也不說轉調去哪,部長只需要知道編制什麼時候變。
|
||||
function changesTable(list) {
|
||||
const rows = list.map(c => `<tr><td>${esc(c.name)}</td><td>${c.kind === 'leave' ? '離開本部門' : '加入本部門'}</td><td class="num">${esc(c.month)}</td></tr>`).join('');
|
||||
return `<div class="sx-scroll"><table><thead><tr><th>姓名</th><th>異動</th><th class="num">生效月份</th></tr></thead><tbody>${rows}</tbody></table></div>
|
||||
<div class="sx-sub" style="margin-top:4px;">已經排定、HR 還沒更新的異動。上面的數字已經照這些算了。</div>`;
|
||||
}
|
||||
|
||||
function deptCard(d, data, simOpen) {
|
||||
const showCost = d.groups.some(g => typeof g.totalCost === 'number');
|
||||
const groupsRows = d.groups.map(g => g.missing ? `<tr><td>${esc(g.group)}</td><td colspan="${showCost ? 5 : 4}" class="sx-sub">目前沒有資料</td></tr>` :
|
||||
@@ -177,6 +185,7 @@
|
||||
${kpi(d.multiplier?.company ? `倍率(${esc(d.multiplier.company)}全公司)` : '部門倍率', times(d.multiplier?.value), '部門內部成本(P+A+G,不含外包)÷ A 成本 × 人薪倍率')}
|
||||
</div>`)}
|
||||
${d.invoice?.indicators ? block('inv2', '發票佔比怎麼來的', indicatorsBlock(d)) : ''}
|
||||
${d.changes && d.changes.length ? block('chg', '人員異動', changesTable(d.changes)) : ''}
|
||||
${block('people', '人力', `<div class="sx-kpis">
|
||||
${d.headcount ? kpi('人數', `${d.headcount.total} 人`, headcountText(d.headcount)) : ''}
|
||||
${typeof d.totalCost === 'number' ? kpi('部門總人力成本(年)', money(d.totalCost), '正職年薪 × 人薪倍率 + 外包 × 外包倍率,不含實習生') : ''}
|
||||
@@ -187,7 +196,7 @@
|
||||
${block('group', '各組', `<div class="sx-scroll"><table><thead><tr><th>組</th><th class="num">人數</th><th class="num">實際 CODA</th><th class="num">平均日 CODA</th><th class="num">定錨 CODA</th>${showCost ? '<th class="num">總人力成本(年)</th>' : ''}</tr></thead><tbody>${groupsRows}</tbody></table></div>
|
||||
${showCost ? '<div class="sx-sub" style="margin-top:4px;">人數是算 CODA 的人(A 與外包);總人力成本含組內所有人(含 P、外包,不含實習生)。</div>' : ''}`)}
|
||||
${data.me.simulate && d.full ? simSection(d, simOpen) : ''}
|
||||
${d.people && mode === 'page' ? `<details data-key="people|${esc(d.dept)}" ${isOpen(`people|${d.dept}`, false) ? 'open' : ''}><summary>個人明細(${d.people.length} 人)</summary><div style="margin:8px 0;">${salaryButton('顯示薪資', '隱藏薪資')}</div>${peopleTable(d.people)}</details>` : ''}
|
||||
${d.people && mode === 'page' ? `<details data-key="people|${esc(d.dept)}" ${isOpen(`people|${d.dept}`, false) ? 'open' : ''}><summary>個人明細(${d.people.length} 人)</summary>${peopleTable(d.people)}</details>` : ''}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
@@ -318,6 +327,8 @@
|
||||
}
|
||||
const parts = [];
|
||||
if (data.company) parts.push(`<div class="sx-card"><h2>全公司</h2>${block('inv', '發票', `<div class="sx-kpis"><div class="sx-kpi"><div class="label">年度發票目標</div><div class="value">${money(data.company.invoiceTotal)}</div></div></div><div class="sx-sub">全公司沒有定錨 CODA 合計(調動時原單位不降、新單位增加,加總會重複)。</div>`)}</div>`);
|
||||
// 「顯示薪資」放在整頁最上面,部長一進來就找得到(按一下,頁面上所有人的薪資一起顯示)。
|
||||
if (data.depts.some(d => d.people)) parts.unshift(`<div class="sx-row" style="margin:0 0 8px;">${salaryButton('顯示薪資', '隱藏薪資')}</div>`);
|
||||
for (const d of data.depts) parts.push(deptCard(d, data, false));
|
||||
if (!data.depts.length && !data.company) parts.push('<div class="sx-card">目前沒有可以看的部門或組別。</div>');
|
||||
root.innerHTML = parts.join('');
|
||||
|
||||
+24
-1
@@ -66,7 +66,29 @@ function anchoredGroup(anchors, dept, group) {
|
||||
return g ? { annual: round(g.value), h1: round(g.h1), h2: g.h2 === null ? null : round(g.h2) } : null;
|
||||
}
|
||||
|
||||
export function buildScopedView(model, anchors, permission, { year } = {}) {
|
||||
// 部長看得到的人員異動:誰離開、誰加入、哪個月生效。
|
||||
// 刻意不分離職或轉調,也不顯示轉調去哪裡,部長只需要知道編制什麼時候變。
|
||||
// 只掛在看得到整個部門的人身上;只看單一組別的人不給,免得看到別組的人。
|
||||
export function changesFor(dept, model, plans) {
|
||||
const name = (employeeNumber) => (model.people || [])
|
||||
.find(p => String(p.employeeNumber || '') === String(employeeNumber))?.name || '';
|
||||
const out = [];
|
||||
for (const person of model.people || []) {
|
||||
if (String(person.dept || '').trim() !== dept) continue;
|
||||
if (person.plannedLeave) out.push({ kind: 'leave', name: person.name || '', month: person.plannedLeave });
|
||||
// 拆成兩段時,前段掛在原部門,那是「離開」不是「加入」(下面用 fromDept 處理)。
|
||||
if (person.plannedTransfer && person.transferSplit !== 'before') out.push({ kind: 'join', name: person.name || '', month: person.plannedTransfer });
|
||||
if (person.plannedHire) out.push({ kind: 'join', name: person.name || '', month: person.plannedHire });
|
||||
}
|
||||
for (const plan of plans?.transfers || []) {
|
||||
if (String(plan.fromDept || '').trim() !== dept) continue;
|
||||
out.push({ kind: 'leave', name: name(plan.employeeNumber), month: plan.effectiveMonth });
|
||||
}
|
||||
return out.filter(change => change.name && change.month)
|
||||
.sort((a, b) => String(a.month).localeCompare(String(b.month)) || a.name.localeCompare(b.name, 'zh-Hant'));
|
||||
}
|
||||
|
||||
export function buildScopedView(model, anchors, permission, { year, plans } = {}) {
|
||||
const allDepts = Object.keys(model.codaGroups || {});
|
||||
const fullDepts = permission.admin || permission.company ? allDepts : allDepts.filter(d => permission.depts.includes(d));
|
||||
const groupOnly = permission.groups.map(key => key.split('|')).filter(([d]) => !fullDepts.includes(d));
|
||||
@@ -86,6 +108,7 @@ export function buildScopedView(model, anchors, permission, { year } = {}) {
|
||||
multiplier: multiplierFor(model, dept),
|
||||
headcount: headcountByKind(model.people.filter(p => (p.dept || '').trim() === dept)),
|
||||
totalCost: round(model.staffCost?.depts?.[dept]),
|
||||
changes: changesFor(dept, model, plans),
|
||||
anchoredInvoice: anchoredInvoice ? { annual: round(anchoredInvoice.annual), h1: round(anchoredInvoice.h1), h2: anchoredInvoice.h2 === null ? null : round(anchoredInvoice.h2) } : null,
|
||||
groups: Object.entries(data.groups).map(([group, g]) => ({
|
||||
group, actualCoda: round(g.coda), avgDailyCoda: round(g.avgDailyCoda), headcount: g.people.length,
|
||||
|
||||
@@ -121,6 +121,7 @@ const allowedStaticFiles = new Map([
|
||||
['/calc-core.js', ['calc-core.js', 'text/javascript; charset=utf-8']],
|
||||
['/scope-ui.js', ['scope-ui.js', 'text/javascript; charset=utf-8']],
|
||||
['/i18n.js', ['i18n.js', 'text/javascript; charset=utf-8']],
|
||||
['/buttons.css', ['buttons.css', 'text/css; charset=utf-8']],
|
||||
// Poppins (SIL OFL 1.1), subset to Latin and digits for numerals; see fonts/OFL-NOTICE.txt.
|
||||
['/fonts/poppins-light.woff', ['fonts/poppins-light.woff', 'font/woff']],
|
||||
['/fonts/poppins-regular.woff', ['fonts/poppins-regular.woff', 'font/woff']],
|
||||
@@ -151,7 +152,7 @@ async function loadBoardInput(session, options = {}) {
|
||||
}
|
||||
if (options.plans === false) return board;
|
||||
const plans = await planStore.load();
|
||||
if (!plans.departures.length && !plans.hires.length) return board;
|
||||
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 }) } };
|
||||
}
|
||||
@@ -931,12 +932,19 @@ const server = createServer(async (request, response) => {
|
||||
}
|
||||
}
|
||||
|
||||
// 依權限的頁面:主管、全公司檢視看 /my;權限管理頁只有最高管理者。
|
||||
if (request.method === 'GET' && (url.pathname === '/my' || url.pathname === '/permissions' || url.pathname === '/archive')) {
|
||||
// 權限管理已經搬進主看板,舊網址導回看板並直接打開那個區塊(別人存的連結不會壞)。
|
||||
if (request.method === 'GET' && url.pathname === '/permissions') {
|
||||
const session = requireAuth(request, response);
|
||||
if (!session) return;
|
||||
return redirect(response, isProduction && !isTopAdmin(session.claims) ? '/my' : '/?view=permissions');
|
||||
}
|
||||
|
||||
// 依權限的頁面:主管、全公司檢視看 /my;年度封存只有最高管理者。
|
||||
if (request.method === 'GET' && (url.pathname === '/my' || url.pathname === '/archive')) {
|
||||
const session = requireAuth(request, response);
|
||||
if (!session) return;
|
||||
if (url.pathname !== '/my' && isProduction && !isTopAdmin(session.claims)) return redirect(response, '/my');
|
||||
const content = await readFile(resolve(root, { '/my': 'my.html', '/permissions': 'permissions.html', '/archive': 'archive.html' }[url.pathname]));
|
||||
const content = await readFile(resolve(root, { '/my': 'my.html', '/archive': 'archive.html' }[url.pathname]));
|
||||
// 登出(含公司帳號)會轉到公司登入伺服器,form-action 要允許它。
|
||||
const authOrigin = (() => { try { return oidc.issuer ? new URL(oidc.issuer).origin : ''; } catch { return ''; } })();
|
||||
response.writeHead(200, {
|
||||
@@ -1002,7 +1010,8 @@ const server = createServer(async (request, response) => {
|
||||
const model = computeModel(board.payload);
|
||||
const year = Number(board.payload.reportYear || board.payload.globalParams?.reportYear || await getCurrentYear());
|
||||
const anchors = await anchorStore.evaluate(model, year);
|
||||
return sendJson(response, 200, { ...buildScopedView(model, anchors, permission, { year }), usdRate: Number(board.payload.globalParams?.usdRate) || 30 });
|
||||
// 預排傳進去只為了「誰離開」那份清單(轉調後的人已經不在原部門,要靠 fromDept 才找得到)。
|
||||
return sendJson(response, 200, { ...buildScopedView(model, anchors, permission, { year, plans: await planStore.load() }), usdRate: Number(board.payload.globalParams?.usdRate) || 30 });
|
||||
}
|
||||
|
||||
// 對外接口:只接受 Bearer token(不用登入 session、不套工號白名單),只讀。
|
||||
|
||||
@@ -9,6 +9,7 @@ export const PARAM_KEYS = Object.freeze([
|
||||
'contractorMultiplier', 'usdRate',
|
||||
]);
|
||||
const MAX_GROUPS = 300;
|
||||
const MAX_SHARE_RULES = 20;
|
||||
// Invoice role per company (default for its departments) and per department:
|
||||
// bear = carries invoice, share = cost goes into the invoice pool but gets no allocation,
|
||||
// exclude = outside the invoice (shown as cost × 人薪倍率).
|
||||
@@ -35,6 +36,26 @@ function groupKeys(list) {
|
||||
return [...new Set(keys)].slice(0, MAX_GROUPS);
|
||||
}
|
||||
|
||||
// CODA 分配規則:from 的部門整包 CODA 分給 to 的部門(依各自 CODA 比例)。
|
||||
// 格式不對的整條跳過;已經在 from 的部門不會再被當成 to。
|
||||
function shareRules(list) {
|
||||
if (list === undefined) return undefined;
|
||||
if (!Array.isArray(list)) throw new TypeError('codaShareRules must be an array');
|
||||
const names = value => [...new Set((Array.isArray(value) ? value : [])
|
||||
.filter(item => typeof item === 'string')
|
||||
.map(item => item.trim().slice(0, 80))
|
||||
.filter(Boolean))].slice(0, MAX_GROUPS);
|
||||
const rules = [];
|
||||
for (const rule of list.slice(0, MAX_SHARE_RULES)) {
|
||||
if (!rule || typeof rule !== 'object' || Array.isArray(rule)) continue;
|
||||
const from = names(rule.from);
|
||||
const to = names(rule.to).filter(name => !from.includes(name));
|
||||
if (!from.length || !to.length) continue;
|
||||
rules.push({ company: String(rule.company || '').trim().slice(0, 80), from, to, noDeptP: Boolean(rule.noDeptP) });
|
||||
}
|
||||
return rules;
|
||||
}
|
||||
|
||||
export function normalizeSettings(input = {}) {
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new TypeError('settings must be an object');
|
||||
const output = {};
|
||||
@@ -46,6 +67,8 @@ export function normalizeSettings(input = {}) {
|
||||
output.invoiceRoles = { companies: roleMap(input.invoiceRoles.companies) || {}, depts: roleMap(input.invoiceRoles.depts) || {} };
|
||||
}
|
||||
if (cgLeadGroups) output.cgLeadGroups = cgLeadGroups;
|
||||
const codaShareRules = shareRules(input.codaShareRules);
|
||||
if (codaShareRules) output.codaShareRules = codaShareRules;
|
||||
if (input.params !== undefined) {
|
||||
if (!input.params || typeof input.params !== 'object' || Array.isArray(input.params)) throw new TypeError('params must be an object');
|
||||
output.params = {};
|
||||
@@ -67,5 +90,6 @@ export function applySettings(globalParams, settings) {
|
||||
...(settings.rdGroups ? { rdGroups: settings.rdGroups } : {}),
|
||||
...(settings.cgLeadGroups ? { cgLeadGroups: settings.cgLeadGroups } : {}),
|
||||
...(settings.invoiceRoles ? { invoiceRoles: settings.invoiceRoles } : {}),
|
||||
...(settings.codaShareRules ? { codaShareRules: settings.codaShareRules } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -51,3 +51,46 @@ test('a group that is both 研發 and CG Lead gets both reductions; groups still
|
||||
assert.ok(Math.abs(groups.R.coda - initial * 0.65 * 0.85) < 1e-6);
|
||||
assert.ok(Math.abs(groups.R.coda + groups.N.coda - model.codaGroups[dept].coda) < 1e-6);
|
||||
});
|
||||
|
||||
// 業務部這類單位:整包 CODA 分給四個部門,自己只算成本,不談指標。
|
||||
function shareFixture() {
|
||||
const base = { company: '夢想創造', h1Start: 1, h1End: 6, h2Start: 7, h2End: 12 };
|
||||
return {
|
||||
baseData: [
|
||||
{ ...base, name: 'a1', title: 'Artist', role: 'A - 藝術家', dept: '甲部', salary: 90000 },
|
||||
{ ...base, name: 'a2', title: 'Artist', role: 'A - 藝術家', dept: '乙部', salary: 30000 },
|
||||
{ ...base, name: 'b1', title: 'Artist', role: 'A - 藝術家', dept: '業務部', salary: 40000 },
|
||||
{ ...base, name: 'b2', title: 'Producer', role: 'P - 製作', dept: '業務部', salary: 20000 },
|
||||
],
|
||||
globalParams: { ...seed.globalParams, reportYear: 2027, orgStructure: null },
|
||||
};
|
||||
}
|
||||
|
||||
test('CODA 分配規則可由核心參數設定:來源部門歸零、不顯示倍率,總額不變', () => {
|
||||
const fixture = shareFixture();
|
||||
const before = computeModel(fixture);
|
||||
assert.ok(before.coda['業務部'] > 0);
|
||||
assert.ok(before.multiplierUnits.some(unit => unit.label === '業務部'));
|
||||
|
||||
const rules = [{ company: '夢想創造', from: ['業務部'], to: ['甲部', '乙部'] }];
|
||||
const after = computeModel({ ...fixture, globalParams: { ...fixture.globalParams, codaShareRules: rules } });
|
||||
assert.ok(Math.abs(after.coda['業務部']) < 1e-6);
|
||||
assert.equal(after.multiplierUnits.some(unit => unit.label === '業務部'), false);
|
||||
assert.ok(after.multiplierUnits.some(unit => unit.label === '甲部'));
|
||||
|
||||
const total = model => Object.values(model.coda).reduce((sum, value) => sum + value, 0);
|
||||
assert.ok(Math.abs(total(before) - total(after)) < 1e-6);
|
||||
// 依各自 CODA 比例分配:甲部的 CODA 是乙部的三倍,拿到的也是三倍。
|
||||
const gained = dept => after.coda[dept] - before.coda[dept];
|
||||
assert.ok(Math.abs(gained('甲部') / gained('乙部') - 3) < 1e-6);
|
||||
});
|
||||
|
||||
test('格式不對的 CODA 分配規則整條跳過,空陣列代表完全不分配', () => {
|
||||
const fixture = shareFixture();
|
||||
const broken = [{ from: [], to: ['甲部'] }, { from: ['業務部'], to: [] }, 'nope', null];
|
||||
const withBroken = computeModel({ ...fixture, globalParams: { ...fixture.globalParams, codaShareRules: broken } });
|
||||
const withNone = computeModel({ ...fixture, globalParams: { ...fixture.globalParams, codaShareRules: [] } });
|
||||
assert.deepEqual(withBroken.coda, withNone.coda);
|
||||
assert.ok(withNone.coda['業務部'] > 0);
|
||||
assert.ok(withNone.multiplierUnits.some(unit => unit.label === '業務部'));
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
+151
-2
@@ -12,7 +12,7 @@ const people = [
|
||||
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: [], history: [] });
|
||||
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 - 外包' }] }));
|
||||
@@ -93,10 +93,159 @@ 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: [], history: [] });
|
||||
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), []);
|
||||
});
|
||||
+18
-2
@@ -41,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());
|
||||
@@ -429,7 +442,10 @@ test('login flow: any company account gets in; only the top admin reaches the bo
|
||||
const admin = await signIn(base, provider);
|
||||
assert.equal(admin.callback.headers.get('location'), '/');
|
||||
assert.equal((await fetch(`${base}/`, { headers: { cookie: admin.cookie }, redirect: 'manual' })).status, 200);
|
||||
assert.equal((await fetch(`${base}/permissions`, { headers: { cookie: admin.cookie }, redirect: 'manual' })).status, 200);
|
||||
// 權限管理搬進主看板後,舊網址導回看板並直接打開那個區塊。
|
||||
const permRedirect = await fetch(`${base}/permissions`, { headers: { cookie: admin.cookie }, redirect: 'manual' });
|
||||
assert.equal(permRedirect.status, 302);
|
||||
assert.equal(permRedirect.headers.get('location'), '/?view=permissions');
|
||||
|
||||
// 部署重新啟動:兩個人都不用重新登入;檔案裡沒有 cookie 原始值。
|
||||
child.kill('SIGTERM');
|
||||
@@ -465,7 +481,7 @@ test('planned hires saved in 預排異動 appear on the board and persist in COS
|
||||
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: [], history: [] });
|
||||
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' };
|
||||
|
||||
@@ -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, []);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user