This commit is contained in:
@@ -4,4 +4,5 @@
|
||||
!.env.example
|
||||
node_modules/
|
||||
npm-debug.log*
|
||||
.local-data/
|
||||
|
||||
|
||||
+3
-2
@@ -2,11 +2,12 @@ FROM node:22-alpine
|
||||
|
||||
ENV NODE_ENV=production \
|
||||
HOST=0.0.0.0 \
|
||||
PORT=8080
|
||||
PORT=8080 \
|
||||
COST_MODEL_DATA_DIR=/app/data
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --chown=node:node package.json server.js access.js hr-sync.js hr-org.js index.html hr.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 index.html hr.html 2022_Moonshine_Logo_MS_logo_w_EN.png ./
|
||||
COPY --chown=node:node data ./data
|
||||
|
||||
USER node
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# pm-board
|
||||
|
||||
MoonShine 成本與發票目標預覽站。現階段只使用去識別化的合成資料;正式 HR Sync 串接會在 API 規格與授權確認後加入。
|
||||
MoonShine 成本與發票目標試算站。內部人員以 HR Sync 的在職名冊、組織與目前薪資轉入 2027 試算;常態型外包仍獨立維護。
|
||||
|
||||
## 本機預覽
|
||||
|
||||
@@ -8,9 +8,11 @@ MoonShine 成本與發票目標預覽站。現階段只使用去識別化的合
|
||||
npm start
|
||||
```
|
||||
|
||||
開啟 `http://127.0.0.1:8080`。本機未提供 OIDC 設定時會進入合成資料預覽模式。
|
||||
開啟 `http://127.0.0.1:8080`。本機未提供 OIDC/HR Sync 設定時會進入合成資料預覽模式。
|
||||
|
||||
## 正式環境
|
||||
|
||||
正式環境由 MoonShine 部署平台提供 `OIDC_ISSUER`、`OIDC_CLIENT_ID`、`OIDC_CLIENT_SECRET`。網站要求公司登入,登入時會指定 `prompt=login`,並要求 `employee_number` scope。
|
||||
|
||||
HR Sync 已啟用時,系統會將目前 HR 標記在職的人員建立為 2027 試算名單:H1 預設為 1–6 月,時薪人員預設每週 5 天、每天 8 小時。P/A、管理職與需修正的部門/組別可由試算頁補齊,依工號保存於站台的持久資料目錄;HR 重新同步不會覆蓋這些手動設定。
|
||||
|
||||
|
||||
@@ -9,4 +9,7 @@ services:
|
||||
HOST: 0.0.0.0
|
||||
PORT: 8080
|
||||
DATA_SOURCE: synthetic
|
||||
COST_MODEL_DATA_DIR: /app/data
|
||||
volumes:
|
||||
- ./.local-data:/app/data
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
const HR_SOURCE = 'hr-sync';
|
||||
|
||||
function text(value) {
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
}
|
||||
|
||||
function month(value, minimum, maximum) {
|
||||
const number = Number(value);
|
||||
return Number.isInteger(number) && number >= minimum && number <= maximum ? number : '';
|
||||
}
|
||||
|
||||
export function isCostRole(role) {
|
||||
return typeof role === 'string' && /^(P|A)\s*-/.test(role);
|
||||
}
|
||||
|
||||
export function normalizeOverride(input = {}) {
|
||||
const role = text(input.role);
|
||||
return {
|
||||
role: /^(P|A)\s*-/.test(role) ? role : '',
|
||||
isManager: input.isManager === true,
|
||||
dept: text(input.dept).slice(0, 80),
|
||||
group: text(input.group).slice(0, 80),
|
||||
weeklyWorkDays: Math.min(5, Math.max(1, Number(input.weeklyWorkDays) || 5)),
|
||||
h1Start: month(input.h1Start, 1, 6),
|
||||
h1End: month(input.h1End, 1, 6),
|
||||
h2Start: month(input.h2Start, 7, 12),
|
||||
h2End: month(input.h2End, 7, 12),
|
||||
};
|
||||
}
|
||||
|
||||
export function toCostPerson(person, salary, override = {}) {
|
||||
const saved = normalizeOverride(override);
|
||||
const salaryType = salary?.salaryType === 'hourly' ? 'hourly' : 'monthly';
|
||||
const amount = Number(salary?.amount);
|
||||
const hasSalary = Number.isFinite(amount) && amount >= 0;
|
||||
const hasRole = isCostRole(saved.role);
|
||||
|
||||
return {
|
||||
row: String(person.employeeNumber),
|
||||
employeeNumber: String(person.employeeNumber),
|
||||
source: HR_SOURCE,
|
||||
name: text(person.name),
|
||||
title: text(person.positionName),
|
||||
dept: saved.dept || text(person.departmentName),
|
||||
group: saved.group || text(person.groupName),
|
||||
role: saved.role || '待分類',
|
||||
isManager: saved.isManager,
|
||||
salary: salaryType === 'monthly' && hasSalary ? amount : 0,
|
||||
hourlyRate: salaryType === 'hourly' && hasSalary ? amount : 0,
|
||||
salaryType: hasSalary ? salaryType : 'unknown',
|
||||
weeklyWorkDays: saved.weeklyWorkDays,
|
||||
h1Start: saved.h1Start || 1,
|
||||
h1End: saved.h1End || 6,
|
||||
h2Start: saved.h2Start,
|
||||
h2End: saved.h2End,
|
||||
workRateUsed: 1,
|
||||
hrStatus: person.status,
|
||||
salaryEffectiveDate: salary?.effectiveDate || null,
|
||||
calculationReady: hasSalary && hasRole,
|
||||
calculationIssue: !hasSalary ? 'HR 尚未提供可用薪資' : !hasRole ? '待設定 P/A 職能' : '',
|
||||
};
|
||||
}
|
||||
|
||||
export function weekdaysInMonth(year, month) {
|
||||
let count = 0;
|
||||
const date = new Date(Date.UTC(year, month - 1, 1));
|
||||
while (date.getUTCMonth() === month - 1) {
|
||||
const day = date.getUTCDay();
|
||||
if (day >= 1 && day <= 5) count += 1;
|
||||
date.setUTCDate(date.getUTCDate() + 1);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
export function hourlyMonthlyAmount(person, year, month) {
|
||||
return weekdaysInMonth(year, month) * 8 * (Number(person.hourlyRate) || 0) * ((Number(person.weeklyWorkDays) || 5) / 5);
|
||||
}
|
||||
+108
-26
@@ -1461,7 +1461,7 @@
|
||||
<div class="nav-item" id="nav-invoice" onclick="showView('invoice')">🧾 年度發票額</div>
|
||||
<div class="nav-item" id="nav-personnel" onclick="showHrPersonnelView()">👥 內部人員</div>
|
||||
<div class="nav-item" id="nav-contractors" onclick="showPersonnelView('all', 'contractors')">🤝 常態型外包</div>
|
||||
<div class="nav-item" id="nav-preview-personnel" onclick="showPersonnelView('all', 'internal', true)">🧪 試算人員(合成)</div>
|
||||
<div class="nav-item" id="nav-preview-personnel" onclick="showPersonnelView('all', 'internal', true)">🧮 試算人員(2027)</div>
|
||||
<div class="nav-item" id="nav-versions" onclick="showView('versions')">📈 薪資版本與調薪</div>
|
||||
|
||||
<div class="nav-item" id="nav-org" onclick="showView('org-structure')">🏢 組織架構</div>
|
||||
@@ -1685,8 +1685,9 @@
|
||||
class="sort-icon"></span></th>
|
||||
<th class="sortable" onclick="toggleSort('isManager')">管理職 <span id="sort-isManager"
|
||||
class="sort-icon"></span></th>
|
||||
<th class="sortable num" onclick="toggleSort('salary')">月/日薪 <span id="sort-salary"
|
||||
<th class="sortable num" onclick="toggleSort('salary')">月/時薪 <span id="sort-salary"
|
||||
class="sort-icon"></span></th>
|
||||
<th class="num">每週天數</th>
|
||||
<th class="num">H1 起</th>
|
||||
<th class="num">H1 迄</th>
|
||||
<th class="num">H2 起</th>
|
||||
@@ -2262,6 +2263,27 @@
|
||||
let sortConfig = { field: 'dept', direction: 'asc' };
|
||||
|
||||
// --- CALCULATION ENGINE ---
|
||||
function isCalculationRole(role) {
|
||||
return /^(P|A|O)\s*-/.test(String(role || ''));
|
||||
}
|
||||
|
||||
function weekdaysInMonth(year, month) {
|
||||
let count = 0;
|
||||
const date = new Date(Date.UTC(year, month - 1, 1));
|
||||
while (date.getUTCMonth() === month - 1) {
|
||||
const weekday = date.getUTCDay();
|
||||
if (weekday >= 1 && weekday <= 5) count++;
|
||||
date.setUTCDate(date.getUTCDate() + 1);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
function hourlyMonthlyAmount(person, month, hourlyRate) {
|
||||
const year = Number(globalParams.reportYear || 2027);
|
||||
const weeklyDays = Math.min(5, Math.max(1, Number(person.weeklyWorkDays) || 5));
|
||||
return weekdaysInMonth(year, month) * 8 * (Number(hourlyRate) || 0) * (weeklyDays / 5);
|
||||
}
|
||||
|
||||
function calculateAll(data) {
|
||||
// 1. Data Migration & Cost Reset
|
||||
data.forEach((p, idx) => {
|
||||
@@ -2284,6 +2306,15 @@
|
||||
|
||||
const isOutsource = p.role && p.role.startsWith('O');
|
||||
|
||||
// HR people remain visible while their P/A classification is waiting for manual review.
|
||||
// They must not silently alter CODA or company totals before that review is complete.
|
||||
if (p.source === 'hr-sync' && !p.calculationReady) {
|
||||
p.realSalaryTotal = 0;
|
||||
p.totalCost = 0;
|
||||
if (p.row === undefined) p.row = idx;
|
||||
return;
|
||||
}
|
||||
|
||||
// NEW: If we are in PUBLIC VERSION and totalCost is already baked, skip expensive calculation
|
||||
if (window.IS_PUBLIC_VERSION && p.totalCost !== undefined) {
|
||||
p.workRateUsed = p.workRateUsed !== undefined ? p.workRateUsed : (isOutsource ? 1.5 : 1.0);
|
||||
@@ -2309,6 +2340,7 @@
|
||||
const workRate = parseFloat(p.workRateUsed) || (isOutsource ? 1.5 : 1.0);
|
||||
const opMult = isOutsource ? 1.0 : globalParams.opMultiplier;
|
||||
const baseSalary = isOutsource ? (parseFloat(p.dayrate) || 0) * globalParams.workingDays : (parseFloat(p.salary) || 0);
|
||||
const baseHourlyRate = parseFloat(p.hourlyRate) || 0;
|
||||
|
||||
for (let m = 1; m <= 12; m++) {
|
||||
// Check if person is active in this month
|
||||
@@ -2317,7 +2349,9 @@
|
||||
|
||||
if (inH1 || inH2) {
|
||||
// Determine applicable monthly salary. Start with base.
|
||||
let currentMonthSalary = baseSalary;
|
||||
let currentMonthSalary = p.salaryType === 'hourly'
|
||||
? hourlyMonthlyAmount(p, m, baseHourlyRate)
|
||||
: baseSalary;
|
||||
|
||||
// Apply overrides from raise events
|
||||
raises.forEach(evt => {
|
||||
@@ -2326,7 +2360,10 @@
|
||||
const reportYear = Number(globalParams.reportYear || new Date().getFullYear());
|
||||
const effectiveYear = Number(adj?.startYear || reportYear);
|
||||
if (adj && (effectiveYear < reportYear || (effectiveYear === reportYear && m >= adj.startMonth))) {
|
||||
currentMonthSalary = isOutsource ? (parseFloat(adj.newSalary) || 0) * globalParams.workingDays : (parseFloat(adj.newSalary) || 0);
|
||||
const changedRate = parseFloat(adj.newSalary) || 0;
|
||||
currentMonthSalary = isOutsource ? changedRate * globalParams.workingDays
|
||||
: p.salaryType === 'hourly' ? hourlyMonthlyAmount(p, m, changedRate)
|
||||
: changedRate;
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -2357,7 +2394,7 @@
|
||||
const cleanD = (d || '').trim();
|
||||
const pInDept = data.filter(p => (p.dept || '').trim() === cleanD);
|
||||
// PARADIGM SHIFT: Exclude 'O - 外包' completely from rawDt and dt calculation for CODA purposes
|
||||
const rawDt = pInDept.filter(p => p.role && !p.role.startsWith('O')).reduce((acc, p) => acc + (p.totalCost || 0), 0);
|
||||
const rawDt = pInDept.filter(p => isCalculationRole(p.role) && !p.role.startsWith('O')).reduce((acc, p) => acc + (p.totalCost || 0), 0);
|
||||
const rawArtistCost = pInDept.filter(p => p.role && p.role.startsWith('A')).reduce((acc, p) => acc + (p.totalCost || 0), 0);
|
||||
|
||||
// Keep a separate count for raw tracking that includes everything
|
||||
@@ -4170,7 +4207,7 @@
|
||||
});
|
||||
|
||||
tbody.innerHTML = '';
|
||||
if (!filtered.length) tbody.innerHTML = '<tr><td colspan="14" style="text-align:center; padding:2rem;">沒有符合條件的人員,可調整篩選或新增。</td></tr>';
|
||||
if (!filtered.length) tbody.innerHTML = '<tr><td colspan="15" style="text-align:center; padding:2rem;">沒有符合條件的人員,可調整篩選或新增。</td></tr>';
|
||||
|
||||
let totalCosts = { pa: 0, o: 0, all: 0 };
|
||||
|
||||
@@ -4186,31 +4223,46 @@
|
||||
if (isOutsource) totalCosts.o += pCost;
|
||||
else totalCosts.pa += pCost;
|
||||
|
||||
const isHourly = p.salaryType === 'hourly';
|
||||
const salaryField = isOutsource ? 'dayrate' : 'salary';
|
||||
const salaryPrefix = isOutsource ? '日 $' : '$';
|
||||
const salaryVal = isOutsource ? p.dayrate : p.salary;
|
||||
const salaryPrefix = isOutsource ? '日 $' : isHourly ? '時 $' : '$';
|
||||
const salaryVal = isOutsource ? p.dayrate : isHourly ? p.hourlyRate : p.salary;
|
||||
const isHrPerson = p.source === 'hr-sync';
|
||||
const safeName = escapeHtml(p.name);
|
||||
const safeTitle = escapeHtml(p.title || '');
|
||||
const safeDept = escapeHtml(p.dept || '');
|
||||
const safeGroup = escapeHtml(p.group || '');
|
||||
const classification = isHrPerson && !p.calculationReady
|
||||
? `<div style="font-size:.72rem;color:var(--accent-warning);margin-top:.35rem;white-space:nowrap;">${escapeHtml(p.calculationIssue || '待確認')}</div>` : '';
|
||||
const roleInput = isHrPerson ? `<select onchange="updatePerson(${origIdx}, 'role', this.value)" style="width:90px;">
|
||||
<option value="" ${!isCalculationRole(p.role) ? 'selected' : ''}>待分類</option>
|
||||
<option value="P - 製作" ${p.role === 'P - 製作' ? 'selected' : ''}>P</option>
|
||||
<option value="A - 藝術家" ${p.role === 'A - 藝術家' ? 'selected' : ''}>A</option>
|
||||
</select>` : `<span class="role-pill ${roleClass}">${escapeHtml((p.role || '').split(' - ')[0])}</span>`;
|
||||
const salaryControl = isHrPerson
|
||||
? `<span title="由 HR Sync 提供,目前不可在試算頁覆寫">${salaryPrefix}${(parseFloat(salaryVal) || 0).toLocaleString()}</span>`
|
||||
: `<div style="display:flex; align-items:center; justify-content: flex-end;"><span style="font-size:0.75rem; color:var(--text-dim); margin-right:2px;">${salaryPrefix}</span><input type="number" style="text-align:right; width: 85px;" value="${salaryVal}" onchange="updatePerson(${origIdx}, '${salaryField}', this.value)"></div>`;
|
||||
const weeklyDays = isHrPerson && isHourly
|
||||
? `<input type="number" min="1" max="5" value="${Math.min(5, Math.max(1, Number(p.weeklyWorkDays) || 5))}" onchange="updatePerson(${origIdx}, 'weeklyWorkDays', this.value)" class="input-mini" style="width:38px;">`
|
||||
: '—';
|
||||
|
||||
const statusHtml = getStatusBadge(p);
|
||||
|
||||
tbody.innerHTML += `
|
||||
<tr>
|
||||
<td><input value="${p.name}" onchange="updatePerson(${origIdx}, 'name', this.value)" style="width: 75px;"></td>
|
||||
<td><input value="${p.title || ''}" onchange="updatePerson(${origIdx}, 'title', this.value)" style="width: 85px;"></td>
|
||||
<td><input value="${p.dept}" onchange="updatePerson(${origIdx}, 'dept', this.value)" style="width: 65px;"></td>
|
||||
<td><input value="${p.group || ''}" onchange="updatePerson(${origIdx}, 'group', this.value)" style="width: 135px;" title="${p.group || ''}"></td>
|
||||
<td><span class="role-pill ${roleClass}">${p.role.split(' - ')[0]}</span></td>
|
||||
<td>${isHrPerson ? safeName : `<input value="${safeName}" onchange="updatePerson(${origIdx}, 'name', this.value)" style="width: 75px;">`}</td>
|
||||
<td>${isHrPerson ? safeTitle : `<input value="${safeTitle}" onchange="updatePerson(${origIdx}, 'title', this.value)" style="width: 85px;">`}</td>
|
||||
<td><input value="${safeDept}" onchange="updatePerson(${origIdx}, 'dept', this.value)" style="width: 65px;"></td>
|
||||
<td><input value="${safeGroup}" onchange="updatePerson(${origIdx}, 'group', this.value)" style="width: 135px;" title="${safeGroup}"></td>
|
||||
<td>${roleInput}${classification}</td>
|
||||
<td style="text-align:center;"><input type="checkbox" ${p.isManager ? 'checked' : ''} onchange="updatePerson(${origIdx}, 'isManager', this.checked)" style="cursor: pointer; width: 14px; height: 14px; margin: 0; background: transparent;"></td>
|
||||
<td class="num">
|
||||
<div style="display:flex; align-items:center; justify-content: flex-end;">
|
||||
<span style="font-size:0.75rem; color:var(--text-dim); margin-right:2px;">${salaryPrefix}</span>
|
||||
<input type="number" style="text-align:right; width: 85px;" value="${salaryVal}" onchange="updatePerson(${origIdx}, '${salaryField}', this.value)">
|
||||
</div>
|
||||
</td>
|
||||
<td class="num">${salaryControl}</td>
|
||||
<td class="num">${weeklyDays}</td>
|
||||
<td class="num"><input type="number" min="1" max="6" value="${p.h1Start || ''}" placeholder="-" onchange="updatePerson(${origIdx}, 'h1Start', this.value)" class="input-mini" style="width: 38px;"></td>
|
||||
<td class="num"><input type="number" min="1" max="6" value="${p.h1End || ''}" placeholder="-" onchange="updatePerson(${origIdx}, 'h1End', this.value)" class="input-mini" style="width: 38px;"></td>
|
||||
<td class="num"><input type="number" min="7" max="12" value="${p.h2Start || ''}" placeholder="-" onchange="updatePerson(${origIdx}, 'h2Start', this.value)" class="input-mini" style="width: 38px;"></td>
|
||||
<td class="num"><input type="number" min="7" max="12" value="${p.h2End || ''}" placeholder="-" onchange="updatePerson(${origIdx}, 'h2End', this.value)" class="input-mini" style="width: 38px;"></td>
|
||||
<td class="num" style="text-align:center;">${statusHtml}</td>
|
||||
<td class="num" style="text-align:center;">${isHrPerson && !p.calculationReady ? '<span class="status-pill status-temp">待確認</span>' : statusHtml}</td>
|
||||
<td class="num" style="color: var(--accent-success); font-weight:700;">$${(p.totalCost || 0).toLocaleString()}</td>
|
||||
<td><button onclick="removePerson(${origIdx})" style="background:none; border:none; color:var(--accent-danger); cursor:pointer;">刪除</button></td>
|
||||
</tr>
|
||||
@@ -4247,9 +4299,34 @@
|
||||
function updatePerson(idx, field, val) {
|
||||
const target = isSimMode ? simData : baseData;
|
||||
target[idx][field] = val;
|
||||
if (target[idx].source === 'hr-sync') {
|
||||
const person = target[idx];
|
||||
person.calculationReady = Boolean((parseFloat(person.salary) || parseFloat(person.hourlyRate)) && isCalculationRole(person.role));
|
||||
person.calculationIssue = person.calculationReady ? '' : (!isCalculationRole(person.role) ? '待設定 P/A 職能' : 'HR 尚未提供可用薪資');
|
||||
saveHrCostOverride(person);
|
||||
}
|
||||
saveAndRefresh();
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value == null ? '' : value).replace(/[&<>\"']/g, char => ({ '&': '&', '<': '<', '>': '>', '\"': '"', "'": ''' })[char]);
|
||||
}
|
||||
|
||||
async function saveHrCostOverride(person) {
|
||||
try {
|
||||
const response = await fetch(`/api/hr/cost-model/employees/${encodeURIComponent(person.employeeNumber)}`, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ role: person.role, isManager: person.isManager, dept: person.dept, group: person.group,
|
||||
weeklyWorkDays: person.weeklyWorkDays, h1Start: person.h1Start, h1End: person.h1End, h2Start: person.h2Start, h2End: person.h2End }),
|
||||
});
|
||||
if (!response.ok) throw new Error('儲存失敗');
|
||||
} catch (error) {
|
||||
console.error('Unable to save HR cost override', error);
|
||||
document.getElementById('data-source-banner').textContent = 'HR 試算資料更新失敗,請重新整理後再試。';
|
||||
document.getElementById('data-source-banner').style.color = 'var(--accent-danger)';
|
||||
}
|
||||
}
|
||||
|
||||
// --- ADD PERSON MODAL FUNCTIONS ---
|
||||
function addPerson() { openAddPersonModal(); } // keep backward compat with existing button
|
||||
|
||||
@@ -4621,11 +4698,11 @@
|
||||
deptFilterEl.innerHTML = deptOptionsHtml;
|
||||
|
||||
deptFilterEl.value = dept;
|
||||
const label = category === 'contractors' ? '常態型外包' : '內部人員';
|
||||
const label = category === 'contractors' ? '常態型外包' : '試算人員';
|
||||
document.getElementById('personnel-view-title').innerText = `${label}(${dept === 'all' ? '全部門' : dept})`;
|
||||
document.getElementById('personnel-source-note').textContent = category === 'contractors'
|
||||
? '獨立維護日薪、合約月份與部門/組別;成本仍納入整體報表。目前為合成預覽,修改僅保留於本次頁面。'
|
||||
: '合成試算名單;正式在職人員請看「內部人員」。修改僅保留於本次頁面。';
|
||||
: '2027 HR 試算名單。姓名、職稱、部門/組別與薪資來自 HR;P/A、管理職及未辨識部/組可在此補齊。未完成 P/A 的人會列出,但不納入正式總額。';
|
||||
document.getElementById('personnel-add-button').textContent = `+ 新增${label}`;
|
||||
document.getElementById('personnel-search').value = '';
|
||||
|
||||
@@ -5667,13 +5744,18 @@
|
||||
}
|
||||
if (!response.ok) throw new Error(`預覽資料載入失敗(HTTP ${response.status})`);
|
||||
const payload = await response.json();
|
||||
if (payload.source !== 'synthetic-demo' || !Array.isArray(payload.baseData) || !payload.globalParams) {
|
||||
throw new Error('伺服器回傳格式不符,或資料來源不是合成預覽。');
|
||||
if (!['synthetic-demo', 'hr-sync-2027-planning'].includes(payload.source) || !Array.isArray(payload.baseData) || !payload.globalParams) {
|
||||
throw new Error('伺服器回傳格式不符。');
|
||||
}
|
||||
baseData = payload.baseData;
|
||||
globalParams = payload.globalParams;
|
||||
document.getElementById('data-source-banner').textContent =
|
||||
'合成資料預覽|姓名、薪資與參數皆為虛構資料;修改只保留在目前頁面工作階段。';
|
||||
const banner = document.getElementById('data-source-banner');
|
||||
if (payload.source === 'hr-sync-2027-planning') {
|
||||
const summary = payload.summary || {};
|
||||
banner.textContent = `2027 HR 試算|已轉入 ${summary.activeEmployees || 0} 位 HR 在職人員;${summary.needsReview || 0} 位待確認 P/A 或薪資,暫不納入正式總額。時薪人員先按每週 5 天、每天 8 小時計算;H1 預設為 1–6 月。`;
|
||||
} else {
|
||||
banner.textContent = '合成資料預覽|姓名、薪資與參數皆為虛構資料;修改只保留在目前頁面工作階段。';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
import { createHash, createPublicKey, randomBytes, verify } from 'node:crypto';
|
||||
import { createServer } from 'node:http';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
||||
import { extname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { canAccess } from './access.js';
|
||||
import { HrError, hrConfig, hrFetch } from './hr-sync.js';
|
||||
import { splitOrganization } from './hr-org.js';
|
||||
import { normalizeOverride, toCostPerson } from './cost-model.js';
|
||||
|
||||
const root = fileURLToPath(new URL('.', import.meta.url));
|
||||
const port = Number(process.env.PORT || 8080);
|
||||
const host = process.env.HOST || (process.env.NODE_ENV === 'production' ? '0.0.0.0' : '127.0.0.1');
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
const demoPath = resolve(root, 'data/demo.json');
|
||||
const costModelDataDir = process.env.COST_MODEL_DATA_DIR;
|
||||
const costOverridesPath = costModelDataDir ? resolve(costModelDataDir, 'cost-overrides.json') : null;
|
||||
const oidc = {
|
||||
issuer: process.env.OIDC_ISSUER?.replace(/\/+$/, ''),
|
||||
clientId: process.env.OIDC_CLIENT_ID,
|
||||
@@ -23,6 +26,8 @@ const pendingLogins = new Map();
|
||||
const sessions = new Map();
|
||||
let discoveryCache;
|
||||
let jwksCache;
|
||||
let persistedOverrides;
|
||||
let overrideWrite = Promise.resolve();
|
||||
|
||||
const allowedStaticFiles = new Map([
|
||||
['/2022_Moonshine_Logo_MS_logo_w_EN.png', ['2022_Moonshine_Logo_MS_logo_w_EN.png', 'image/png']],
|
||||
@@ -228,6 +233,89 @@ async function getOrganizations(session) {
|
||||
return records;
|
||||
}
|
||||
|
||||
async function mapWithConcurrency(items, limit, task) {
|
||||
const results = new Array(items.length);
|
||||
let next = 0;
|
||||
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
|
||||
while (next < items.length) {
|
||||
const index = next++;
|
||||
results[index] = await task(items[index]);
|
||||
}
|
||||
}));
|
||||
return results;
|
||||
}
|
||||
|
||||
async function getCostOverrides() {
|
||||
if (persistedOverrides) return persistedOverrides;
|
||||
persistedOverrides = new Map();
|
||||
if (!costOverridesPath) return persistedOverrides;
|
||||
try {
|
||||
const raw = JSON.parse(await readFile(costOverridesPath, 'utf8'));
|
||||
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
||||
for (const [employeeNumber, override] of Object.entries(raw)) {
|
||||
if (/^[a-zA-Z0-9_-]{1,40}$/.test(employeeNumber)) persistedOverrides.set(employeeNumber, normalizeOverride(override));
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (error?.code !== 'ENOENT') throw error;
|
||||
}
|
||||
return persistedOverrides;
|
||||
}
|
||||
|
||||
async function saveCostOverrides() {
|
||||
if (!costOverridesPath || !persistedOverrides) return;
|
||||
const serialized = Object.fromEntries(persistedOverrides);
|
||||
await mkdir(costModelDataDir, { recursive: true });
|
||||
const temporaryPath = `${costOverridesPath}.${process.pid}.tmp`;
|
||||
await writeFile(temporaryPath, JSON.stringify(serialized, null, 2), { mode: 0o600 });
|
||||
await rename(temporaryPath, costOverridesPath);
|
||||
}
|
||||
|
||||
async function getCostModel(session) {
|
||||
if (session.costModelCache?.expiresAt > Date.now()) return session.costModelCache.payload;
|
||||
const [records, organizations, demo] = await Promise.all([
|
||||
getRoster(session), getOrganizations(session), readFile(demoPath, 'utf8').then(JSON.parse),
|
||||
]);
|
||||
const salaryResults = await mapWithConcurrency(records, 6, async (person) => {
|
||||
try {
|
||||
return await hrFetch(session, 'hr:salary:read', `/employees/${encodeURIComponent(person.employeeNumber)}/salary`, hr, oidc, await getDiscovery());
|
||||
} catch (error) {
|
||||
if (error instanceof HrError && ['hr_not_found', 'hr_endpoint_forbidden', 'hr_exchange_denied'].includes(error.code)) return null;
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
const overrides = await getCostOverrides();
|
||||
const people = records.map((person, index) => toCostPerson({
|
||||
...person,
|
||||
...splitOrganization(person, organizations),
|
||||
}, salaryResults[index], overrides.get(person.employeeNumber)));
|
||||
const contractors = demo.baseData.filter(person => String(person.role || '').startsWith('O'));
|
||||
const payload = {
|
||||
source: 'hr-sync-2027-planning',
|
||||
reportYear: 2027,
|
||||
generatedAt: new Date().toISOString(),
|
||||
baseData: [...people, ...contractors],
|
||||
globalParams: { ...demo.globalParams, reportYear: 2027, orgStructure: null },
|
||||
summary: {
|
||||
activeEmployees: people.length,
|
||||
readyForCalculation: people.filter(person => person.calculationReady).length,
|
||||
needsReview: people.filter(person => !person.calculationReady).length,
|
||||
hourlyEmployees: people.filter(person => person.salaryType === 'hourly').length,
|
||||
},
|
||||
};
|
||||
session.costModelCache = { payload, expiresAt: Date.now() + 60_000 };
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function readJson(request) {
|
||||
let raw = '';
|
||||
for await (const chunk of request) {
|
||||
raw += chunk;
|
||||
if (raw.length > 20_000) throw new HrError('invalid_request', 400);
|
||||
}
|
||||
try { return JSON.parse(raw || '{}'); } catch { throw new HrError('invalid_request', 400); }
|
||||
}
|
||||
|
||||
const server = createServer(async (request, response) => {
|
||||
const url = new URL(request.url || '/', `http://${request.headers.host || 'localhost'}`);
|
||||
|
||||
@@ -335,14 +423,34 @@ const server = createServer(async (request, response) => {
|
||||
} });
|
||||
}
|
||||
|
||||
if (request.method === 'GET' && url.pathname === '/api/hr/cost-model') {
|
||||
const session = requireAuth(request, response, true);
|
||||
if (!session) return;
|
||||
if (!canAccess(session.claims)) return sendJson(response, 403, { error: 'access_denied' });
|
||||
return sendJson(response, 200, await getCostModel(session));
|
||||
}
|
||||
|
||||
if (request.method === 'POST' && /^\/api\/hr\/cost-model\/employees\/[^/]+$/.test(url.pathname)) {
|
||||
const session = requireAuth(request, response, true);
|
||||
if (!session) return;
|
||||
if (!canAccess(session.claims)) return sendJson(response, 403, { error: 'access_denied' });
|
||||
const employeeNumber = url.pathname.split('/')[5];
|
||||
if (!/^[a-zA-Z0-9_-]{1,40}$/.test(employeeNumber)) return sendJson(response, 400, { error: 'invalid_employee_number' });
|
||||
const roster = await getRoster(session);
|
||||
if (!roster.some(person => person.employeeNumber === employeeNumber)) return sendJson(response, 404, { error: 'employee_not_found' });
|
||||
const body = await readJson(request);
|
||||
const overrides = await getCostOverrides();
|
||||
overrides.set(employeeNumber, normalizeOverride(body));
|
||||
overrideWrite = overrideWrite.then(saveCostOverrides);
|
||||
await overrideWrite;
|
||||
session.costModelCache = null;
|
||||
return sendJson(response, 200, { ok: true });
|
||||
}
|
||||
|
||||
if (request.method === 'GET' && url.pathname === '/api/bootstrap') {
|
||||
if (!requireAuth(request, response, true)) return;
|
||||
if ((process.env.DATA_SOURCE || 'synthetic') !== 'synthetic') {
|
||||
return sendJson(response, 503, {
|
||||
error: 'The HR data provider is not configured. Synthetic preview is the only enabled source.',
|
||||
source: 'unavailable',
|
||||
});
|
||||
}
|
||||
const session = getSession(request);
|
||||
if (hr && session && canAccess(session.claims)) return sendJson(response, 200, await getCostModel(session));
|
||||
const demo = JSON.parse(await readFile(demoPath, 'utf8'));
|
||||
return sendJson(response, 200, demo);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { hourlyMonthlyAmount, toCostPerson, weekdaysInMonth } from '../cost-model.js';
|
||||
|
||||
test('HR people become 2027 H1 planning records without inventing a P/A role', () => {
|
||||
const person = toCostPerson({
|
||||
employeeNumber: '20170101', name: '許宏玉', positionName: 'Admin Assistant',
|
||||
departmentName: null, groupName: '行政管理組', status: 'ACTIVE',
|
||||
}, { amount: 250, salaryType: 'hourly', effectiveDate: '2026-10-20' });
|
||||
|
||||
assert.equal(person.row, '20170101');
|
||||
assert.equal(person.salaryType, 'hourly');
|
||||
assert.equal(person.hourlyRate, 250);
|
||||
assert.equal(person.weeklyWorkDays, 5);
|
||||
assert.equal(person.h1Start, 1);
|
||||
assert.equal(person.h1End, 6);
|
||||
assert.equal(person.h2Start, '');
|
||||
assert.equal(person.calculationReady, false);
|
||||
assert.equal(person.calculationIssue, '待設定 P/A 職能');
|
||||
});
|
||||
|
||||
test('manual HR classification becomes calculation-ready while preserving HR salary type', () => {
|
||||
const person = toCostPerson({ employeeNumber: '20260702', name: '曾得維', positionName: 'Engineer', status: 'ACTIVE' },
|
||||
{ amount: 200, salaryType: 'hourly' }, { role: 'A - 藝術家', weeklyWorkDays: 3, h1Start: 1, h1End: 6 });
|
||||
assert.equal(person.role, 'A - 藝術家');
|
||||
assert.equal(person.weeklyWorkDays, 3);
|
||||
assert.equal(person.calculationReady, true);
|
||||
assert.equal(person.salaryType, 'hourly');
|
||||
});
|
||||
|
||||
test('hourly planning uses weekdays, eight hours, and the selected weekly-days ratio', () => {
|
||||
assert.equal(weekdaysInMonth(2027, 2), 20);
|
||||
assert.equal(hourlyMonthlyAmount({ hourlyRate: 200, weeklyWorkDays: 5 }, 2027, 2), 32000);
|
||||
assert.equal(hourlyMonthlyAmount({ hourlyRate: 200, weeklyWorkDays: 3 }, 2027, 2), 19200);
|
||||
});
|
||||
+26
-1
@@ -3,6 +3,9 @@ import { spawn } from 'node:child_process';
|
||||
import test from 'node:test';
|
||||
import { createServer } from 'node:http';
|
||||
import { generateKeyPairSync, sign } from 'node:crypto';
|
||||
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const node = process.execPath;
|
||||
|
||||
@@ -71,6 +74,8 @@ test('configured production redirects pages and protects APIs', async (t) => {
|
||||
});
|
||||
|
||||
test('a signed-in session is revoked by logout and cannot be replayed', async (t) => {
|
||||
const dataDir = await mkdtemp(join(tmpdir(), 'pm-board-cost-model-'));
|
||||
t.after(() => rm(dataDir, { recursive: true, force: true }));
|
||||
const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
|
||||
const key = { ...publicKey.export({ format: 'jwk' }), kid: 'test-key' };
|
||||
let nonce;
|
||||
@@ -121,6 +126,7 @@ test('a signed-in session is revoked by logout and cannot be replayed', async (t
|
||||
const base = 'http://127.0.0.1:18085';
|
||||
const child = start({ PORT: '18085', HOST: '127.0.0.1', NODE_ENV: 'production',
|
||||
OIDC_ISSUER: issuer, OIDC_CLIENT_ID: 'test-client', OIDC_CLIENT_SECRET: 'test-secret',
|
||||
COST_MODEL_DATA_DIR: dataDir,
|
||||
RESOURCE_SERVERS: JSON.stringify({ 'hr-sync': { audience: 'hr-sync-api', base_url: issuer,
|
||||
required_scopes: ['hr-sync-api', 'employee_number'], scopes: ['hr:read', 'hr:salary:read'] } }) });
|
||||
t.after(() => child.kill());
|
||||
@@ -140,7 +146,26 @@ test('a signed-in session is revoked by logout and cannot be replayed', async (t
|
||||
const appHtml = await app.text();
|
||||
assert.match(appHtml, /id="nav-personnel" onclick="showHrPersonnelView\(\)"/);
|
||||
assert.match(appHtml, /id="hr-personnel" class="view"/);
|
||||
assert.equal((await fetch(`${base}/api/bootstrap`, { headers: { cookie } })).status, 200);
|
||||
const bootstrap = await fetch(`${base}/api/bootstrap`, { headers: { cookie } });
|
||||
assert.equal(bootstrap.status, 200);
|
||||
const model = await bootstrap.json();
|
||||
assert.equal(model.source, 'hr-sync-2027-planning');
|
||||
assert.equal(model.globalParams.reportYear, 2027);
|
||||
const planningPerson = model.baseData.find(person => person.employeeNumber === '20150906');
|
||||
assert.equal(planningPerson.h1Start, 1);
|
||||
assert.equal(planningPerson.h1End, 6);
|
||||
assert.equal(planningPerson.calculationReady, false);
|
||||
const override = await fetch(`${base}/api/hr/cost-model/employees/20150906`, {
|
||||
method: 'POST', headers: { cookie, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ role: 'A - 藝術家', weeklyWorkDays: 3, h1Start: 1, h1End: 6 }),
|
||||
});
|
||||
assert.equal(override.status, 200);
|
||||
const savedOverrides = JSON.parse(await readFile(join(dataDir, 'cost-overrides.json'), 'utf8'));
|
||||
assert.equal(savedOverrides['20150906'].role, 'A - 藝術家');
|
||||
const updatedModel = await fetch(`${base}/api/hr/cost-model`, { headers: { cookie } });
|
||||
const updatedPerson = (await updatedModel.json()).baseData.find(person => person.employeeNumber === '20150906');
|
||||
assert.equal(updatedPerson.role, 'A - 藝術家');
|
||||
assert.equal(updatedPerson.calculationReady, true);
|
||||
const roster = await fetch(`${base}/api/hr/employees`, { headers: { cookie } });
|
||||
assert.equal(roster.status, 200);
|
||||
const people = (await roster.json()).employees;
|
||||
|
||||
Reference in New Issue
Block a user