CI / build (push) Successful in 40s
Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
664 lines
37 KiB
JavaScript
664 lines
37 KiB
JavaScript
// PM Board 計算核心。網頁與伺服器載入同一份程式碼,保證兩邊算出來的數字一樣。
|
||
// - 網頁:以一般 <script> 載入,函式成為全域函式,讀取頁面上的 globalParams、baseData。
|
||
// - 伺服器:calc-engine.js 用 node:vm 在獨立環境執行,globalParams、baseData 由呼叫端提供。
|
||
// 這裡只放純計算,不碰畫面(DOM)。本檔的函式是從 index.html 原封不動搬過來的。
|
||
|
||
// --- INIT ORG STRUCTURE ---
|
||
function initOrgStructure() {
|
||
if (!globalParams.orgStructure) {
|
||
globalParams.orgStructure = {};
|
||
|
||
// 1. Enforce specific department order first
|
||
const predefinedOrder = ['前製部', '廣告部', '視效部', '動畫部'];
|
||
predefinedOrder.forEach(d => { globalParams.orgStructure[d] = []; });
|
||
|
||
// 2. Populate groups from data
|
||
baseData.forEach(p => {
|
||
const dept = (p.dept || '').trim();
|
||
if (!dept) return;
|
||
|
||
if (!globalParams.orgStructure[dept]) {
|
||
globalParams.orgStructure[dept] = [];
|
||
}
|
||
const group = (p.group || '').trim() || '未分組';
|
||
if (!globalParams.orgStructure[dept].includes(group)) {
|
||
globalParams.orgStructure[dept].push(group);
|
||
}
|
||
});
|
||
|
||
// 3. Remove functionally empty predefined departments if they have no people (optional safety)
|
||
Object.keys(globalParams.orgStructure).forEach(d => {
|
||
if (globalParams.orgStructure[d].length === 0 && predefinedOrder.includes(d)) {
|
||
// We keep it to maintain the visible structure even if empty in the model,
|
||
// but normally we might delete it. For now, leave it to keep the 4 pillars.
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
// --- CALCULATION ENGINE ---
|
||
function isSupportRole(role) {
|
||
return /^G\s*-/.test(String(role || ''));
|
||
}
|
||
|
||
function isCalculationRole(role) {
|
||
return /^(P|A|O|G)\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) {
|
||
// Units outside the invoice count HR salary × 人薪倍率 without needing a P/A role.
|
||
const invoiceCompanyMap = deptCompanyMap(data);
|
||
// 1. Data Migration & Cost Reset
|
||
data.forEach((p, idx) => {
|
||
// Critical: Normalize all metadata immediately to ensure consistent mapping
|
||
if (p.dept) p.dept = p.dept.trim();
|
||
if (p.name) p.name = p.name.trim();
|
||
if (p.group) p.group = p.group.trim();
|
||
|
||
// Migrate old format if necessary
|
||
if (p.start !== undefined && p.h1Start === undefined) {
|
||
const s = parseInt(p.start);
|
||
const e = parseInt(p.end);
|
||
p.h1Start = s <= 6 ? s : "";
|
||
p.h1End = s <= 6 ? Math.min(e, 6) : "";
|
||
p.h2Start = e >= 7 ? Math.max(s, 7) : "";
|
||
p.h2End = e >= 7 ? e : "";
|
||
delete p.start;
|
||
delete p.end;
|
||
}
|
||
|
||
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.
|
||
p.costCountedUnclassified = p.source === 'hr-sync' && !p.calculationReady
|
||
&& p.calculationIssue === '待設定 P/A 職能'
|
||
&& personInvoiceRole(p, invoiceCompanyMap) === 'exclude';
|
||
// G (營運支援) inside invoice-bearing or cost-sharing units is left out entirely.
|
||
p.supportExcluded = isSupportRole(p.role) && personInvoiceRole(p, invoiceCompanyMap) !== 'exclude';
|
||
if (p.supportExcluded) {
|
||
p.realSalaryTotal = 0;
|
||
p.totalCost = 0;
|
||
if (p.row === undefined) p.row = idx;
|
||
return;
|
||
}
|
||
if (p.source === 'hr-sync' && !p.calculationReady && !p.costCountedUnclassified) {
|
||
p.realSalaryTotal = 0;
|
||
p.totalCost = 0;
|
||
if (p.row === undefined) p.row = idx;
|
||
return;
|
||
}
|
||
|
||
// Interns: no CODA and no cost in CODA / A:P; they still count as A / P headcount
|
||
// (see calculateDeptAllocations). Their salary × 1 goes into the invoice only (invoiceCost).
|
||
if (isCostExcludedIntern(p)) {
|
||
p.realSalaryTotal = 0;
|
||
p.totalCost = 0;
|
||
if (p.row === undefined) p.row = idx;
|
||
let internSalary = 0;
|
||
const monthlyInvoiceCost = new Array(12).fill(0);
|
||
for (let m = 1; m <= 12; m++) {
|
||
const inH1 = (p.h1Start && p.h1End && m >= parseInt(p.h1Start) && m <= parseInt(p.h1End));
|
||
const inH2 = (p.h2Start && p.h2End && m >= parseInt(p.h2Start) && m <= parseInt(p.h2End));
|
||
if (!inH1 && !inH2) continue;
|
||
const monthSalary = p.salaryType === 'hourly'
|
||
? hourlyMonthlyAmount(p, m, parseFloat(p.hourlyRate) || 0)
|
||
: (parseFloat(p.salary) || 0);
|
||
internSalary += monthSalary;
|
||
monthlyInvoiceCost[m - 1] = monthSalary * INTERN_INVOICE_MULTIPLIER;
|
||
}
|
||
p.invoiceCost = internSalary * INTERN_INVOICE_MULTIPLIER;
|
||
p.monthlyInvoiceCost = monthlyInvoiceCost;
|
||
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);
|
||
// Critical: Ensure row index is assigned if missing even in Public version
|
||
if (p.row === undefined) p.row = idx;
|
||
return;
|
||
}
|
||
|
||
// Ensure every person has a stable row index
|
||
if (p.row === undefined) p.row = idx;
|
||
|
||
// M & N: Month-by-Month Accumulation
|
||
let accumulatedRealSalary = 0;
|
||
let accumulatedTotalCost = 0;
|
||
let accumulatedCostNoUtil = 0;
|
||
// 每月成本(定錨、調動按月拆分用):monthlyCost 同 totalCost,monthlyCodaCost 同 costNoUtil。
|
||
const monthlyCost = new Array(12).fill(0);
|
||
const monthlyCodaCost = new Array(12).fill(0);
|
||
|
||
if (isOutsource) {
|
||
// 常態型外包: one multiplier for everyone, 核心參數 › 外包倍率 (default 1.5).
|
||
p.workRateUsed = contractorMultiplier();
|
||
} else if (p.workRateUsed === undefined || p.workRateUsed === null || p.workRateUsed === "") {
|
||
p.workRateUsed = 1.0;
|
||
}
|
||
const workRate = isOutsource ? contractorMultiplier() : (parseFloat(p.workRateUsed) || 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
|
||
const inH1 = (p.h1Start && p.h1End && m >= parseInt(p.h1Start) && m <= parseInt(p.h1End));
|
||
const inH2 = (p.h2Start && p.h2End && m >= parseInt(p.h2Start) && m <= parseInt(p.h2End));
|
||
|
||
if (inH1 || inH2) {
|
||
// Monthly salary is the current salary (no historical raise events).
|
||
const currentMonthSalary = p.salaryType === 'hourly'
|
||
? hourlyMonthlyAmount(p, m, baseHourlyRate)
|
||
: baseSalary;
|
||
|
||
accumulatedRealSalary += currentMonthSalary;
|
||
// APPLICATION OF ROLE-SPECIFIC UTILIZATION: Efficiency penalty (divisor) only for in-house staff
|
||
const utilP = globalParams.utilizationP || globalParams.utilization || 1.0;
|
||
const utilA = globalParams.utilizationA || globalParams.utilization || 1.0;
|
||
let util = 1.0;
|
||
if (!isOutsource) {
|
||
util = (p.role && p.role.startsWith('P')) ? utilP : utilA;
|
||
}
|
||
accumulatedTotalCost += (currentMonthSalary * opMult * workRate) / util;
|
||
accumulatedCostNoUtil += currentMonthSalary * opMult * workRate;
|
||
monthlyCost[m - 1] = (currentMonthSalary * opMult * workRate) / util;
|
||
monthlyCodaCost[m - 1] = currentMonthSalary * opMult * workRate;
|
||
}
|
||
}
|
||
|
||
p.realSalaryTotal = accumulatedRealSalary;
|
||
p.totalCost = accumulatedTotalCost;
|
||
p.costNoUtil = accumulatedCostNoUtil;
|
||
p.monthlyCost = monthlyCost;
|
||
p.monthlyCodaCost = monthlyCodaCost;
|
||
});
|
||
|
||
// 2. Dept Raw Totals (DT)
|
||
// Use orgStructure to define valid active departments
|
||
initOrgStructure();
|
||
const depts = Object.keys(globalParams.orgStructure);
|
||
const deptStats = {};
|
||
|
||
depts.forEach(d => {
|
||
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 => 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
|
||
const rawDtWithOutsource = pInDept.reduce((acc, p) => acc + (p.totalCost || 0), 0);
|
||
|
||
const dt = rawDt;
|
||
const artistCost = rawArtistCost;
|
||
|
||
deptStats[d] = {
|
||
rawDt: rawDtWithOutsource, // Keep all costs for the studio raw total
|
||
dt,
|
||
artistCost,
|
||
personnel: pInDept.length
|
||
};
|
||
});
|
||
|
||
// 3. Final CODA per department: its own non-outsource DT (P + A)
|
||
const businessDepts = Object.keys(globalParams.orgStructure);
|
||
|
||
businessDepts.forEach(d => {
|
||
deptStats[d].coda = deptStats[d].dt;
|
||
deptStats[d].multiplier = deptStats[d].artistCost === 0 ? 0 : (deptStats[d].coda / deptStats[d].artistCost);
|
||
});
|
||
|
||
return {
|
||
data,
|
||
deptStats,
|
||
studioTotalDT: Object.values(deptStats).reduce((acc, s) => acc + s.dt, 0),
|
||
studioRawTotalDT: Object.values(deptStats).reduce((acc, s) => acc + s.rawDt, 0)
|
||
};
|
||
}
|
||
|
||
// 外包倍率 (核心參數 › 基本參數): 常態型外包 cost × this in the invoice and in 全企業總成本.
|
||
function contractorMultiplier() {
|
||
const v = Number(globalParams.contractorMultiplier);
|
||
return globalParams.contractorMultiplier !== undefined && globalParams.contractorMultiplier !== '' && Number.isFinite(v) && v >= 0 ? v : 1.5;
|
||
}
|
||
|
||
function calculateInvoiceSummary(current) {
|
||
let totalPA = 0;
|
||
let totalO = 0;
|
||
initOrgStructure();
|
||
const companyMap = deptCompanyMap(current);
|
||
let sharedCost = 0;
|
||
current.filter(p => ['bear', 'share'].includes(personInvoiceRole(p, companyMap))).forEach(p => {
|
||
// invoiceCost: cost that counts for the invoice only (interns, salary × 1).
|
||
const cost = (p.totalCost || 0) + (p.invoiceCost || 0);
|
||
if (personInvoiceRole(p, companyMap) === 'share') sharedCost += cost;
|
||
if (p.role.startsWith('O')) {
|
||
totalO += cost;
|
||
} else {
|
||
totalPA += cost;
|
||
}
|
||
});
|
||
|
||
const extOutsource = globalParams.externalProjectOutsourcing !== undefined ? parseFloat(globalParams.externalProjectOutsourcing) : 30000000;
|
||
const tripInvoices = globalParams.employeeTripInvoices !== undefined ? parseFloat(globalParams.employeeTripInvoices) : 15000000;
|
||
const grossMargin = (globalParams.grossMarginPct !== undefined) ? parseFloat(globalParams.grossMarginPct) : 0.85;
|
||
|
||
// totalO already carries 外包倍率 (see the cost loop); totalORaw is the contract amount before it.
|
||
const totalORaw = current.filter(p => p.role.startsWith('O') && ['bear', 'share'].includes(personInvoiceRole(p, companyMap))).reduce((s, p) => s + (p.realSalaryTotal || 0), 0);
|
||
// Only internal staff carry the margin; 常態型外包 and 專案委外 go in at cost.
|
||
const targetRevenue = totalPA / grossMargin + totalO + extOutsource;
|
||
const finalInvoiceTotal = targetRevenue + tripInvoices;
|
||
|
||
return { totalPA, totalO, totalORaw, sharedCost, extOutsource, tripInvoices, grossMargin, finalInvoiceTotal };
|
||
}
|
||
|
||
// Companies shown as a single multiplier on the dashboard instead of one per department.
|
||
const DASHBOARD_COMPANY_MULTIPLIERS = ['夢境現實'];
|
||
|
||
// Multiplier units for the dashboard: each department, except companies listed above,
|
||
// which become one unit over the whole company (including people without a department).
|
||
// multiplier = internal (P + A + G, no 外包) cost ÷ A cost; the display multiplies by 人薪倍率.
|
||
function dashboardMultiplierUnits(current, depts, deptStats) {
|
||
const map = deptCompanyMap(current);
|
||
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)) {
|
||
if (seen.has(company)) return;
|
||
seen.add(company);
|
||
const people = current.filter(p => shortCompanyName(personCompany(p, map)) === company);
|
||
const internal = people.filter(p => isCalculationRole(p.role) && !p.role.startsWith('O')).reduce((sum, p) => sum + (p.totalCost || 0), 0);
|
||
const artist = people.filter(p => p.role.startsWith('A')).reduce((sum, p) => sum + (p.totalCost || 0), 0);
|
||
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 });
|
||
});
|
||
return units;
|
||
}
|
||
|
||
// 部門 CODA uses cost without 產出率 (年薪 × 人薪倍率 × 管理率); 外包 keeps its own cost.
|
||
function codaCost(p) {
|
||
if (String(p.role || '').startsWith('O')) return p.totalCost || 0;
|
||
return p.costNoUtil !== undefined ? p.costNoUtil : (p.totalCost || 0);
|
||
}
|
||
|
||
// 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. 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) {
|
||
const add = {};
|
||
const out = {};
|
||
const rules = [];
|
||
const map = deptCompanyMap(current);
|
||
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);
|
||
const noDeptPeople = rule.noDeptP ? current.filter(p => !(p.dept || '').trim()
|
||
&& String(p.role || '').startsWith('P')
|
||
&& shortCompanyName(personCompany(p, map)) === rule.company) : [];
|
||
const noDeptCoda = noDeptPeople.reduce((s, p) => s + codaCost(p), 0);
|
||
const pool = fromDepts.reduce((s, d) => s + (ownCoda[d] || 0), 0) + noDeptCoda;
|
||
if (pool <= 0) return;
|
||
const base = to.reduce((s, d) => s + (ownCoda[d] || 0), 0);
|
||
const parts = {};
|
||
to.forEach(d => {
|
||
const share = base > 0 ? (ownCoda[d] || 0) / base : 1 / to.length;
|
||
parts[d] = pool * share;
|
||
add[d] = (add[d] || 0) + parts[d];
|
||
});
|
||
fromDepts.forEach(d => { out[d] = (out[d] || 0) + (ownCoda[d] || 0); });
|
||
rules.push({ ...rule, fromDepts, to, noDeptPeople, noDeptCoda, pool, parts });
|
||
});
|
||
return { add, out, rules };
|
||
}
|
||
|
||
// Same per-unit CODA as the 部門 CODA page: P cost + A cost (外包 and G not included),
|
||
// after CODA sharing.
|
||
function codaPageByDept(current, withoutSharing = false) {
|
||
const out = {};
|
||
Object.keys(globalParams.orgStructure || {}).forEach(d => { out[d] = 0; });
|
||
current.forEach(p => {
|
||
const d = (p.dept || '').trim();
|
||
if (!(d in out)) return;
|
||
if (p.role.startsWith('P') || p.role.startsWith('A')) out[d] += codaCost(p);
|
||
});
|
||
if (withoutSharing) return out;
|
||
const shares = codaShares(current, { ...out });
|
||
Object.entries(shares.out).forEach(([d, v]) => { out[d] -= v; });
|
||
Object.entries(shares.add).forEach(([d, v]) => { out[d] += v; });
|
||
return out;
|
||
}
|
||
|
||
// Shared function for calculating department allocations (Metric 1, 2, 3 and Final %)
|
||
function calculateDeptAllocations(current, finalInvoiceTotal) {
|
||
const businessDepts = invoiceDepts(current);
|
||
const wP = Number(globalParams.invoiceWeightP ?? 0.25);
|
||
const wA = Number(globalParams.invoiceWeightA ?? 0.4);
|
||
const wS = Number(globalParams.invoiceWeightSurplus ?? 0.35);
|
||
const pcHeadcountWeight = Number(globalParams.pPCReductionPct ?? 0.7);
|
||
|
||
const deptData = {};
|
||
let globalP = 0;
|
||
let globalA = 0;
|
||
businessDepts.forEach(d => {
|
||
deptData[d] = { pCost: 0, aCost: 0, oCost: 0, pNum: 0, aNum: 0, weight3: 0, m1: 0, m2: 0, m3: 0, finalPct: 0, invoiceTarget: 0 };
|
||
});
|
||
|
||
current.forEach(person => {
|
||
const d = (person.dept || '').trim();
|
||
if (!businessDepts.includes(d)) return;
|
||
const cost = person.totalCost || 0;
|
||
// Headcount for the A:P ratio is full-time equivalent (months in the year ÷ 12).
|
||
// Interns count by their P/A role; 常態型外包 count as A (headcount only, no cost).
|
||
// A Production Coordinator counts as a fraction of a P (核心參數 › PC 承擔比例); managers count as 1.
|
||
const fte = activeMonths(person) / 12;
|
||
if (person.role.startsWith('P')) {
|
||
const pWeight = isProductionCoordinator(person) ? pcHeadcountWeight : 1;
|
||
deptData[d].pCost += cost;
|
||
deptData[d].pNum += fte * pWeight;
|
||
globalP += cost;
|
||
} else if (person.role.startsWith('A')) {
|
||
deptData[d].aCost += cost;
|
||
deptData[d].aNum += fte;
|
||
globalA += cost;
|
||
} else if (person.role.startsWith('O')) {
|
||
deptData[d].aNum += fte;
|
||
deptData[d].oNum = (deptData[d].oNum || 0) + fte;
|
||
deptData[d].oCost += cost;
|
||
}
|
||
});
|
||
|
||
// 指標3 P 輕重: P cost × (P cost ÷ A cost), A cost including 常態型外包. A department whose
|
||
// P is heavy relative to its A carries more; one with relatively light P carries less.
|
||
let totalWeight3 = 0;
|
||
businessDepts.forEach(d => {
|
||
const data = deptData[d];
|
||
data.m1 = globalP > 0 ? (data.pCost / globalP) : 0;
|
||
data.m2 = globalA > 0 ? (data.aCost / globalA) : 0;
|
||
data.aCostAll = data.aCost + data.oCost;
|
||
data.costRatio = data.pCost > 0 ? data.aCostAll / data.pCost : Infinity;
|
||
// Without any A cost the P is weighed at par (P ÷ A taken as 1).
|
||
data.weight3 = data.aCostAll > 0 ? data.pCost * (data.pCost / data.aCostAll) : data.pCost;
|
||
totalWeight3 += data.weight3;
|
||
});
|
||
|
||
businessDepts.forEach(d => {
|
||
const data = deptData[d];
|
||
data.m3 = totalWeight3 > 0 ? (data.weight3 / totalWeight3) : 0;
|
||
data.finalPct = (data.m1 * wP) + (data.m2 * wA) + (data.m3 * wS);
|
||
data.invoiceTarget = finalInvoiceTotal * data.finalPct;
|
||
});
|
||
|
||
// Lean status is a ranking of the A:P cost ratio against all invoice-bearing departments
|
||
// combined: best = 精實, worst = 超標, others above / below the overall = 接近精實 / 臨近超標.
|
||
const sumA = businessDepts.reduce((s, d) => s + deptData[d].aCostAll, 0);
|
||
const sumP = businessDepts.reduce((s, d) => s + deptData[d].pCost, 0);
|
||
const overallRatio = sumP > 0 ? sumA / sumP : Infinity;
|
||
const ratioOf = d => deptData[d].costRatio;
|
||
const ratios = businessDepts.map(ratioOf);
|
||
const best = Math.max(...ratios);
|
||
const worst = Math.min(...ratios);
|
||
const EPS = 1e-9;
|
||
businessDepts.forEach(d => {
|
||
const data = deptData[d];
|
||
const ratio = ratioOf(d);
|
||
let status;
|
||
if (businessDepts.length > 1 && best - worst > EPS && ratio >= best - EPS) status = 'lean';
|
||
else if (businessDepts.length > 1 && best - worst > EPS && ratio <= worst + EPS) status = 'over';
|
||
else if (businessDepts.length === 1) status = 'lean';
|
||
else status = ratio >= overallRatio - EPS ? 'nearLean' : 'nearOver';
|
||
// P cost above (+) or below (−) what the overall A:P cost ratio would give this department.
|
||
const vsOverall = Number.isFinite(overallRatio) && overallRatio > 0 ? data.pCost - data.aCostAll / overallRatio : 0;
|
||
data.lean = { status, ratio, overallRatio, vsOverall, toOverall: Math.max(0, vsOverall) };
|
||
});
|
||
// Within 臨近超標, departments with more extra P cost than the group's average are
|
||
// shown orange; the rest yellow.
|
||
const nearOver = businessDepts.filter(d => deptData[d].lean.status === 'nearOver');
|
||
const meanGap = nearOver.reduce((s, d) => s + deptData[d].lean.vsOverall, 0) / (nearOver.length || 1);
|
||
nearOver.forEach(d => {
|
||
if (deptData[d].lean.vsOverall > meanGap + EPS) deptData[d].lean.status = 'nearOverHigh';
|
||
});
|
||
|
||
return { deptData, globalP, globalA, totalWeight3, wP, wA, wS, overallRatio };
|
||
}
|
||
|
||
function activeMonths(p) {
|
||
const m1 = (p.h1Start && p.h1End) ? Math.max(0, parseInt(p.h1End) - parseInt(p.h1Start) + 1) : 0;
|
||
const m2 = (p.h2Start && p.h2End) ? Math.max(0, parseInt(p.h2End) - parseInt(p.h2Start) + 1) : 0;
|
||
return Math.min(12, (m1 || 0) + (m2 || 0));
|
||
}
|
||
|
||
// Only 夢想創造 carries the annual invoice (and the global invoice parameters). Other
|
||
// companies are shown as cost × 人薪倍率 only. A department belongs to the company most of
|
||
// its HR staff belong to; contractors follow their department.
|
||
const INVOICE_COMPANY = '夢想創造';
|
||
|
||
function deptCompanyMap(current) {
|
||
const votes = {};
|
||
current.filter(p => !(p.role || '').startsWith('O') && p.company && p.dept).forEach(p => {
|
||
votes[p.dept] = votes[p.dept] || {};
|
||
votes[p.dept][p.company] = (votes[p.dept][p.company] || 0) + 1;
|
||
});
|
||
return new Map(Object.entries(votes).map(([dept, v]) => [dept, Object.entries(v).sort((a, b) => b[1] - a[1])[0][0]]));
|
||
}
|
||
|
||
function personCompany(person, map) {
|
||
if ((person.role || '').startsWith('O')) return map.get((person.dept || '').trim()) || '';
|
||
return person.company || '';
|
||
}
|
||
|
||
function isInvoiceCompany(name) {
|
||
return shortCompanyName(name) === INVOICE_COMPANY;
|
||
}
|
||
|
||
function companyDefaultRole(company) {
|
||
const saved = globalParams.invoiceRoles?.companies?.[company];
|
||
if (saved) return saved;
|
||
return isInvoiceCompany(company) ? 'bear' : 'exclude';
|
||
}
|
||
|
||
function deptRole(dept, company) {
|
||
return globalParams.invoiceRoles?.depts?.[dept] || companyDefaultRole(company);
|
||
}
|
||
|
||
function personInvoiceRole(person, map) {
|
||
const dept = (person.dept || '').trim();
|
||
const company = personCompany(person, map);
|
||
if (dept && (!globalParams.orgStructure || Object.prototype.hasOwnProperty.call(globalParams.orgStructure, dept))) {
|
||
return deptRole(dept, map.get(dept) || company);
|
||
}
|
||
return companyDefaultRole(company);
|
||
}
|
||
|
||
function invoiceDepts(current) {
|
||
initOrgStructure();
|
||
const map = deptCompanyMap(current);
|
||
return Object.keys(globalParams.orgStructure).filter(d => deptRole(d, map.get(d) || '') === 'bear');
|
||
}
|
||
|
||
// Interns (title "Intern") are not part of cost, CODA or per-person averages, but still
|
||
// count as A / P headcount for the A:P ratio used in invoice allocation.
|
||
// 實習生進發票的倍率:薪資 × 1(不乘人薪倍率),不算 CODA。
|
||
const INTERN_INVOICE_MULTIPLIER = 1;
|
||
|
||
function isCostExcludedIntern(person) {
|
||
return !String(person?.role || '').startsWith('O') && /\bintern\b/i.test(String(person?.title || ''));
|
||
}
|
||
|
||
// PC = Production Coordinator. HR uses the full title, older data used the "PC" abbreviation.
|
||
function isProductionCoordinator(person) {
|
||
const title = String(person?.title || '');
|
||
const role = String(person?.role || '');
|
||
return /production\s+coordinator/i.test(title) || /\bPC\b/i.test(title) || /\bPC\b/i.test(role);
|
||
}
|
||
|
||
// Company comes from HR's organization tree (corporationName). Long legal names are
|
||
// shortened for display only; filtering always uses the full name.
|
||
function shortCompanyName(name) {
|
||
return String(name || '').replace(/股份有限公司$|有限公司$/, '');
|
||
}
|
||
|
||
// 百分比顯示(無條件進位到小數第二位)。計算說明文字也會用到,所以放在計算核心。
|
||
function formatPct(val) {
|
||
if (isNaN(val) || val === 0) return "0.00";
|
||
return (Math.ceil(val * 100) / 100).toFixed(2);
|
||
}
|
||
|
||
// 組別 CODA:部門 CODA 依組內 A 成本比例分到各組,再套研發減免與 CG Lead 承擔,
|
||
// 減掉的部分分給一般組。原本寫在 renderCoda 裡,原封不動搬來,網頁與伺服器共用。
|
||
function codaGroupsForDept(deptName, groups, deptTotalCoda) {
|
||
const sortedGroups = Object.entries(groups).map(([gName, gData]) => {
|
||
const gRaw = gData.rawA + gData.rawO;
|
||
// Group CODA is distributed by the group's share of the department's A cost.
|
||
// PARADIGM SHIFT: O costs are no longer factors in CODA aggregation
|
||
const groupA = gData.rawA;
|
||
const deptA = Object.values(groups).reduce((acc, g) => acc + g.rawA, 0);
|
||
|
||
const initialCoda = deptA === 0 ? 0 : deptTotalCoda * (groupA / deptA);
|
||
|
||
const isRD = (globalParams.rdGroups || []).includes(`${deptName}|${gName}`);
|
||
const isCGLead = (globalParams.cgLeadGroups || []).includes(`${deptName}|${gName}`);
|
||
|
||
// Calculate Total FTE for the group to correctly derive Average Daily CODA
|
||
const groupFTE = gData.people.reduce((acc, p) => {
|
||
if (p.role.startsWith('O') || isCostExcludedIntern(p)) return acc; // Outsource and interns do not count towards FTE for group CODA average
|
||
const m1 = (p.h1Start && p.h1End) ? Math.max(0, parseInt(p.h1End) - parseInt(p.h1Start) + 1) : 0;
|
||
const m2 = (p.h2Start && p.h2End) ? Math.max(0, parseInt(p.h2End) - parseInt(p.h2Start) + 1) : 0;
|
||
return acc + ((m1 + m2) / 12);
|
||
}, 0);
|
||
|
||
return { gName, gData, gRaw, groupA, initialCoda, isRD, isCGLead, groupFTE };
|
||
});
|
||
|
||
const rdReductionPct = globalParams.rdReductionPct ?? 0.35;
|
||
const cgLeadReductionPct = globalParams.cgLeadReductionPct ?? 0.85; // 承擔 85%
|
||
|
||
// Calculate Total Redistribution Pool from RD and CG Lead
|
||
const totalRDTax = sortedGroups.filter(g => g.isRD).reduce((acc, g) => acc + (g.initialCoda * rdReductionPct), 0);
|
||
// 同時是研發組與 CG Lead 組:先減研發,再對剩下的部分減 CG Lead(2026-11-04 決定「兩個都減」),
|
||
// 兩份減掉的金額都進分攤池,所以各組加總仍等於部門 CODA。
|
||
const totalCGLeadTax = sortedGroups.filter(g => g.isCGLead).reduce((acc, g) => acc + (g.initialCoda * (g.isRD ? (1 - rdReductionPct) : 1) * (1 - cgLeadReductionPct)), 0);
|
||
|
||
// Final pool to redistribute to NORMAL groups (Non-RD AND Non-CGLead)
|
||
const totalRedistributionPool = totalRDTax + totalCGLeadTax;
|
||
const normalGroupsInitialCodaTotal = sortedGroups.filter(g => !g.isRD && !g.isCGLead).reduce((acc, g) => acc + g.initialCoda, 0);
|
||
|
||
sortedGroups.forEach(g => {
|
||
if (g.isRD && g.isCGLead) {
|
||
g.finalCoda = g.initialCoda * (1 - rdReductionPct) * cgLeadReductionPct;
|
||
g.rdNote = `研發減免 -${formatPct(rdReductionPct * 100)}%,CG Lead 承擔 -${formatPct((1 - cgLeadReductionPct) * 100)}%`;
|
||
} else if (g.isRD) {
|
||
g.finalCoda = g.initialCoda * (1 - rdReductionPct);
|
||
g.rdNote = `研發減免 -${formatPct(rdReductionPct * 100)}%`;
|
||
} else if (g.isCGLead) {
|
||
g.finalCoda = g.initialCoda * cgLeadReductionPct;
|
||
g.rdNote = `CG Lead 承擔 -${formatPct((1 - cgLeadReductionPct) * 100)}%`;
|
||
} else {
|
||
const shareOfNormal = normalGroupsInitialCodaTotal === 0 ? 0 : (g.initialCoda / normalGroupsInitialCodaTotal);
|
||
g.finalCoda = g.initialCoda + (totalRedistributionPool * shareOfNormal);
|
||
if (totalRedistributionPool > 0) g.rdNote = `分攤研製及管理 CODA`;
|
||
}
|
||
});
|
||
return { sortedGroups, totalCGLeadTax };
|
||
}
|
||
|
||
// 伺服器用:每個部門、每個組的實際 CODA(與 CODA 頁相同算法)與平均日 CODA。
|
||
function codaByGroup(current) {
|
||
initOrgStructure();
|
||
const targetDepts = Object.keys(globalParams.orgStructure);
|
||
const deptCoda = codaPageByDept(current);
|
||
const groupsByDept = {};
|
||
targetDepts.forEach(d => { groupsByDept[d] = {}; });
|
||
current.filter(p => targetDepts.includes(p.dept) && (p.role.startsWith('A') || p.role.startsWith('O'))).forEach(p => {
|
||
const gName = p.group || '未分組';
|
||
const groups = groupsByDept[p.dept];
|
||
if (!groups[gName]) groups[gName] = { people: [], rawA: 0, rawO: 0 };
|
||
const cost = codaCost(p);
|
||
if (p.role.startsWith('A')) groups[gName].rawA += cost; else groups[gName].rawO += cost;
|
||
groups[gName].people.push(p);
|
||
});
|
||
const annualWorkDays = globalParams.annualWorkDays || 255;
|
||
const out = {};
|
||
targetDepts.forEach(d => {
|
||
const { sortedGroups } = codaGroupsForDept(d, groupsByDept[d], deptCoda[d] || 0);
|
||
// 部門平均日 CODA:與 CODA 頁相同(組內所有人,不含實習生,依在職月份折算人數)。
|
||
const deptFTE = Object.values(groupsByDept[d]).reduce((acc, g) => acc + g.people.reduce((acc2, p) => {
|
||
if (isCostExcludedIntern(p)) return acc2;
|
||
const m1 = (p.h1Start && p.h1End) ? Math.max(0, parseInt(p.h1End) - parseInt(p.h1Start) + 1) : 0;
|
||
const m2 = (p.h2Start && p.h2End) ? Math.max(0, parseInt(p.h2End) - parseInt(p.h2Start) + 1) : 0;
|
||
return acc2 + ((m1 + m2) / 12);
|
||
}, 0), 0);
|
||
out[d] = { coda: deptCoda[d] || 0, avgDailyCoda: deptFTE === 0 ? 0 : ((deptCoda[d] || 0) / annualWorkDays) / deptFTE, fte: deptFTE, groups: {} };
|
||
sortedGroups.forEach(g => {
|
||
out[d].groups[g.gName] = {
|
||
coda: g.finalCoda,
|
||
avgDailyCoda: g.groupFTE === 0 ? 0 : (g.finalCoda / annualWorkDays) / g.groupFTE,
|
||
fte: g.groupFTE,
|
||
aCost: g.groupA,
|
||
people: g.gData.people.map(p => p.employeeNumber || p.row),
|
||
};
|
||
});
|
||
});
|
||
return out;
|
||
}
|