CI / build (push) Successful in 33s
Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
446 lines
35 KiB
JavaScript
446 lines
35 KiB
JavaScript
// 依權限的檢視與部門模擬試算(共用元件)。/my 單頁和主看板的「模擬試算」都用這一份。
|
||
// 數字都由伺服器算(/api/scope、/api/simulate),這裡只負責顯示。
|
||
// 顏色用 --sx-* 變數,放進主看板時由主看板換成自己的配色。
|
||
(function () {
|
||
// 金額依右上角的幣別顯示(i18n.js);沒有載入 i18n.js 時照舊用 NT$。
|
||
const money = v => v === null || v === undefined ? '—' : (window.PMI18n ? PMI18n.cur(v) : 'NT$ ' + Math.round(v).toLocaleString());
|
||
const num = v => Math.round(v).toLocaleString();
|
||
const amtv = v => (window.PMI18n ? PMI18n.amt(v) : num(v));
|
||
const pct = (v, digits = 1) => v === null || v === undefined ? '—' : `${(v * 100).toFixed(digits)}%`;
|
||
const times = v => v === null || v === undefined ? '—' : `${Number(v).toFixed(2)}x`;
|
||
const ratio = v => v === null || v === undefined ? '無 P' : `${Number(v).toFixed(1)} : 1`;
|
||
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||
const KINDS = [['A', 'A 藝術家'], ['P', 'P 製作'], ['O', 'O 外包'], ['intern', '實習生'], ['parttime', '工讀(算 O)']];
|
||
const KIND_LABEL = Object.fromEntries(KINDS);
|
||
const PAY_LABEL = { monthly: '月薪', daily: '日薪', hourly: '時薪' };
|
||
const MONTH_FIELDS = ['amount', 'h1Start', 'h1End', 'h2Start', 'h2End'];
|
||
const HEADCOUNT_LABELS = [['A', 'A'], ['P', 'P'], ['G', 'G 管理'], ['O', '外包'], ['intern', '實習'], ['parttime', '工讀'], ['other', '待分類']];
|
||
const DISCLAIMER = '本試算只用來快速估算加人、調薪後大約的 CODA 與發票量,結果只代表試算當下的狀態。實際數字會隨人員與參數變動,正式數字一律以每年 1 月、7 月定錨後統一公布的為準。';
|
||
|
||
const CSS = `
|
||
.sx { --sx-card-bg: var(--sx-card, #ffffff); color: var(--sx-text, #1f2328); }
|
||
.sx .sx-sub { color: var(--sx-muted, #5f6670); font-size: .85rem; }
|
||
.sx .sx-card { background: var(--sx-card-bg); border: 1px solid var(--sx-line, #e4e0d8); border-radius: 14px; padding: 18px; margin-bottom: 16px; }
|
||
.sx h2 { margin: 0 0 4px; font-size: 1.05rem; }
|
||
.sx h3 { margin: 0 0 6px; font-size: .95rem; }
|
||
.sx h4 { margin: 14px 0 6px; font-size: .85rem; color: var(--sx-muted, #5f6670); font-weight: 500; }
|
||
.sx .sx-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; margin: 12px 0; }
|
||
.sx .sx-kpi { border: 1px solid var(--sx-line, #e4e0d8); border-radius: 10px; padding: 10px 12px; }
|
||
.sx .sx-kpi .label { color: var(--sx-muted, #5f6670); font-size: .78rem; }
|
||
.sx .sx-kpi .value { font-size: 1.15rem; font-weight: 600; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||
.sx .sx-kpi .note { color: var(--sx-muted, #5f6670); font-size: .75rem; font-weight: 400; }
|
||
.sx table { width: 100%; border-collapse: collapse; font-size: .88rem; }
|
||
.sx th, .sx td { padding: 8px 6px; border-bottom: 1px solid var(--sx-line, #e4e0d8); text-align: left; vertical-align: top; }
|
||
.sx th { color: var(--sx-muted, #5f6670); font-weight: 500; font-size: .8rem; }
|
||
.sx td.num, .sx th.num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||
.sx .sx-scroll { overflow-x: auto; }
|
||
.sx .sx-tag { display: inline-block; font-size: .72rem; padding: 1px 8px; border-radius: 99px; border: 1px solid var(--sx-line, #e4e0d8); color: var(--sx-muted, #5f6670); margin-left: 6px; }
|
||
.sx .sx-warn { color: var(--sx-warn, #b4540a); }
|
||
.sx .up { color: var(--sx-up, #2f5fd0); }
|
||
.sx .down { color: var(--sx-down, #b4540a); }
|
||
.sx button { font: inherit; border: 1px solid var(--sx-line, #e4e0d8); background: var(--sx-card-bg); color: inherit; border-radius: 8px; padding: 4px 10px; cursor: pointer; }
|
||
.sx button.sx-primary { background: var(--sx-accent, #4f6bed); border-color: var(--sx-accent, #4f6bed); color: var(--sx-on-accent, #fff); }
|
||
.sx button:focus-visible, .sx select:focus-visible, .sx input:focus-visible { outline: 2px solid var(--sx-accent, #4f6bed); outline-offset: 2px; }
|
||
.sx details summary { cursor: pointer; color: var(--sx-accent, #4f6bed); margin-top: 8px; }
|
||
.sx .sx-mask { letter-spacing: 2px; color: var(--sx-muted, #5f6670); }
|
||
.sx .sx-val { display: none; }
|
||
.sx.show-salary .sx-val { display: inline; }
|
||
.sx.show-salary .sx-sal .sx-mask { display: none; }
|
||
.sx th.sal, .sx td.sal { width: 11em; min-width: 11em; }
|
||
.sx .sx-block { border-radius: 14px; padding: 14px 16px; margin: 12px 0; background: var(--sx-tint, transparent); border: 1px solid var(--sx-tint-border, transparent); }
|
||
.sx .sx-bh { display: flex; align-items: center; gap: 8px; font-weight: 600; font-size: .92rem; margin-bottom: 4px; }
|
||
.sx .sx-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--sx-dot, var(--sx-muted, #5f6670)); flex: none; }
|
||
.sx .b-coda { --sx-tint: var(--sx-tint-coda, #eef3f8); --sx-tint-border: var(--sx-tint-coda-border, #d6e1ec); --sx-dot: var(--sx-dot-coda, #5b7f98); }
|
||
.sx .b-inv { --sx-tint: var(--sx-tint-inv, #fbf4ea); --sx-tint-border: var(--sx-tint-inv-border, #ecd9bf); --sx-dot: var(--sx-dot-inv, #b5722a); }
|
||
.sx .b-inv2 { --sx-tint: var(--sx-tint-inv2, #fdf9f3); --sx-tint-border: var(--sx-tint-inv-border, #ecd9bf); --sx-dot: var(--sx-dot-inv, #b5722a); }
|
||
.sx .b-people { --sx-tint: transparent; --sx-tint-border: var(--sx-line, #e4e0d8); --sx-dot: var(--sx-muted, #5f6670); }
|
||
.sx .b-group { --sx-tint: var(--sx-tint-group, #f0f3ef); --sx-tint-border: var(--sx-tint-group-border, #d9e1d4); --sx-dot: var(--sx-dot-group, #6f8463); }
|
||
.sx .b-sim { --sx-tint: var(--sx-tint-sim, rgba(0,0,0,.035)); --sx-tint-border: var(--sx-line, #e4e0d8); --sx-dot: var(--sx-sim-bar, #9bb32a); border-left: 4px solid var(--sx-sim-bar, #c7dc4a); }
|
||
.sx .sx-block .sx-kpis { margin: 8px 0 2px; }
|
||
.sx .sx-block .sx-kpi { background: var(--sx-kpi-bg, rgba(255,255,255,.6)); border-color: var(--sx-tint-border, var(--sx-line, #e4e0d8)); }
|
||
.sx .sx-block table th, .sx .sx-block table td { border-bottom-color: var(--sx-tint-border, var(--sx-line, #e4e0d8)); }
|
||
.sx .sx-step { border-radius: 10px; padding: 10px 12px; margin: 8px 0; }
|
||
.sx .sx-step h4 { margin: 0 0 6px; }
|
||
.sx .sx-step.strong { background: var(--sx-strong, rgba(0,0,0,.04)); }
|
||
.sx select, .sx input { font: inherit; padding: 3px 6px; border: 1px solid var(--sx-line, #e4e0d8); border-radius: 6px; background: var(--sx-input, #f6f4ef); color: inherit; }
|
||
.sx .sx-sim input[type=number] { width: 110px; }
|
||
.sx .sx-sim input.m[type=number] { width: 58px; }
|
||
.sx .sx-sim input.sx-changed { border-color: var(--sx-accent, #4f6bed); box-shadow: 0 0 0 2px color-mix(in srgb, var(--sx-accent, #4f6bed) 25%, transparent); }
|
||
.sx tr.sx-changed td { background: color-mix(in srgb, var(--sx-accent, #4f6bed) 8%, transparent); }
|
||
.sx .sx-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin: 8px 0; }
|
||
.sx .sx-count { font-size: .8rem; color: var(--sx-muted, #5f6670); }
|
||
.sx .sx-pick { display: flex; gap: 6px; flex-wrap: wrap; margin: 4px 0 16px; }
|
||
.sx .sx-pick button[aria-pressed="true"] { background: var(--sx-accent, #4f6bed); border-color: var(--sx-accent, #4f6bed); color: var(--sx-on-accent, #fff); }
|
||
.sx .sx-stale { border: 1px solid var(--sx-warn, #b4540a); color: var(--sx-warn, #b4540a); border-radius: 10px; padding: 8px 12px; margin: 10px 0; font-size: .85rem; }
|
||
.sx .sx-result { border: 1px solid var(--sx-line, #e4e0d8); border-radius: 12px; padding: 6px 8px 10px; margin: 12px 0; background: var(--sx-card-bg); }
|
||
.sx .sx-result.is-stale { opacity: .55; }
|
||
.sx .sx-did { margin: 0 0 4px; padding-left: 1.2em; font-size: .88rem; }
|
||
.sx .sx-did li { margin: 2px 0; }
|
||
.sx .sx-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 10px; }
|
||
.sx .sx-change { border: 1px solid var(--sx-line, #e4e0d8); border-radius: 10px; padding: 10px 12px; background: var(--sx-card-bg); }
|
||
.sx .sx-change .label { color: var(--sx-muted, #5f6670); font-size: .78rem; }
|
||
.sx .sx-change .ba { font-variant-numeric: tabular-nums; font-size: .88rem; margin: 2px 0; }
|
||
.sx .sx-change .ba span { white-space: nowrap; }
|
||
.sx .sx-change .ba b { white-space: nowrap; font-weight: 600; }
|
||
.sx .sx-change .say { font-weight: 600; font-size: .9rem; }
|
||
.sx .sx-change .say.same { font-weight: 400; color: var(--sx-muted, #5f6670); }
|
||
.sx .sx-where { display: grid; grid-template-columns: minmax(90px, 1fr) 2fr auto; gap: 6px 10px; align-items: center; font-size: .86rem; }
|
||
.sx .sx-bar { height: 8px; border-radius: 99px; background: var(--sx-line, #e4e0d8); overflow: hidden; }
|
||
.sx .sx-bar span { display: block; height: 100%; border-radius: 99px; background: var(--sx-up, #2f5fd0); }
|
||
.sx .sx-bar span.down { background: var(--sx-down, #b4540a); }
|
||
.sx .sx-fine { font-size: .74rem; line-height: 1.5; color: var(--sx-muted, #5f6670); margin-top: 12px; padding-top: 8px; border-top: 1px solid var(--sx-line, #e4e0d8); }
|
||
.sx .sx-ind td small { display: block; color: var(--sx-muted, #5f6670); font-size: .74rem; }
|
||
`;
|
||
|
||
function injectStyle() {
|
||
if (document.getElementById('sx-style')) return;
|
||
const style = document.createElement('style');
|
||
style.id = 'sx-style';
|
||
style.textContent = CSS;
|
||
document.head.appendChild(style);
|
||
}
|
||
|
||
// mount(root, { mode, onMeta })
|
||
// mode 'page':/my 單頁,全部部門依序列出。
|
||
// mode 'simulate':主看板,一次看一個部門,模擬區直接展開。
|
||
function mount(root, { mode = 'page', onMeta } = {}) {
|
||
injectStyle();
|
||
root.classList.add('sx');
|
||
const state = { data: null, salaryShown: false, sim: {}, dept: null, loading: false, open: {} };
|
||
const isOpen = (key, fallback) => (key in state.open ? state.open[key] : fallback);
|
||
|
||
const emptySim = () => ({ additions: [], raises: {}, result: null, ran: null, stale: false, error: '' });
|
||
const simFor = dept => state.sim[dept] || (state.sim[dept] = emptySim());
|
||
const anchorText = a => !a ? '<span class="sx-sub">尚未定錨</span>'
|
||
: `${money(a.annual)}<div class="note">H1 ${money(a.h1)}${a.h2 === null ? '' : ' H2 ' + money(a.h2)}</div>`;
|
||
// 薪資:遮住和顯示兩種都先放好,切換時只換 CSS class,不重畫(畫面不會跳)。
|
||
const salaryCell = text => `<span class="sx-sal"><span class="sx-mask">••••</span><span class="sx-val">${text}</span></span>`;
|
||
const salaryButton = (labelShow, labelHide) => `<button type="button" data-act="salary" data-show="${labelShow}" data-hide="${labelHide}" aria-pressed="${state.salaryShown}">${state.salaryShown ? labelHide : labelShow}</button>`;
|
||
const monthsText = m => [m.h1Start && `${m.h1Start}–${m.h1End}`, m.h2Start && `${m.h2Start}–${m.h2End}`].filter(Boolean).join('、') || '—';
|
||
|
||
function peopleTable(people) {
|
||
const salary = p => p.dayrate !== null && p.dayrate !== undefined ? '日 ' + money(p.dayrate) : (p.salaryType === 'hourly' ? '時 ' : '') + money(p.salary);
|
||
return `<div class="sx-scroll"><table><thead><tr><th>組</th><th>姓名</th><th>職稱</th><th>職能</th><th>在職月份</th><th class="num sal">薪資</th><th class="num sal">年度成本</th></tr></thead><tbody>
|
||
${people.map(p => `<tr><td>${esc(p.group)}</td><td>${esc(p.name)}${p.isManager ? '<span class="sx-tag">主管</span>' : ''}${p.partTime ? '<span class="sx-tag">工讀</span>' : ''}${p.intern ? '<span class="sx-tag">實習</span>' : ''}${p.issue ? `<div class="sx-sub sx-warn">${esc(p.issue)}</div>` : ''}</td><td>${esc(p.title)}</td><td>${esc((p.role || '').split(' - ')[0] || '待分類')}</td>
|
||
<td>${monthsText(p.months)} 月</td>
|
||
<td class="num sal">${salaryCell(salary(p))}</td><td class="num sal">${salaryCell(money(p.cost || p.invoiceCost))}</td></tr>`).join('')}
|
||
</tbody></table></div>`;
|
||
}
|
||
|
||
// --- 部門的數字:倍率、發票佔比、三個指標、人數、總人力成本 ---
|
||
function headcountText(h) {
|
||
return HEADCOUNT_LABELS.filter(([k]) => h[k]).map(([k, l]) => `${l} ${h[k]}`).join('・') || '—';
|
||
}
|
||
|
||
function invoiceKpi(d) {
|
||
if (!d.invoice) return '<div class="sx-kpi"><div class="label">年度發票目標</div><div class="value">—</div><div class="note">這個部門不分配發票</div></div>';
|
||
const a = d.anchoredInvoice;
|
||
const halves = a
|
||
? `定錨:上半年 ${money(a.h1)}${a.h2 === null ? '' : `/下半年 ${money(a.h2)}`}`
|
||
: `上半年 ${money(d.invoice.h1)}/下半年 ${money(d.invoice.h2)}(定錨前預估)`;
|
||
return `<div class="sx-kpi"><div class="label">年度發票目標</div><div class="value">${money(d.invoice.annual)}</div>
|
||
<div class="note">佔全公司 ${pct(d.invoice.share)}</div><div class="note">${halves}</div>${a ? `<div class="note">定錨後全年:${money(a.annual)}</div>` : ''}</div>`;
|
||
}
|
||
|
||
function indicatorsBlock(d) {
|
||
const ind = d.invoice?.indicators;
|
||
if (!ind) return '';
|
||
const rows = [
|
||
['指標 1 P 佔比', ind.p, '你部門 P 的成本,佔四個出發票部門 P 成本總和的比例。'],
|
||
['指標 2 A 佔比', ind.a, '你部門 A 的成本,佔四個出發票部門 A 成本總和的比例。'],
|
||
['指標 3 P 輕重', ind.s, 'P 成本 ×(P 成本 ÷ A 成本,A 含常態型外包),再換算成佔比。P 相對 A 越重,分得越多。'],
|
||
];
|
||
return `<div class="sx-sub">發票佔比 = 三個指標各自乘上權重後加總。下面是你部門的三個指標:</div>
|
||
<div class="sx-scroll"><table class="sx-ind"><thead><tr><th>指標</th><th class="num">你部門</th><th class="num">權重</th><th class="num">貢獻</th></tr></thead><tbody>
|
||
${rows.map(([name, v, hint]) => `<tr><td>${name}<small>${hint}</small></td><td class="num">${pct(v.value)}</td><td class="num">${pct(v.weight, 0)}</td><td class="num">${pct(v.value * v.weight, 2)}</td></tr>`).join('')}
|
||
<tr><td><b>發票佔比</b></td><td></td><td></td><td class="num"><b>${pct(d.invoice.share, 2)}</b></td></tr>
|
||
</tbody></table></div>
|
||
<div class="sx-sub" style="margin-top:6px;">A:P 成本比(A 含外包 ÷ P):你部門 <b>${ratio(ind.apRatio)}</b>,四個部門整體 ${ratio(ind.overallApRatio)}。數字越大,代表每 1 元 P 成本對應的 A 越多。</div>`;
|
||
}
|
||
|
||
// 區塊:沿用主看板的底色(CODA 藍、發票琥珀、組別綠灰),前後深淺交錯。
|
||
const block = (kind, title, body) => `<div class="sx-block b-${kind}"><div class="sx-bh"><span class="sx-dot"></span>${title}</div>${body}</div>`;
|
||
|
||
|
||
// 人員異動:只給姓名和生效月份。不分離職或轉調,也不說轉調去哪,部長只需要知道編制什麼時候變。
|
||
function changesTable(list) {
|
||
const rows = list.map(c => `<tr><td>${esc(c.name)}</td><td>${c.kind === 'leave' ? '離開本部門' : '加入本部門'}</td><td class="num">${esc(c.month)}</td></tr>`).join('');
|
||
return `<div class="sx-scroll"><table><thead><tr><th>姓名</th><th>異動</th><th class="num">生效月份</th></tr></thead><tbody>${rows}</tbody></table></div>
|
||
<div class="sx-sub" style="margin-top:4px;">已經排定、HR 還沒更新的異動。上面的數字已經照這些算了。</div>`;
|
||
}
|
||
|
||
function deptCard(d, data, simOpen) {
|
||
const showCost = d.groups.some(g => typeof g.totalCost === 'number');
|
||
const groupsRows = d.groups.map(g => g.missing ? `<tr><td>${esc(g.group)}</td><td colspan="${showCost ? 5 : 4}" class="sx-sub">目前沒有資料</td></tr>` :
|
||
`<tr><td>${esc(g.group)}</td><td class="num">${g.headcount} 人</td><td class="num">${money(g.actualCoda)}</td><td class="num">${money(g.avgDailyCoda)}</td><td class="num">${anchorText(g.anchoredCoda)}</td>${showCost ? `<td class="num">${money(g.totalCost)}</td>` : ''}</tr>`).join('');
|
||
const kpi = (label, value, ...notes) => `<div class="sx-kpi"><div class="label">${label}</div><div class="value">${value}</div>${notes.filter(Boolean).map(n => `<div class="note">${n}</div>`).join('')}</div>`;
|
||
const full = d.full ? `
|
||
${block('coda', 'CODA', `<div class="sx-kpis">
|
||
${kpi('實際 CODA(部門)', money(d.actualCoda))}
|
||
${kpi('平均日 CODA(部門)', money(d.avgDailyCoda))}
|
||
<div class="sx-kpi"><div class="label">定錨 CODA(部門=各組加總)</div><div class="value">${anchorText(d.anchoredCoda)}</div></div>
|
||
</div>`)}
|
||
${block('inv', '發票與倍率', `<div class="sx-kpis">
|
||
${invoiceKpi(d)}
|
||
${kpi(d.multiplier?.company ? `倍率(${esc(d.multiplier.company)}全公司)` : '部門倍率', times(d.multiplier?.value), '部門內部成本(P+A+G,不含外包)÷ A 成本 × 人薪倍率')}
|
||
</div>`)}
|
||
${d.invoice?.indicators ? block('inv2', '發票佔比怎麼來的', indicatorsBlock(d)) : ''}
|
||
${d.changes && d.changes.length ? block('chg', '人員異動', changesTable(d.changes)) : ''}
|
||
${block('people', '人力', `<div class="sx-kpis">
|
||
${d.headcount ? kpi('人數', `${d.headcount.total} 人`, headcountText(d.headcount)) : ''}
|
||
${typeof d.totalCost === 'number' ? kpi('部門總人力成本(年)', money(d.totalCost), '正職年薪 × 人薪倍率 + 外包 × 外包倍率,不含實習生') : ''}
|
||
</div>`)}` : '';
|
||
return `<section class="sx-card">
|
||
<h2>${esc(d.dept)}${d.full ? '' : '<span class="sx-tag">只看組別</span>'}</h2>
|
||
${full}
|
||
${block('group', '各組', `<div class="sx-scroll"><table><thead><tr><th>組</th><th class="num">人數</th><th class="num">實際 CODA</th><th class="num">平均日 CODA</th><th class="num">定錨 CODA</th>${showCost ? '<th class="num">總人力成本(年)</th>' : ''}</tr></thead><tbody>${groupsRows}</tbody></table></div>
|
||
${showCost ? '<div class="sx-sub" style="margin-top:4px;">人數是算 CODA 的人(A 與外包);總人力成本含組內所有人(含 P、外包,不含實習生)。</div>' : ''}`)}
|
||
${data.me.simulate && d.full ? simSection(d, simOpen) : ''}
|
||
${d.people && mode === 'page' ? `<details data-key="people|${esc(d.dept)}" ${isOpen(`people|${d.dept}`, false) ? 'open' : ''}><summary>個人明細(${d.people.length} 人)</summary>${peopleTable(d.people)}</details>` : ''}
|
||
</section>`;
|
||
}
|
||
|
||
// --- 模擬試算 ---
|
||
const ROW_LABELS = { actualCoda: '實際 CODA(部門)', avgDailyCoda: '平均日 CODA(部門)', anchoredCoda: '定錨 CODA(部門)', invoice: '年度發票目標', anchoredInvoice: '定錨後發票', multiplier: '部門倍率', invoiceShare: '發票佔比' };
|
||
const ROW_ORDER = ['actualCoda', 'avgDailyCoda', 'anchoredCoda', 'invoice', 'invoiceShare', 'anchoredInvoice', 'multiplier'];
|
||
|
||
function changeCard(r, anchored) {
|
||
const label = ROW_LABELS[r.key];
|
||
if (r.before === null && r.after === null) {
|
||
if (r.key.startsWith('anchored') && !anchored) return `<div class="sx-change"><div class="label">${label}</div><div class="say same">尚未定錨,定錨後才有</div></div>`;
|
||
return '';
|
||
}
|
||
const fmt = r.key === 'multiplier' ? times : r.key === 'invoiceShare' ? v => pct(v, 2) : money;
|
||
const delta = r.delta ?? 0;
|
||
const tiny = r.key === 'invoiceShare' ? Math.abs(delta) < 0.00005 : r.key === 'multiplier' ? Math.abs(delta) < 0.005 : Math.abs(delta) < 1;
|
||
let say;
|
||
if (tiny) say = '<div class="say same">不變</div>';
|
||
else {
|
||
const cls = delta > 0 ? 'up' : 'down';
|
||
const word = delta > 0 ? '▲ 增加' : '▼ 減少';
|
||
const amount = r.key === 'multiplier' ? Math.abs(delta).toFixed(2)
|
||
: r.key === 'invoiceShare' ? `${Math.abs(delta * 100).toFixed(2)} 個百分點`
|
||
: amtv(Math.abs(delta));
|
||
const rel = r.key !== 'invoiceShare' && r.before ? `(${delta > 0 ? '+' : '−'}${Math.abs(delta / r.before * 100).toFixed(1)}%)` : '';
|
||
say = `<div class="say ${cls}">${word} ${amount}${rel}</div>`;
|
||
}
|
||
return `<div class="sx-change"><div class="label">${label}</div><div class="ba"><span>${fmt(r.before)}</span> → <b>${fmt(r.after)}</b></div>${say}</div>`;
|
||
}
|
||
|
||
function didList(d, ran) {
|
||
const people = new Map((d.people || []).map(p => [p.employeeNumber, p]));
|
||
const items = [];
|
||
ran.additions.forEach(a => {
|
||
const pay = a.amount === '' ? '—' : 'NT$ ' + num(Number(a.amount) || 0);
|
||
items.push(`加 1 人:${esc(KIND_LABEL[a.kind] || a.kind)}・${esc(a.group || '未分組')}・${PAY_LABEL[a.salaryType] || ''} ${pay}・${monthsText(a)} 月`);
|
||
});
|
||
Object.entries(ran.raises).forEach(([id, amount]) => {
|
||
const p = people.get(id);
|
||
const current = p ? p.salary : null;
|
||
const diff = current !== null && current !== undefined ? `<span class="sx-val">(${amount - current >= 0 ? '+' : '−'}${num(Math.abs(amount - current))})</span>` : '';
|
||
items.push(`調薪:${esc(p?.name || id)}${p?.group ? `(${esc(p.group)})` : ''} → ${p?.salaryType === 'hourly' ? '時薪 ' : ''}NT$ ${num(amount)}${diff}`);
|
||
});
|
||
return items.length ? `<ul class="sx-did">${items.map(i => `<li>${i}</li>`).join('')}</ul>` : '<div class="sx-sub">沒有調整任何東西(目前的數字)。</div>';
|
||
}
|
||
|
||
function whereBlock(d, st) {
|
||
const ran = st.ran;
|
||
const added = {};
|
||
ran.additions.forEach(a => { const g = a.group || '未分組'; added[g] = (added[g] || 0) + 1; });
|
||
const raisedIn = {};
|
||
Object.keys(ran.raises).forEach(id => { const g = (d.people || []).find(p => p.employeeNumber === id)?.group || '未分組'; raisedIn[g] = (raisedIn[g] || 0) + 1; });
|
||
// 加的人或調薪的人不在算 CODA 的組裡(例如 P),也列出來,標「不算 CODA」。
|
||
const known = new Set(st.result.groups.map(g => g.group));
|
||
const extra = [...new Set([...Object.keys(added), ...Object.keys(raisedIn)])].filter(g => !known.has(g))
|
||
.map(group => ({ group, before: { actualCoda: 0, headcount: 0 }, after: { actualCoda: 0, headcount: 0 }, noCoda: true }));
|
||
const groups = [...st.result.groups, ...extra].map(g => ({ ...g, delta: g.after.actualCoda - g.before.actualCoda, people: (g.after.headcount || 0) - (g.before.headcount || 0) }))
|
||
.filter(g => g.delta !== 0 || g.people !== 0 || added[g.group] || raisedIn[g.group])
|
||
.sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta));
|
||
if (!groups.length) return '<div class="sx-sub">各組的實際 CODA 都沒有變。</div>';
|
||
const max = Math.max(...groups.map(g => Math.abs(g.delta)), 1);
|
||
return `<div class="sx-where">${groups.map(g => {
|
||
const tags = [g.people ? `${g.people > 0 ? '+' : '−'}${Math.abs(g.people)} 人` : (added[g.group] ? `+${added[g.group]} 人(不算 CODA)` : ''), raisedIn[g.group] ? `調薪 ${raisedIn[g.group]} 人` : ''].filter(Boolean);
|
||
return `<div>${esc(g.group)}${tags.map(t => `<span class="sx-tag">${t}</span>`).join('')}</div>
|
||
<div class="sx-bar" aria-hidden="true"><span class="${g.delta < 0 ? 'down' : ''}" style="width:${(Math.abs(g.delta) / max * 100).toFixed(1)}%"></span></div>
|
||
<div class="num ${g.delta > 0 ? 'up' : g.delta < 0 ? 'down' : ''}" style="text-align:right;font-variant-numeric:tabular-nums;">${g.noCoda ? '不算 CODA' : g.delta === 0 ? '不變' : `${g.delta > 0 ? '+' : '−'}${amtv(Math.abs(g.delta))}`}</div>`;
|
||
}).join('')}</div>
|
||
<div class="sx-sub" style="margin-top:4px;">實際 CODA 的變化,變最多的排最上面。</div>`;
|
||
}
|
||
|
||
function resultBlock(d, st) {
|
||
if (!st.result) return '';
|
||
const rows = ROW_ORDER.map(key => st.result.rows.find(r => r.key === key)).filter(Boolean);
|
||
const cards = rows.map(r => changeCard(r, st.result.anchored)).join('');
|
||
const share = rows.find(r => r.key === 'invoiceShare');
|
||
const invoiceNote = !share || share.delta === null || Math.abs(share.delta) < 0.00005 ? ''
|
||
: `發票是全公司一起分的:你部門${share.delta > 0 ? '變多,其他部門會相對變少' : '變少,其他部門會相對變多'}。`;
|
||
return `${st.stale ? '<div class="sx-stale" role="status">內容已改,請重新試算。下面是上一次試算的結果。</div>' : ''}
|
||
<div class="sx-result${st.stale ? ' is-stale' : ''}">
|
||
<div class="sx-step"><h4>① 你這次試算了什麼</h4>${didList(d, st.ran)}</div>
|
||
<div class="sx-step strong"><h4>② 結果:現在 → 試算後</h4><div class="sx-cards">${cards}</div>
|
||
${invoiceNote ? `<div class="sx-sub" style="margin-top:8px;">${invoiceNote}</div>` : ''}</div>
|
||
<div class="sx-step"><h4>③ 影響在哪一組</h4>${whereBlock(d, st)}</div>
|
||
<div class="sx-fine">※ ${DISCLAIMER}</div>
|
||
</div>`;
|
||
}
|
||
|
||
function simSection(d, open) {
|
||
const st = simFor(d.dept);
|
||
const groupOpts = sel => ['<option value="">未分組</option>', ...d.groups.map(g => `<option ${g.group === sel ? 'selected' : ''}>${esc(g.group)}</option>`)].join('');
|
||
const addRows = st.additions.map((a, i) => `<tr class="sx-changed">
|
||
<td><select data-sim="set" data-i="${i}" data-field="kind" aria-label="職能">${KINDS.map(([v, l]) => `<option value="${v}" ${a.kind === v ? 'selected' : ''}>${l}</option>`).join('')}</select></td>
|
||
<td><select data-sim="set" data-i="${i}" data-field="group" aria-label="組">${groupOpts(a.group)}</select></td>
|
||
<td><select data-sim="set" data-i="${i}" data-field="salaryType" aria-label="薪資類型">${[['monthly', '月薪'], ['daily', '日薪'], ['hourly', '時薪']].map(([v, l]) => `<option value="${v}" ${a.salaryType === v ? 'selected' : ''}>${l}</option>`).join('')}</select>
|
||
<input type="number" min="0" value="${a.amount}" data-sim="set" data-i="${i}" data-field="amount" aria-label="金額"></td>
|
||
<td>H1 <input class="m" type="number" min="1" max="6" value="${a.h1Start}" data-sim="set" data-i="${i}" data-field="h1Start" aria-label="H1 起">–<input class="m" type="number" min="1" max="6" value="${a.h1End}" data-sim="set" data-i="${i}" data-field="h1End" aria-label="H1 迄">
|
||
H2 <input class="m" type="number" min="7" max="12" value="${a.h2Start}" data-sim="set" data-i="${i}" data-field="h2Start" aria-label="H2 起">–<input class="m" type="number" min="7" max="12" value="${a.h2End}" data-sim="set" data-i="${i}" data-field="h2End" aria-label="H2 迄"></td>
|
||
<td><button type="button" data-act="remove" data-i="${i}">移除</button></td></tr>`).join('');
|
||
const raisable = (d.people || []).filter(p => p.employeeNumber && !String(p.role).startsWith('O'));
|
||
const raiseRows = raisable.length ? `<details data-key="raise|${esc(d.dept)}" ${isOpen(`raise|${d.dept}`, open) ? 'open' : ''}><summary>模擬調薪(${raisable.length} 人可調)</summary>
|
||
${open ? `<div class="sx-row">${salaryButton('顯示目前薪資', '隱藏目前薪資')}</div>` : ''}
|
||
<div class="sx-scroll"><table><thead><tr><th>姓名</th><th>組</th><th class="num sal">目前</th><th class="num">模擬後</th></tr></thead><tbody>${raisable.map(p => {
|
||
const changed = st.raises[p.employeeNumber] !== undefined;
|
||
return `<tr class="${changed ? 'sx-changed' : ''}"><td>${esc(p.name)}</td><td>${esc(p.group)}</td><td class="num sal">${salaryCell((p.salaryType === 'hourly' ? '時 ' : '') + 'NT$ ' + num(p.salary || 0))}</td>
|
||
<td class="num"><input type="number" min="0" class="${changed ? 'sx-changed' : ''}" value="${st.raises[p.employeeNumber] ?? ''}" placeholder="不調整" data-sim="raise" data-id="${esc(p.employeeNumber)}" aria-label="${esc(p.name)} 模擬薪資"></td></tr>`;
|
||
}).join('')}</tbody></table></div></details>` : '';
|
||
const raiseCount = Object.keys(st.raises).length;
|
||
const counts = [raiseCount ? `已調整 ${raiseCount} 人` : '', st.additions.length ? `加 ${st.additions.length} 人` : ''].filter(Boolean).join('、');
|
||
const dirty = st.result || st.additions.length || raiseCount;
|
||
return `<div class="sx-block b-sim sx-sim" data-dept="${esc(d.dept)}"><div class="sx-bh"><span class="sx-dot"></span>模擬試算(不會存檔)</div>
|
||
<div class="sx-sub">在本部門加人或調薪,看看實際 CODA、平均日 CODA、定錨 CODA、發票、倍率會變多少。工讀算 O:日薪=時薪×8。實習生只進發票、不算 CODA。</div>
|
||
${st.additions.length ? `<div class="sx-scroll"><table><thead><tr><th>職能</th><th>組</th><th>薪資</th><th>在職月份</th><th></th></tr></thead><tbody>${addRows}</tbody></table></div>` : ''}
|
||
<div class="sx-row"><button type="button" data-act="add">+ 加一個人</button><button type="button" class="sx-primary" data-act="run">試算</button>${dirty ? '<button type="button" data-act="reset">清除</button>' : ''}<span class="sx-count" data-count>${counts}</span></div>
|
||
${st.error ? `<div class="sx-warn" role="alert">${esc(st.error)}</div>` : ''}${resultBlock(d, st)}
|
||
${raiseRows}</div>`;
|
||
}
|
||
|
||
function render() {
|
||
const data = state.data;
|
||
if (onMeta) onMeta(data);
|
||
if (mode === 'simulate') {
|
||
const depts = data.depts.filter(d => d.full && data.me.simulate);
|
||
if (!depts.length) { root.innerHTML = '<div class="sx-card">你目前沒有可以模擬的部門。</div>'; return; }
|
||
if (!depts.some(d => d.dept === state.dept)) state.dept = depts[0].dept;
|
||
const pick = `<div class="sx-pick" role="group" aria-label="選擇部門">${depts.map(d => `<button type="button" data-act="dept" data-dept="${esc(d.dept)}" aria-pressed="${d.dept === state.dept}">${esc(d.dept)}</button>`).join('')}</div>`;
|
||
root.innerHTML = pick + deptCard(depts.find(d => d.dept === state.dept), data, true);
|
||
return;
|
||
}
|
||
const parts = [];
|
||
if (data.company) parts.push(`<div class="sx-card"><h2>全公司</h2>${block('inv', '發票', `<div class="sx-kpis"><div class="sx-kpi"><div class="label">年度發票目標</div><div class="value">${money(data.company.invoiceTotal)}</div></div></div><div class="sx-sub">全公司沒有定錨 CODA 合計(調動時原單位不降、新單位增加,加總會重複)。</div>`)}</div>`);
|
||
// 「顯示薪資」放在整頁最上面,部長一進來就找得到(按一下,頁面上所有人的薪資一起顯示)。
|
||
if (data.depts.some(d => d.people)) parts.unshift(`<div class="sx-row" style="margin:0 0 8px;">${salaryButton('顯示薪資', '隱藏薪資')}</div>`);
|
||
for (const d of data.depts) parts.push(deptCard(d, data, false));
|
||
if (!data.depts.length && !data.company) parts.push('<div class="sx-card">目前沒有可以看的部門或組別。</div>');
|
||
root.innerHTML = parts.join('');
|
||
}
|
||
|
||
// 重畫時保留展開狀態(直接畫成展開,不會先收起再打開)與捲動位置,畫面不會跳。
|
||
function scrollers() {
|
||
const list = [];
|
||
for (let el = root.parentElement; el; el = el.parentElement) if (el.scrollHeight > el.clientHeight && /(auto|scroll)/.test(getComputedStyle(el).overflowY)) list.push([el, el.scrollTop]);
|
||
return list;
|
||
}
|
||
function rerender() {
|
||
const saved = scrollers();
|
||
const y = window.scrollY;
|
||
root.style.minHeight = `${root.offsetHeight}px`;
|
||
render();
|
||
root.classList.toggle('show-salary', state.salaryShown);
|
||
saved.forEach(([el, top]) => { el.scrollTop = top; });
|
||
window.scrollTo({ top: y, behavior: 'instant' });
|
||
root.style.minHeight = '';
|
||
}
|
||
root.addEventListener('toggle', event => {
|
||
const key = event.target?.dataset?.key;
|
||
if (key) state.open[key] = event.target.open;
|
||
}, true);
|
||
|
||
const deptOf = el => el.closest('[data-dept]')?.getAttribute('data-dept');
|
||
const markStale = st => { if (st.result) st.stale = true; };
|
||
|
||
root.addEventListener('click', async event => {
|
||
const button = event.target.closest('button[data-act]');
|
||
if (!button || !root.contains(button)) return;
|
||
const act = button.dataset.act;
|
||
if (act === 'salary') {
|
||
state.salaryShown = !state.salaryShown;
|
||
root.classList.toggle('show-salary', state.salaryShown);
|
||
root.querySelectorAll('button[data-act="salary"]').forEach(b => { b.textContent = state.salaryShown ? b.dataset.hide : b.dataset.show; b.setAttribute('aria-pressed', String(state.salaryShown)); });
|
||
return;
|
||
}
|
||
if (act === 'dept') { state.dept = button.dataset.dept; render(); return; }
|
||
const dept = deptOf(button);
|
||
const st = simFor(dept);
|
||
if (act === 'add') { st.additions.push({ kind: 'A', group: '', salaryType: 'monthly', amount: 45000, h1Start: 1, h1End: 6, h2Start: 7, h2End: 12 }); markStale(st); }
|
||
if (act === 'remove') { st.additions.splice(Number(button.dataset.i), 1); markStale(st); }
|
||
if (act === 'reset') state.sim[dept] = emptySim();
|
||
if (act === 'run') {
|
||
button.disabled = true;
|
||
const ran = { additions: st.additions.map(a => ({ ...a })), raises: { ...st.raises } };
|
||
const response = await fetch('/api/simulate' + location.search, { method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ dept, additions: ran.additions, raises: Object.entries(ran.raises).map(([employeeNumber, amount]) => ({ employeeNumber, amount })) }) });
|
||
const body = await response.json().catch(() => ({}));
|
||
st.result = response.ok ? body : null;
|
||
st.ran = response.ok ? ran : null;
|
||
st.stale = false;
|
||
st.error = response.ok ? '' : `試算失敗:${body.error || response.status}(請檢查在職月份與金額)`;
|
||
}
|
||
rerender();
|
||
});
|
||
|
||
root.addEventListener('change', event => {
|
||
const el = event.target.closest('[data-sim]');
|
||
if (!el) return;
|
||
const st = simFor(deptOf(el));
|
||
if (el.dataset.sim === 'raise') {
|
||
if (el.value === '') delete st.raises[el.dataset.id]; else st.raises[el.dataset.id] = Number(el.value);
|
||
el.classList.toggle('sx-changed', el.value !== '');
|
||
el.closest('tr')?.classList.toggle('sx-changed', el.value !== '');
|
||
} else {
|
||
const field = el.dataset.field;
|
||
st.additions[Number(el.dataset.i)][field] = MONTH_FIELDS.includes(field) ? (el.value === '' ? '' : Number(el.value)) : el.value;
|
||
}
|
||
// 只更新提示,不整個重畫(避免打字到一半跳掉)。
|
||
const wasStale = st.stale;
|
||
markStale(st);
|
||
const sim = el.closest('.sx-sim');
|
||
const count = sim?.querySelector('[data-count]');
|
||
const raiseCount = Object.keys(st.raises).length;
|
||
if (count) count.textContent = [raiseCount ? `已調整 ${raiseCount} 人` : '', st.additions.length ? `加 ${st.additions.length} 人` : ''].filter(Boolean).join('、');
|
||
if (st.stale && !wasStale) {
|
||
const result = sim?.querySelector('.sx-result');
|
||
if (result) {
|
||
result.classList.add('is-stale');
|
||
result.insertAdjacentHTML('beforebegin', '<div class="sx-stale" role="status">內容已改,請重新試算。下面是上一次試算的結果。</div>');
|
||
}
|
||
}
|
||
});
|
||
|
||
async function load() {
|
||
if (state.loading) return;
|
||
state.loading = true;
|
||
if (!state.data) root.innerHTML = '<div class="sx-sub">讀取中…</div>';
|
||
try {
|
||
const response = await fetch('/api/scope' + location.search, { cache: 'no-store' });
|
||
if (response.status === 401) { location.href = '/api/auth/login'; return; }
|
||
const data = await response.json().catch(() => ({}));
|
||
if (!response.ok) {
|
||
if (onMeta) onMeta(null, data);
|
||
root.innerHTML = `<div class="sx-card">${data.error === 'no_permission' ? '你目前沒有 LeadBoard 的檢視權限。需要的話請找管理者開通。' : '資料讀取失敗,請稍後重新整理。'}</div>`;
|
||
return;
|
||
}
|
||
if (window.PMI18n) PMI18n.setRate(data.usdRate);
|
||
state.data = data;
|
||
rerender();
|
||
} finally {
|
||
state.loading = false;
|
||
}
|
||
}
|
||
|
||
load();
|
||
return { reload: load };
|
||
}
|
||
|
||
window.PMScope = { mount };
|
||
})();
|