Files
leadboard/simulate.js
2026-11-04 12:56:18 +00:00

107 lines
6.4 KiB
JavaScript

// 部長模擬試算:在自己部門加人(O/P/A/實習/工讀)或幫現有的人調薪,伺服器算出
// 實際 CODA、平均日 CODA、定錨 CODA、發票各會變多少。不存檔、不影響正式數字。
import { PART_TIME_HOURS_PER_DAY } from './cost-model.js';
import { multiplierFor } from './scope-view.js';
export const SIM_KINDS = Object.freeze(['P', 'A', 'O', 'intern', 'parttime']);
const MAX_ADDITIONS = 30;
const MAX_RAISES = 100;
const text = (value, max = 80) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
const money = (value) => {
const number = Number(value);
if (!Number.isFinite(number) || number < 0 || number > 10_000_000) throw new RangeError('amount out of range');
return number;
};
const month = (value, min, max) => {
if (value === '' || value === null || value === undefined) return '';
const number = Number(value);
if (!Number.isInteger(number) || number < min || number > max) throw new RangeError('month out of range');
return number;
};
// 把一筆「新增的人」轉成計算核心看得懂的資料。
export function simulatedPerson(input, { dept, company }, index) {
const kind = text(input.kind, 10);
if (!SIM_KINDS.includes(kind)) throw new RangeError('unknown kind');
const salaryType = text(input.salaryType, 10);
const amount = money(input.amount);
const months = {
h1Start: month(input.h1Start, 1, 6), h1End: month(input.h1End, 1, 6),
h2Start: month(input.h2Start, 7, 12), h2End: month(input.h2End, 7, 12),
};
if ((months.h1Start === '') !== (months.h1End === '') || (months.h2Start === '') !== (months.h2End === '')) throw new RangeError('months incomplete');
if (months.h1Start !== '' && months.h1Start > months.h1End) throw new RangeError('months reversed');
if (months.h2Start !== '' && months.h2Start > months.h2End) throw new RangeError('months reversed');
const base = {
row: `sim-${index}`, source: 'simulation', name: text(input.name) || `模擬 ${index + 1}`,
dept, group: text(input.group) || '', company, isManager: false, weeklyWorkDays: 5,
calculationReady: true, calculationIssue: '', ...months,
};
if (kind === 'O' || kind === 'parttime') {
// 工讀當 O:日薪 = 時薪 × 8。外包可以填日薪或時薪。
let dayrate;
if (salaryType === 'daily') dayrate = amount;
else if (salaryType === 'hourly') dayrate = amount * PART_TIME_HOURS_PER_DAY;
else throw new RangeError('O needs a daily or hourly rate');
return { ...base, role: 'O - 外包', title: kind === 'parttime' ? '工讀生' : '外包', partTime: kind === 'parttime', dayrate, salary: 0, hourlyRate: 0, salaryType: 'daily' };
}
const role = kind === 'P' ? 'P - 製作' : 'A - 藝術家';
const title = kind === 'intern' ? 'Intern' : (text(input.title) || (kind === 'P' ? 'Producer' : 'Artist'));
if (salaryType === 'monthly') return { ...base, role, title, salary: amount, hourlyRate: 0, salaryType: 'monthly' };
if (salaryType === 'hourly') return { ...base, role, title, salary: 0, hourlyRate: amount, salaryType: 'hourly' };
if (salaryType === 'daily') return { ...base, role, title, salary: 0, hourlyRate: amount / 8, salaryType: 'hourly' };
throw new RangeError('unknown salary type');
}
// 依模擬內容做出一份新的輸入資料(不動原本的資料)。
export function applySimulation(payload, dept, { additions = [], raises = [] } = {}) {
if (!Array.isArray(additions) || additions.length > MAX_ADDITIONS) throw new RangeError('too many additions');
if (!Array.isArray(raises) || raises.length > MAX_RAISES) throw new RangeError('too many raises');
const baseData = JSON.parse(JSON.stringify(payload.baseData));
const inDept = baseData.filter(p => (p.dept || '').trim() === dept);
const company = inDept.find(p => p.company)?.company || '';
for (const raise of raises) {
const key = text(String(raise.employeeNumber ?? ''), 40);
const person = inDept.find(p => String(p.employeeNumber || '') === key && p.source === 'hr-sync' && !String(p.role || '').startsWith('O'));
if (!person) throw new RangeError('raise target not in department');
const amount = money(raise.amount);
if (person.salaryType === 'hourly') person.hourlyRate = amount; else person.salary = amount;
}
additions.forEach((input, index) => baseData.push(simulatedPerson(input, { dept, company }, index)));
return { ...payload, baseData };
}
// 前後比較:只回傳這個部門的數字。
export function compareDept(before, after, anchorsBefore, anchorsAfter, dept) {
const pick = (model, anchors) => {
const coda = model.codaGroups?.[dept] || { coda: 0, avgDailyCoda: 0, groups: {} };
const alloc = model.allocations?.deptData?.[dept];
return {
actualCoda: coda.coda, avgDailyCoda: coda.avgDailyCoda,
groups: Object.fromEntries(Object.entries(coda.groups).map(([g, v]) => [g, { actualCoda: v.coda, avgDailyCoda: v.avgDailyCoda, headcount: v.people.length }])),
invoice: alloc ? model.invoice.finalInvoiceTotal * (alloc.finalPct || 0) : null,
invoiceShare: alloc ? alloc.finalPct || 0 : null,
multiplier: multiplierFor(model, dept)?.value ?? null,
anchoredCoda: anchors?.coda?.[dept]?.value ?? null,
anchoredInvoice: anchors?.invoice?.[dept]?.annual ?? null,
};
};
const a = pick(before, anchorsBefore);
const b = pick(after, anchorsAfter);
const delta = (x, y) => (x === null || y === null ? null : Math.round(y - x));
const groups = [...new Set([...Object.keys(a.groups), ...Object.keys(b.groups)])].map(group => ({
group,
before: { actualCoda: Math.round(a.groups[group]?.actualCoda || 0), avgDailyCoda: Math.round(a.groups[group]?.avgDailyCoda || 0), headcount: a.groups[group]?.headcount || 0 },
after: { actualCoda: Math.round(b.groups[group]?.actualCoda || 0), avgDailyCoda: Math.round(b.groups[group]?.avgDailyCoda || 0), headcount: b.groups[group]?.headcount || 0 },
}));
const rows = ['actualCoda', 'avgDailyCoda', 'anchoredCoda', 'invoice', 'anchoredInvoice'].map(key => ({
key, before: a[key] === null ? null : Math.round(a[key]), after: b[key] === null ? null : Math.round(b[key]), delta: delta(a[key], b[key]),
}));
// 倍率(兩位小數)與發票佔比(0–1):不四捨五入成整數。
for (const key of ['multiplier', 'invoiceShare']) {
rows.push({ key, before: a[key], after: b[key], delta: a[key] === null || b[key] === null ? null : b[key] - a[key] });
}
return { dept, rows, groups, anchored: Boolean(anchorsBefore?.active) };
}