CI / build (push) Successful in 30s
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
258 lines
12 KiB
JavaScript
258 lines
12 KiB
JavaScript
// 定錨:發票與定錨 CODA。純計算,不讀寫檔案(存檔在 anchor-store.js)。
|
||
//
|
||
// 規則(PLAN-ANCHOR.md):
|
||
// - 一年兩個定錨點 H1(1–6 月)、H2(7–12 月)。按下定錨時存一份快照。
|
||
// - 發票:部門全年 = 定錨全年 + 調動淨額 + 半年內「自身增減」的最高點(只增不減)。
|
||
// 自身增減 = 內部人力增減 ÷ 毛利率 + 常態型外包增減(已含外包倍率,不除毛利率)。
|
||
// 調動:生效月份起,這個人剩下月份的金額從原部門移到新部門,兩邊都不算增減,總額不變。
|
||
// - 定錨 CODA:每個組取「定錨值、半年內實際 CODA」的最高點;部門=各組加總。
|
||
// 調動時原組不降(最高點留著)、新組照實增加。
|
||
// - H1 = 全年 ÷ 2;H2 = 最新全年 − H1 結算。
|
||
|
||
export const HALVES = Object.freeze(['H1', 'H2']);
|
||
|
||
export function personKey(person) {
|
||
if (person.employeeNumber) return `hr:${person.employeeNumber}`;
|
||
return `${person.source || 'board'}:${person.row ?? ''}:${person.name || ''}`;
|
||
}
|
||
|
||
const sum = (list) => list.reduce((total, value) => total + (Number(value) || 0), 0);
|
||
const monthly = (list) => (Array.isArray(list) && list.length === 12 ? list.map(v => Number(v) || 0) : new Array(12).fill(0));
|
||
|
||
// 這個人在發票上的每月金額:內部人力(含實習生 × 1)與外包分開,外包不除毛利率。
|
||
function invoiceMonths(person) {
|
||
const isO = String(person.role || '').startsWith('O');
|
||
const cost = monthly(person.monthlyCost);
|
||
const extra = monthly(person.monthlyInvoiceCost);
|
||
return {
|
||
pa: isO ? new Array(12).fill(0) : cost.map((v, i) => v + extra[i]),
|
||
o: isO ? cost : new Array(12).fill(0),
|
||
};
|
||
}
|
||
|
||
// 調動後同一個人會拆成「調動前」「調動後」兩筆(splitTransfers);比對與快照時合回一個人:
|
||
// 金額相加,部門/組用調動後(現在)的。
|
||
export function mergedPeople(people) {
|
||
const byKey = new Map();
|
||
for (const p of people) {
|
||
const key = personKey(p);
|
||
const months = invoiceMonths(p);
|
||
const entry = byKey.get(key);
|
||
if (!entry) { byKey.set(key, { person: p, pa: months.pa, o: months.o, cost: (p.totalCost || 0) + (p.invoiceCost || 0) }); continue; }
|
||
entry.pa = entry.pa.map((v, i) => v + months.pa[i]);
|
||
entry.o = entry.o.map((v, i) => v + months.o[i]);
|
||
entry.cost += (p.totalCost || 0) + (p.invoiceCost || 0);
|
||
if (p.transferSplit !== 'before') entry.person = p;
|
||
}
|
||
return byKey;
|
||
}
|
||
|
||
// 快照:從伺服器算好的模型抓出定錨需要的數字。
|
||
export function buildSnapshot(model, { year, half, note, by, at }) {
|
||
const invoiceDeptNames = Object.keys(model.allocations?.deptData || {});
|
||
const people = [...mergedPeople(model.people)]
|
||
.filter(([, e]) => e.cost > 0)
|
||
.map(([key, { person: p, pa, o }]) => ({
|
||
key, name: p.name || '', dept: (p.dept || '').trim(), group: (p.group || '').trim(),
|
||
role: p.role || '', invoiceRole: p.invoiceRoleAtAnchor || null, pa, o,
|
||
}));
|
||
const invoice = {};
|
||
for (const dept of invoiceDeptNames) {
|
||
const data = model.allocations.deptData[dept];
|
||
invoice[dept] = { annual: model.invoice.finalInvoiceTotal * (data.finalPct || 0), finalPct: data.finalPct || 0 };
|
||
}
|
||
const coda = {};
|
||
for (const [dept, data] of Object.entries(model.codaGroups || {})) {
|
||
coda[dept] = { dept: data.coda, groups: Object.fromEntries(Object.entries(data.groups).map(([g, v]) => [g, v.coda])) };
|
||
}
|
||
return {
|
||
year, half, note: String(note || '').slice(0, 500), by, at,
|
||
calcVersion: model.calcVersion,
|
||
grossMargin: model.invoice.grossMargin,
|
||
finalInvoiceTotal: model.invoice.finalInvoiceTotal,
|
||
invoiceDepts: invoiceDeptNames,
|
||
invoice, coda, people,
|
||
};
|
||
}
|
||
|
||
// 調動:快照時的部門與現在不同。effectiveMonth 由使用者確認,預設為偵測到的月份。
|
||
export function detectTransfers(snapshot, model, savedMonths = {}, detectedMonth = 1) {
|
||
const now = new Map([...mergedPeople(model.people)].map(([key, e]) => [key, e.person]));
|
||
const list = [];
|
||
for (const before of snapshot.people) {
|
||
const current = now.get(before.key);
|
||
if (!current) continue;
|
||
const dept = (current.dept || '').trim();
|
||
const group = (current.group || '').trim();
|
||
if (dept === before.dept && group === before.group) continue;
|
||
const saved = savedMonths[before.key];
|
||
list.push({
|
||
key: before.key, name: before.name,
|
||
from: { dept: before.dept, group: before.group }, to: { dept, group },
|
||
effectiveMonth: Number.isInteger(saved?.month) ? saved.month : detectedMonth,
|
||
confirmed: Boolean(saved),
|
||
});
|
||
}
|
||
return list;
|
||
}
|
||
|
||
// 依調動生效月份,把每月金額分到前後部門。
|
||
function splitByDept(paMonths, oMonths, fromDept, toDept, effectiveMonth, into) {
|
||
for (let i = 0; i < 12; i += 1) {
|
||
const dept = i + 1 >= effectiveMonth ? toDept : fromDept;
|
||
if (!into[dept]) into[dept] = { pa: 0, o: 0 };
|
||
into[dept].pa += paMonths[i];
|
||
into[dept].o += oMonths[i];
|
||
}
|
||
}
|
||
|
||
function costsByDept(people, deptOf) {
|
||
const out = {};
|
||
for (const person of people) {
|
||
const { dept, pa, o, transfer } = deptOf(person);
|
||
if (transfer) splitByDept(pa, o, transfer.from.dept, transfer.to.dept, transfer.effectiveMonth, out);
|
||
else {
|
||
if (!out[dept]) out[dept] = { pa: 0, o: 0 };
|
||
out[dept].pa += sum(pa);
|
||
out[dept].o += sum(o);
|
||
}
|
||
}
|
||
return out;
|
||
}
|
||
|
||
// 發票:回傳每個承擔部門的 { anchored, transferNet, organic, peak, annual },並告訴呼叫端最高點有沒有更新。
|
||
export function anchoredInvoice(snapshot, model, transfers, peaks = {}) {
|
||
const margin = snapshot.grossMargin || 1;
|
||
const byKey = new Map(transfers.map(t => [t.key, t]));
|
||
// 定錨時的金額:調動的人生效月份前算原部門、之後算新部門(=把定錨金額移過去)。
|
||
const anchoredAdj = costsByDept(snapshot.people, p => ({ dept: p.dept, pa: p.pa, o: p.o, transfer: byKey.get(p.key) }));
|
||
const anchoredRaw = costsByDept(snapshot.people, p => ({ dept: p.dept, pa: p.pa, o: p.o }));
|
||
// 現在的金額:調動的人同樣按月拆分。
|
||
const current = costsByDept(model.people, p => {
|
||
const months = invoiceMonths(p);
|
||
const transfer = byKey.get(personKey(p));
|
||
return { dept: (p.dept || '').trim(), pa: months.pa, o: months.o, transfer };
|
||
});
|
||
const result = {};
|
||
const updates = {};
|
||
for (const dept of snapshot.invoiceDepts) {
|
||
const anchored = snapshot.invoice[dept]?.annual || 0;
|
||
const raw = anchoredRaw[dept] || { pa: 0, o: 0 };
|
||
const adj = anchoredAdj[dept] || { pa: 0, o: 0 };
|
||
const now = current[dept] || { pa: 0, o: 0 };
|
||
const transferNet = (adj.pa - raw.pa) / margin + (adj.o - raw.o);
|
||
const organic = (now.pa - adj.pa) / margin + (now.o - adj.o);
|
||
const previous = Number(peaks[dept]?.value) || 0;
|
||
const peak = Math.max(previous, organic, 0);
|
||
if (peak > previous + 0.5) updates[dept] = peak;
|
||
result[dept] = { anchored, transferNet, organic, peak, annual: anchored + transferNet + peak };
|
||
}
|
||
return { depts: result, peakUpdates: updates };
|
||
}
|
||
|
||
// 定錨 CODA:每個組取最高點;部門=各組加總(沒有組的部門用部門本身的最高點)。
|
||
export function anchoredCoda(snapshot, model, peaks = {}) {
|
||
const result = {};
|
||
const updates = {};
|
||
const depts = new Set([...Object.keys(snapshot.coda || {}), ...Object.keys(model.codaGroups || {})]);
|
||
for (const dept of depts) {
|
||
const before = snapshot.coda?.[dept] || { dept: 0, groups: {} };
|
||
const now = model.codaGroups?.[dept] || { coda: 0, groups: {} };
|
||
const groupNames = new Set([...Object.keys(before.groups), ...Object.keys(now.groups)]);
|
||
const groups = {};
|
||
for (const group of groupNames) {
|
||
const id = `${dept}|${group}`;
|
||
const anchored = before.groups[group] || 0;
|
||
const actual = now.groups[group]?.coda || 0;
|
||
const previous = Number(peaks[id]?.value) || 0;
|
||
const value = Math.max(previous, anchored, actual);
|
||
if (value > Math.max(previous, anchored) + 0.5) updates[id] = value;
|
||
groups[group] = { anchored, actual, value };
|
||
}
|
||
let value;
|
||
if (groupNames.size) value = sum(Object.values(groups).map(g => g.value));
|
||
else {
|
||
const id = `${dept}|`;
|
||
const previous = Number(peaks[id]?.value) || 0;
|
||
value = Math.max(previous, before.dept || 0, now.coda || 0);
|
||
if (value > Math.max(previous, before.dept || 0) + 0.5) updates[id] = value;
|
||
}
|
||
result[dept] = { anchored: before.dept || 0, actual: now.coda || 0, value, groups };
|
||
}
|
||
return { depts: result, peakUpdates: updates };
|
||
}
|
||
|
||
// 半年:H1 = 全年 ÷ 2;H2 = 最新全年 − H1 結算。
|
||
export function halves(annual, half, h1Settled) {
|
||
if (half === 'H1') return { h1: annual / 2, h1Settled: false, h2: null };
|
||
const h1 = Number(h1Settled) || 0;
|
||
return { h1, h1Settled: true, h2: annual - h1 };
|
||
}
|
||
|
||
// 異動清單:拿現在的資料和定錨快照逐人比對(新進、離職、調薪/成本變動、職能改變、調動)。
|
||
// 金額是「全年」的增減;發票增減 = 內部人力 ÷ 毛利率 + 外包。生效月份取 HR 的日期。
|
||
export function detectChanges(snapshot, model) {
|
||
const margin = snapshot.grossMargin || 1;
|
||
const before = new Map(snapshot.people.map(p => [p.key, p]));
|
||
const merged = mergedPeople(model.people);
|
||
const now = new Map([...merged].map(([key, e]) => [key, e.person]));
|
||
const monthOf = (date) => { const m = /^\d{4}-(\d{2})/.exec(String(date || '')); return m ? Number(m[1]) : null; };
|
||
const list = [];
|
||
const push = (type, key, name, dept, group, beforeCost, afterCost, effectiveMonth, extra = {}) => {
|
||
const pa = afterCost.pa - beforeCost.pa;
|
||
const o = afterCost.o - beforeCost.o;
|
||
list.push({ type, key, name, dept, group, effectiveMonth, costDelta: Math.round(pa + o), invoiceDelta: Math.round(pa / margin + o), ...extra });
|
||
};
|
||
const zero = { pa: 0, o: 0 };
|
||
for (const [key, p] of now) {
|
||
const cost = { pa: sum(merged.get(key).pa), o: sum(merged.get(key).o) };
|
||
const old = before.get(key);
|
||
const dept = (p.dept || '').trim();
|
||
const group = (p.group || '').trim();
|
||
if (!old) {
|
||
if (cost.pa + cost.o > 0) push('new', key, p.name || '', dept, group, zero, cost, monthOf(p.hireDate));
|
||
continue;
|
||
}
|
||
const oldCost = { pa: sum(old.pa), o: sum(old.o) };
|
||
if (old.dept !== dept || old.group !== group) {
|
||
list.push({ type: 'transfer', key, name: p.name || old.name, dept, group, from: { dept: old.dept, group: old.group }, effectiveMonth: null, costDelta: 0, invoiceDelta: 0 });
|
||
}
|
||
if (old.role !== (p.role || '')) push('role', key, p.name || old.name, dept, group, oldCost, cost, null, { fromRole: old.role, toRole: p.role || '' });
|
||
else if (Math.abs((cost.pa + cost.o) - (oldCost.pa + oldCost.o)) > 1) {
|
||
const type = p.leaveDate && cost.pa + cost.o < oldCost.pa + oldCost.o ? 'leave' : 'cost';
|
||
push(type, key, p.name || old.name, dept, group, oldCost, cost, monthOf(type === 'leave' ? p.leaveDate : p.salaryEffectiveDate));
|
||
}
|
||
}
|
||
for (const [key, old] of before) {
|
||
if (now.has(key)) continue;
|
||
push('leave', key, old.name, old.dept, old.group, { pa: sum(old.pa), o: sum(old.o) }, zero, null);
|
||
}
|
||
const order = { new: 0, leave: 1, cost: 2, role: 3, transfer: 4 };
|
||
return list.sort((a, b) => order[a.type] - order[b.type] || a.dept.localeCompare(b.dept, 'zh-Hant'));
|
||
}
|
||
|
||
// 實際 CODA 依調動月份拆分:生效月份之前算原部門/組,之後算新部門/組。
|
||
// splits:[{ key, from: { dept, group }, month }]。只拆在職月份,薪資與設定不變。
|
||
export function splitTransfers(people, splits) {
|
||
if (!splits?.length) return people;
|
||
const byKey = new Map(splits.map(s => [s.key, s]));
|
||
const clip = (p, first, last) => {
|
||
const out = { ...p };
|
||
for (const [a, b] of [['h1Start', 'h1End'], ['h2Start', 'h2End']]) {
|
||
if (out[a] === '' || out[b] === '' || out[a] === undefined || out[b] === undefined) continue;
|
||
const start = Math.max(Number(out[a]), first);
|
||
const end = Math.min(Number(out[b]), last);
|
||
if (start > end) { out[a] = ''; out[b] = ''; } else { out[a] = start; out[b] = end; }
|
||
}
|
||
return out;
|
||
};
|
||
const result = [];
|
||
for (const p of people) {
|
||
const split = byKey.get(personKey(p));
|
||
if (!split || split.month <= 1 || split.month > 12) { result.push(p); continue; }
|
||
result.push({ ...clip(p, 1, split.month - 1), dept: split.from.dept, group: split.from.group, transferSplit: 'before', transferMonth: split.month, row: `${p.row}-before` });
|
||
result.push({ ...clip(p, split.month, 12), transferSplit: 'after', transferMonth: split.month });
|
||
}
|
||
return result;
|
||
}
|