Files
leadboard/plans.js

270 lines
16 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 預排異動(預計離職、預計新進、預計轉調)。存在 COST_MODEL_DATA_DIR/planned-changes.json(不進 Git),
// 只有最高管理者能看、能改。HR 還沒同步之前,先把已知的離職、新進排進試算,定錨時就會照這份算。
// - 預計離職:最後工作月份。在職月份以「HR 的在職期間」和「預排」較短的為準;HR 一有離職日就以 HR 為準。
// - 預計新進:先用一個名稱(不一定是真名)、部門、組、職能、預估薪資、開始月份加進名單。
// - 預計轉調:生效月份起算新部門/組。生效月份在報表年度中間就按月拆成兩段(前段原單位、後段新單位),
// 在報表年度之前就整年算新單位,在之後則先不套用。目標部門可以是 HR 還沒有的新部門。
// 主管職:預設轉調後卸任(keepManager 可保留);原單位可以指定接任者,模擬時就當成主管。
// 這只影響數字與模擬,不影響看板權限(權限一律以 HR 的主管關係為準)。
// 部長在 /my 看到的是套用預排之後的數字(不顯示原因);所有計算都用同一份資料,定錨的最高點才不會被墊高。
// 自動核對(reconcilePlans):HR 名單一出現結果(離職的人不在名單上或有離職日、新人出現在名單上)就自動移除那一筆;
// 時間過了 HR 還沒改,寬限 1 個月後也自動移除。移除紀錄留在 history 給最高管理者看。
import { bindFile } from './storage.js';
import { personKey, splitTransfers } from './anchor-calc.js';
import { boundMonths, toCostPerson } from './cost-model.js';
const MONTH = /^(\d{4})-(0[1-9]|1[0-2])$/;
const ROLES = ['A - 藝術家', 'P - 製作', 'G - 營運支援'];
const MAX = 300;
const text = (value, max = 80) => (typeof value === 'string' ? value.replace(/\s+/g, ' ').trim().slice(0, max) : '');
const monthOf = (value) => (MONTH.test(text(value)) ? text(value) : '');
export function normalizePlans(input = {}) {
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new TypeError('plans must be an object');
const array = (value) => {
if (value === undefined) return [];
if (!Array.isArray(value)) throw new TypeError('plans list must be an array');
return value.slice(0, MAX);
};
const seen = new Set();
const departures = [];
for (const item of array(input.departures)) {
const employeeNumber = text(String(item?.employeeNumber ?? ''), 40);
const lastMonth = monthOf(item?.lastMonth);
if (!/^[A-Za-z0-9_-]{1,40}$/.test(employeeNumber) || !lastMonth || seen.has(employeeNumber)) throw new RangeError('invalid departure');
seen.add(employeeNumber);
departures.push({ employeeNumber, lastMonth, note: text(item.note, 200), createdAt: text(item.createdAt, 40) || new Date().toISOString() });
}
const ids = new Set();
const hires = [];
for (const item of array(input.hires)) {
const id = text(String(item?.id ?? ''), 40);
const name = text(item?.name, 40);
const dept = text(item?.dept);
const startMonth = monthOf(item?.startMonth);
const endMonth = item?.endMonth ? monthOf(item.endMonth) : '';
const amount = Number(item?.amount);
const salaryType = item?.salaryType === 'hourly' ? 'hourly' : 'monthly';
if (!/^[A-Za-z0-9_-]{1,40}$/.test(id) || ids.has(id) || !name || !dept || !startMonth || !ROLES.includes(item?.role)
|| !(Number.isFinite(amount) && amount > 0 && amount < 10_000_000) || (item?.endMonth && (!endMonth || endMonth < startMonth))) {
throw new RangeError('invalid hire');
}
ids.add(id);
hires.push({ id, name, title: text(item.title), dept, group: text(item.group), role: item.role, salaryType, amount: Math.round(amount),
startMonth, endMonth, note: text(item.note, 200), createdAt: text(item.createdAt, 40) || new Date().toISOString() });
}
const moved = new Set();
const transfers = [];
for (const item of array(input.transfers)) {
const employeeNumber = text(String(item?.employeeNumber ?? ''), 40);
const toDept = text(item?.toDept);
const effectiveMonth = monthOf(item?.effectiveMonth);
if (!/^[A-Za-z0-9_-]{1,40}$/.test(employeeNumber) || !toDept || !effectiveMonth || moved.has(employeeNumber)) throw new RangeError('invalid transfer');
moved.add(employeeNumber);
const successor = text(String(item?.successorEmployeeNumber ?? ''), 40);
if (successor && (!/^[A-Za-z0-9_-]{1,40}$/.test(successor) || successor === employeeNumber)) throw new RangeError('invalid transfer');
transfers.push({ employeeNumber, toDept, toGroup: text(item.toGroup), fromDept: text(item.fromDept), effectiveMonth,
keepManager: item?.keepManager === true, successorEmployeeNumber: successor,
note: text(item.note, 200), createdAt: text(item.createdAt, 40) || new Date().toISOString() });
}
const REASONS = ['hr_left', 'hr_leave_date', 'hr_joined', 'hr_transferred', 'expired', 'manual'];
const history = (Array.isArray(input.history) ? input.history : []).slice(-100).flatMap((entry) => {
if (!entry || !['departure', 'hire', 'transfer'].includes(entry.kind) || !REASONS.includes(entry.reason)) return [];
return [{ kind: entry.kind, reason: entry.reason, label: text(entry.label, 80), month: monthOf(entry.month),
matched: text(entry.matched, 80), at: text(entry.at, 40) }];
});
return { departures, hires, transfers, history };
}
const addMonths = (month, n) => {
const [y, m] = month.split('-').map(Number);
const total = y * 12 + (m - 1) + n;
return `${Math.floor(total / 12)}-${String((total % 12) + 1).padStart(2, '0')}`;
};
const monthNow = (now) => `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
export const GRACE_MONTHS = 1;
// 新人比對:同名,或同部門、HR 到職月份在預排開始月份前後 1 個月內。一個 HR 的人只配一筆預排。
function matchHires(hires, hrPeople) {
const used = new Set();
const matches = new Map();
const pick = (hire, test) => {
const person = hrPeople.find(p => !used.has(String(p.employeeNumber)) && test(p));
if (person) { used.add(String(person.employeeNumber)); matches.set(hire.id, person); }
};
for (const hire of hires) pick(hire, p => p.name === hire.name && (!p.dept || p.dept === hire.dept));
for (const hire of hires) {
if (matches.has(hire.id)) continue;
// 預排建立之前就到職的人不算(他們本來就在名單上)。
const created = monthOf(String(hire.createdAt || '').slice(0, 7));
const lo = [addMonths(hire.startMonth, -1), created].filter(Boolean).sort().pop();
const hi = addMonths(hire.startMonth, 1);
pick(hire, p => p.dept === hire.dept && p.hireDate && String(p.hireDate).slice(0, 7) >= lo && String(p.hireDate).slice(0, 7) <= hi);
}
return matches;
}
// 主管職是否已經照預排處理:本人的主管身分符合預排,指定的接任者在 HR 也已經是主管。
function managerSettled(plan, person, hr) {
if (Boolean(person?.isManager) !== Boolean(plan.keepManager)) return false;
if (!plan.successorEmployeeNumber) return true;
return Boolean(hr.get(String(plan.successorEmployeeNumber))?.isManager);
}
// 拿目前 HR 名單核對預排,回傳要留下的預排和這次自動移除的紀錄。HR 名單是空的(例如 HR 暫時連不上)就不動。
export function reconcilePlans(plans, people, now = new Date()) {
const hrPeople = (people || []).filter(p => p.source === 'hr-sync');
if (!hrPeople.length) return { plans, removed: [] };
const thisMonth = monthNow(now);
const at = now.toISOString();
const hr = new Map(hrPeople.map(p => [String(p.employeeNumber), p]));
const removed = [];
const departures = (plans.departures || []).filter((plan) => {
const person = hr.get(plan.employeeNumber);
const reason = !person ? 'hr_left' : person.leaveDate ? 'hr_leave_date'
: thisMonth > addMonths(plan.lastMonth, GRACE_MONTHS) ? 'expired' : null;
if (reason) removed.push({ kind: 'departure', reason, label: person?.name || plan.employeeNumber, month: plan.lastMonth, matched: '', at });
return !reason;
});
const matches = matchHires(plans.hires || [], hrPeople);
const hires = (plans.hires || []).filter((plan) => {
const person = matches.get(plan.id);
const reason = person ? 'hr_joined' : thisMonth > addMonths(plan.startMonth, GRACE_MONTHS) ? 'expired' : null;
if (reason) removed.push({ kind: 'hire', reason, label: plan.name, month: plan.startMonth, matched: person ? `${person.name}(${person.employeeNumber})` : '', at });
return !reason;
});
// 轉調:HR 的部門(有填組就連組)變成目標單位就算完成;人不在名單上或過了寬限期也移除。
const transfers = (plans.transfers || []).filter((plan) => {
const person = hr.get(plan.employeeNumber);
const movedDept = Boolean(person) && String(person.dept || '').trim() === plan.toDept
&& (!plan.toGroup || String(person.group || '').trim() === plan.toGroup);
const arrived = movedDept && managerSettled(plan, person, hr);
// 部門對了但主管還沒處理:留著提醒,不讓它過期被默默移除。
const reason = !person ? 'hr_left' : arrived ? 'hr_transferred'
: movedDept ? null
: thisMonth > addMonths(plan.effectiveMonth, GRACE_MONTHS) ? 'expired' : null;
if (reason) {
removed.push({ kind: 'transfer', reason, label: person?.name || plan.employeeNumber, month: plan.effectiveMonth,
matched: person ? `${person.dept || ''}${person.group ? ' / ' + person.group : ''}` : '', at });
}
return !reason;
});
if (!removed.length) return { plans, removed };
return { plans: { departures, hires, transfers, history: [...(plans.history || []), ...removed].slice(-100) }, removed };
}
// 把預排套到看板名單上(只套在名單層,不改 HR 資料)。
export function applyPlans(people, plans, { year, fullYearDefault = false } = {}) {
if (!plans || (!plans.departures?.length && !plans.hires?.length && !plans.transfers?.length)) return people;
const leaving = new Map((plans.departures || []).map(d => [String(d.employeeNumber), d]));
const out = people.map((person) => {
const plan = person.source === 'hr-sync' ? leaving.get(String(person.employeeNumber)) : null;
if (!plan) return person;
const months = boundMonths({ h1Start: person.h1Start, h1End: person.h1End, h2Start: person.h2Start, h2End: person.h2End }, null, `${plan.lastMonth}-01`, year);
return { ...person, h1Start: months.h1Start, h1End: months.h1End, h2Start: months.h2Start, h2End: months.h2End,
employmentBounded: person.employmentBounded || months.bounded, plannedLeave: plan.lastMonth };
});
for (const hire of plans.hires || []) {
const company = people.find(p => p.dept === hire.dept && p.company)?.company || '';
const person = toCostPerson({
employeeNumber: `PLAN-${hire.id}`, name: hire.name, positionName: hire.title, corporationName: company,
departmentName: hire.dept, groupName: hire.group, hireDate: `${hire.startMonth}-01`,
leaveDate: hire.endMonth ? `${hire.endMonth}-01` : '', status: 'PLANNED', supervisorOf: [],
}, { amount: hire.amount, salaryType: hire.salaryType }, { role: hire.role }, { year, fullYearDefault });
out.push({ ...person, row: `PLAN-${hire.id}`, source: 'planned', plannedHire: hire.startMonth, planId: hire.id });
}
// 預計轉調:生效月份在報表年度之後先不套用;在之前就整年算新單位;年度中間則按月拆成兩段。
if (!plans.transfers?.length) return out;
const moving = new Map(plans.transfers.map(plan => [String(plan.employeeNumber), plan]));
const splits = [];
// 接任者:原單位由誰接主管(簡化為整年都算主管,一月生效的轉調本來就一致)。
const successors = new Map(plans.transfers.filter(plan => plan.successorEmployeeNumber)
.map(plan => [String(plan.successorEmployeeNumber), plan]));
const managerBefore = new Map();
const moved = out.map((person) => {
if (person.source === 'hr-sync' && successors.has(String(person.employeeNumber))) {
return { ...person, isManager: true, plannedManager: true };
}
const plan = person.source === 'hr-sync' ? moving.get(String(person.employeeNumber)) : null;
if (!plan) return person;
const [planYear, planMonth] = plan.effectiveMonth.split('-').map(Number);
if (Number.isFinite(year) && planYear > year) return person;
const month = !Number.isFinite(year) || planYear < year ? 1 : planMonth;
if (month > 1) {
splits.push({ key: personKey(person), from: { dept: person.dept, group: person.group }, month });
managerBefore.set(personKey(person), { isManager: person.isManager, supervisorOf: person.supervisorOf });
}
const manager = plan.keepManager
? { isManager: person.isManager, supervisorOf: person.supervisorOf }
: { isManager: false, supervisorOf: [] };
return { ...person, dept: plan.toDept, group: plan.toGroup, plannedTransfer: plan.effectiveMonth, ...manager };
});
// 拆成兩段時,生效月份之前還是原單位的主管。
return splitTransfers(moved, splits).map((person) => {
if (person.transferSplit !== 'before') return person;
const before = managerBefore.get(personKey(person));
return before ? { ...person, ...before } : person;
});
}
// 每一筆預排目前的狀態(給你看:等待中/HR 已完成/過期未完成)。
export function planStatus(plans, people, now = new Date()) {
const thisMonth = monthNow(now);
const hr = new Map(people.filter(p => p.source === 'hr-sync').map(p => [String(p.employeeNumber), p]));
const departures = (plans.departures || []).map((plan) => {
const person = hr.get(plan.employeeNumber);
const status = thisMonth > plan.lastMonth ? 'overdue' : 'pending';
return { ...plan, name: person?.name || '', dept: person?.dept || '', group: person?.group || '', status,
autoRemoveAfter: addMonths(plan.lastMonth, GRACE_MONTHS) };
});
const hires = (plans.hires || []).map((plan) => ({ ...plan, status: thisMonth > plan.startMonth ? 'overdue' : 'pending',
autoRemoveAfter: addMonths(plan.startMonth, GRACE_MONTHS) }));
// HR 把人調到「原單位和目標單位以外」的地方=衝突,留著讓最高管理者自己判斷,不自動移除。
const transfers = (plans.transfers || []).map((plan) => {
const person = hr.get(plan.employeeNumber);
const current = String(person?.dept || '').trim();
const conflict = Boolean(person) && Boolean(plan.fromDept) && Boolean(current)
&& current !== plan.fromDept && current !== plan.toDept;
const movedDept = Boolean(person) && current === plan.toDept
&& (!plan.toGroup || String(person.group || '').trim() === plan.toGroup);
const status = conflict ? 'conflict'
: movedDept && !managerSettled(plan, person, hr) ? 'manager_pending'
: thisMonth > plan.effectiveMonth ? 'overdue' : 'pending';
const successor = plan.successorEmployeeNumber ? hr.get(String(plan.successorEmployeeNumber)) : null;
return { ...plan, name: person?.name || '', dept: current, group: person?.group || '', status,
isManager: Boolean(person?.isManager), leads: (person?.supervisorOf || []).map(unit => unit.deptName).filter(Boolean),
successorName: successor?.name || '', successorIsManager: Boolean(successor?.isManager),
autoRemoveAfter: addMonths(plan.effectiveMonth, GRACE_MONTHS) };
});
return { departures, hires, transfers, history: [...(plans.history || [])].reverse().slice(0, 30),
overdue: [...departures, ...hires, ...transfers].filter(p => p.status === 'overdue').length,
conflicts: transfers.filter(p => p.status === 'conflict').length,
managerPending: transfers.filter(p => p.status === 'manager_pending').length };
}
export function createPlanStore(source) {
const file = bindFile(source);
let state = null;
let queue = Promise.resolve();
return {
async load() {
if (state) return state;
state = { departures: [], hires: [], transfers: [], history: [] };
const text = file ? file.read() : null;
if (text !== null) state = normalizePlans(JSON.parse(text));
return state;
},
save(input) {
let next;
try { next = normalizePlans(input); } catch (error) { return Promise.reject(error); }
const run = queue.then(async () => {
file?.write(JSON.stringify(next, null, 2));
state = next;
return next;
});
queue = run.catch(() => {});
return run;
},
};
}