Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
This commit was merged in pull request #38.
This commit is contained in:
@@ -1,11 +1,14 @@
|
||||
// 預排異動(第一部分:預計離職、預計新進)。存在 COST_MODEL_DATA_DIR/planned-changes.json(不進 Git),
|
||||
// 預排異動(預計離職、預計新進、預計轉調)。存在 COST_MODEL_DATA_DIR/planned-changes.json(不進 Git),
|
||||
// 只有最高管理者能看、能改。HR 還沒同步之前,先把已知的離職、新進排進試算,定錨時就會照這份算。
|
||||
// - 預計離職:最後工作月份。在職月份以「HR 的在職期間」和「預排」較短的為準;HR 一有離職日就以 HR 為準。
|
||||
// - 預計新進:先用一個名稱(不一定是真名)、部門、組、職能、預估薪資、開始月份加進名單。
|
||||
// - 預計轉調:生效月份起算新部門/組。生效月份在報表年度中間就按月拆成兩段(前段原單位、後段新單位),
|
||||
// 在報表年度之前就整年算新單位,在之後則先不套用。目標部門可以是 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])$/;
|
||||
@@ -48,13 +51,24 @@ export function normalizePlans(input = {}) {
|
||||
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 REASONS = ['hr_left', 'hr_leave_date', 'hr_joined', 'expired', 'manual'];
|
||||
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);
|
||||
transfers.push({ employeeNumber, toDept, toGroup: text(item.toGroup), fromDept: text(item.fromDept), effectiveMonth,
|
||||
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'].includes(entry.kind) || !REASONS.includes(entry.reason)) return [];
|
||||
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, history };
|
||||
return { departures, hires, transfers, history };
|
||||
}
|
||||
|
||||
const addMonths = (month, n) => {
|
||||
@@ -107,13 +121,26 @@ export function reconcilePlans(plans, people, now = new Date()) {
|
||||
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 arrived = Boolean(person) && String(person.dept || '').trim() === plan.toDept
|
||||
&& (!plan.toGroup || String(person.group || '').trim() === plan.toGroup);
|
||||
const reason = !person ? 'hr_left' : arrived ? 'hr_transferred'
|
||||
: 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, history: [...(plans.history || []), ...removed].slice(-100) }, 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)) return people;
|
||||
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;
|
||||
@@ -131,7 +158,20 @@ export function applyPlans(people, plans, { year, fullYearDefault = false } = {}
|
||||
}, { 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 });
|
||||
}
|
||||
return out;
|
||||
// 預計轉調:生效月份在報表年度之後先不套用;在之前就整年算新單位;年度中間則按月拆成兩段。
|
||||
if (!plans.transfers?.length) return out;
|
||||
const moving = new Map(plans.transfers.map(plan => [String(plan.employeeNumber), plan]));
|
||||
const splits = [];
|
||||
const moved = out.map((person) => {
|
||||
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 });
|
||||
return { ...person, dept: plan.toDept, group: plan.toGroup, plannedTransfer: plan.effectiveMonth };
|
||||
});
|
||||
return splitTransfers(moved, splits);
|
||||
}
|
||||
|
||||
// 每一筆預排目前的狀態(給你看:等待中/HR 已完成/過期未完成)。
|
||||
@@ -146,8 +186,19 @@ export function planStatus(plans, people, now = new Date()) {
|
||||
});
|
||||
const hires = (plans.hires || []).map((plan) => ({ ...plan, status: thisMonth > plan.startMonth ? 'overdue' : 'pending',
|
||||
autoRemoveAfter: addMonths(plan.startMonth, GRACE_MONTHS) }));
|
||||
return { departures, hires, history: [...(plans.history || [])].reverse().slice(0, 30),
|
||||
overdue: [...departures, ...hires].filter(p => p.status === 'overdue').length };
|
||||
// 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 status = conflict ? 'conflict' : thisMonth > plan.effectiveMonth ? 'overdue' : 'pending';
|
||||
return { ...plan, name: person?.name || '', dept: current, group: person?.group || '', status,
|
||||
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 };
|
||||
}
|
||||
|
||||
export function createPlanStore(source) {
|
||||
@@ -157,7 +208,7 @@ export function createPlanStore(source) {
|
||||
return {
|
||||
async load() {
|
||||
if (state) return state;
|
||||
state = { departures: [], hires: [], history: [] };
|
||||
state = { departures: [], hires: [], transfers: [], history: [] };
|
||||
const text = file ? file.read() : null;
|
||||
if (text !== null) state = normalizePlans(JSON.parse(text));
|
||||
return state;
|
||||
|
||||
@@ -152,7 +152,7 @@ async function loadBoardInput(session, options = {}) {
|
||||
}
|
||||
if (options.plans === false) return board;
|
||||
const plans = await planStore.load();
|
||||
if (!plans.departures.length && !plans.hires.length) return board;
|
||||
if (!plans.departures.length && !plans.hires.length && !plans.transfers.length) return board;
|
||||
const year = Number(board.payload.reportYear || board.payload.globalParams?.reportYear || await getCurrentYear());
|
||||
return { payload: { ...board.payload, baseData: applyPlans(board.payload.baseData, plans, { year, fullYearDefault: year > FIRST_YEAR }) } };
|
||||
}
|
||||
|
||||
+80
-2
@@ -12,7 +12,7 @@ const people = [
|
||||
const hire = { id: 'h1', name: '動畫師(3 月)', dept: '動畫部', group: 'AA1', role: 'A - 藝術家', salaryType: 'monthly', amount: 45000, startMonth: '2027-03' };
|
||||
|
||||
test('normalizePlans rejects bad input and keeps good input', () => {
|
||||
assert.deepEqual(normalizePlans({}), { departures: [], hires: [], history: [] });
|
||||
assert.deepEqual(normalizePlans({}), { departures: [], hires: [], transfers: [], history: [] });
|
||||
assert.throws(() => normalizePlans({ departures: [{ employeeNumber: '1001', lastMonth: '2027-13' }] }));
|
||||
assert.throws(() => normalizePlans({ departures: [{ employeeNumber: '1001', lastMonth: '2027-02' }, { employeeNumber: '1001', lastMonth: '2027-03' }] }));
|
||||
assert.throws(() => normalizePlans({ hires: [{ ...hire, role: 'O - 外包' }] }));
|
||||
@@ -93,10 +93,88 @@ test('plan store saves to a private file and reloads', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'plans-'));
|
||||
const path = join(dir, 'planned-changes.json');
|
||||
const store = createPlanStore(path);
|
||||
assert.deepEqual(await store.load(), { departures: [], hires: [], history: [] });
|
||||
assert.deepEqual(await store.load(), { departures: [], hires: [], transfers: [], history: [] });
|
||||
await store.save({ hires: [hire] });
|
||||
assert.equal(JSON.parse(await readFile(path, 'utf8')).hires[0].id, 'h1');
|
||||
assert.equal((await createPlanStore(path).load()).hires.length, 1);
|
||||
await assert.rejects(store.save({ hires: [{ ...hire, amount: -1 }] }));
|
||||
assert.equal((await store.load()).hires.length, 1);
|
||||
});
|
||||
|
||||
// ---- 預計轉調 ----
|
||||
const transfer = { employeeNumber: '1001', toDept: '業務部', effectiveMonth: '2027-01', fromDept: '動畫部' };
|
||||
|
||||
test('預計轉調:欄位不齊、同一人重複都不收', () => {
|
||||
assert.equal(normalizePlans({ transfers: [transfer] }).transfers.length, 1);
|
||||
assert.equal(normalizePlans({}).transfers.length, 0);
|
||||
assert.throws(() => normalizePlans({ transfers: [{ ...transfer, toDept: '' }] }), RangeError);
|
||||
assert.throws(() => normalizePlans({ transfers: [{ ...transfer, effectiveMonth: '2027-13' }] }), RangeError);
|
||||
assert.throws(() => normalizePlans({ transfers: [transfer, { ...transfer, toDept: '前製部' }] }), RangeError);
|
||||
});
|
||||
|
||||
test('一月生效的轉調:整年算新部門,不拆成兩段', () => {
|
||||
const out = applyPlans(people, normalizePlans({ transfers: [transfer] }), { year: 2027 });
|
||||
assert.equal(out.length, people.length);
|
||||
const person = out.find(p => p.employeeNumber === '1001');
|
||||
assert.equal(person.dept, '業務部');
|
||||
assert.equal(person.plannedTransfer, '2027-01');
|
||||
assert.equal(person.h1Start, 1);
|
||||
assert.equal(person.h2End, 12);
|
||||
assert.equal(out.find(p => p.employeeNumber === '1002').dept, '動畫部');
|
||||
});
|
||||
|
||||
test('年度中間生效的轉調:拆成前段原部門、後段新部門,月份不重疊', () => {
|
||||
const plans = normalizePlans({ transfers: [{ ...transfer, toDept: '業務部', toGroup: '業務組', effectiveMonth: '2027-07' }] });
|
||||
const out = applyPlans(people, plans, { year: 2027 });
|
||||
const rows = out.filter(p => p.employeeNumber === '1001');
|
||||
assert.equal(rows.length, 2);
|
||||
const before = rows.find(p => p.transferSplit === 'before');
|
||||
const after = rows.find(p => p.transferSplit === 'after');
|
||||
assert.equal(before.dept, '動畫部');
|
||||
assert.deepEqual([before.h1Start, before.h1End, before.h2Start, before.h2End], [1, 6, '', '']);
|
||||
assert.equal(after.dept, '業務部');
|
||||
assert.equal(after.group, '業務組');
|
||||
assert.deepEqual([after.h1Start, after.h1End, after.h2Start, after.h2End], ['', '', 7, 12]);
|
||||
});
|
||||
|
||||
test('生效月份在報表年度之後先不套用,在之前則整年算新部門', () => {
|
||||
const later = applyPlans(people, normalizePlans({ transfers: [{ ...transfer, effectiveMonth: '2028-03' }] }), { year: 2027 });
|
||||
assert.equal(later.find(p => p.employeeNumber === '1001').dept, '動畫部');
|
||||
const earlier = applyPlans(people, normalizePlans({ transfers: [{ ...transfer, effectiveMonth: '2026-09' }] }), { year: 2027 });
|
||||
const rows = earlier.filter(p => p.employeeNumber === '1001');
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(rows[0].dept, '業務部');
|
||||
});
|
||||
|
||||
test('HR 同步到目標部門後自動移除,紀錄留在 history', () => {
|
||||
const plans = normalizePlans({ transfers: [transfer] });
|
||||
const waiting = reconcilePlans(plans, people, new Date('2027-01-15T00:00:00Z'));
|
||||
assert.equal(waiting.removed.length, 0);
|
||||
const arrived = people.map(p => (p.employeeNumber === '1001' ? { ...p, dept: '業務部' } : p));
|
||||
const done = reconcilePlans(plans, arrived, new Date('2027-01-15T00:00:00Z'));
|
||||
assert.equal(done.plans.transfers.length, 0);
|
||||
assert.equal(done.removed[0].kind, 'transfer');
|
||||
assert.equal(done.removed[0].reason, 'hr_transferred');
|
||||
assert.equal(done.plans.history.at(-1).reason, 'hr_transferred');
|
||||
});
|
||||
|
||||
test('有指定組別時,組也要對上才算完成;過了寬限期會自動移除', () => {
|
||||
const plans = normalizePlans({ transfers: [{ ...transfer, toGroup: '業務組' }] });
|
||||
const deptOnly = people.map(p => (p.employeeNumber === '1001' ? { ...p, dept: '業務部', group: '別組' } : p));
|
||||
assert.equal(reconcilePlans(plans, deptOnly, new Date('2027-01-15T00:00:00Z')).removed.length, 0);
|
||||
const late = reconcilePlans(plans, people, new Date('2027-03-15T00:00:00Z'));
|
||||
assert.equal(late.removed[0].reason, 'expired');
|
||||
assert.equal(late.plans.transfers.length, 0);
|
||||
});
|
||||
|
||||
test('HR 把人調到別的地方=衝突,不自動移除,狀態標成 conflict', () => {
|
||||
const plans = normalizePlans({ transfers: [transfer] });
|
||||
const elsewhere = people.map(p => (p.employeeNumber === '1001' ? { ...p, dept: '視效部' } : p));
|
||||
const kept = reconcilePlans(plans, elsewhere, new Date('2027-01-15T00:00:00Z'));
|
||||
assert.equal(kept.plans.transfers.length, 1);
|
||||
const status = planStatus(kept.plans, elsewhere, new Date('2027-01-15T00:00:00Z'));
|
||||
assert.equal(status.transfers[0].status, 'conflict');
|
||||
assert.equal(status.transfers[0].dept, '視效部');
|
||||
assert.equal(status.conflicts, 1);
|
||||
assert.equal(planStatus(plans, people, new Date('2027-01-15T00:00:00Z')).transfers[0].status, 'pending');
|
||||
});
|
||||
|
||||
@@ -478,7 +478,7 @@ test('planned hires saved in 預排異動 appear on the board and persist in COS
|
||||
await waitFor(`${base}/api/health`);
|
||||
const before = (await (await fetch(`${base}/api/bootstrap`)).json()).baseData.length;
|
||||
const empty = await (await fetch(`${base}/api/plans`)).json();
|
||||
assert.deepEqual(empty.plans, { departures: [], hires: [], history: [] });
|
||||
assert.deepEqual(empty.plans, { departures: [], hires: [], transfers: [], history: [] });
|
||||
const bad = await fetch(`${base}/api/plans`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ hires: [{ id: 'x' }] }) });
|
||||
assert.equal(bad.status, 400);
|
||||
const hire = { id: 'h1', name: '預排動畫師', dept: '動畫部', role: 'A - 藝術家', salaryType: 'monthly', amount: 45000, startMonth: '2027-03' };
|
||||
|
||||
Reference in New Issue
Block a user