Contractors are not in HR. Store them in COST_MODEL_DATA_DIR (contractors.json, never in Git) behind a PUT /api/cost-model/contractors endpoint with server-side normalization, and save automatically from the board whenever the contractor list changes. Production no longer shows the synthetic seed contractors. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
This commit is contained in:
+1
-1
@@ -7,7 +7,7 @@ ENV NODE_ENV=production \
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --chown=node:node package.json server.js access.js hr-sync.js hr-org.js cost-model.js index.html hr.html 2022_Moonshine_Logo_MS_logo_w_EN.png ./
|
||||
COPY --chown=node:node package.json server.js access.js hr-sync.js hr-org.js cost-model.js contractor-store.js index.html hr.html 2022_Moonshine_Logo_MS_logo_w_EN.png ./
|
||||
COPY --chown=node:node seed ./seed
|
||||
RUN mkdir -p /app/data && chown node:node /app/data
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// Regular contractors are not in HR. They are maintained by hand on the board and
|
||||
// persisted next to the HR overrides (COST_MODEL_DATA_DIR), never in Git.
|
||||
export const CONTRACTOR_ROLE = 'O - 外包';
|
||||
export const MAX_CONTRACTORS = 500;
|
||||
|
||||
function text(value, max = 80) {
|
||||
return typeof value === 'string' ? value.trim().slice(0, max) : '';
|
||||
}
|
||||
|
||||
function month(value, minimum, maximum) {
|
||||
const number = Number(value);
|
||||
return Number.isInteger(number) && number >= minimum && number <= maximum ? number : '';
|
||||
}
|
||||
|
||||
export function normalizeContractor(input = {}, index = 0) {
|
||||
const name = text(input.name);
|
||||
if (!name) return null;
|
||||
const dayrate = Number(input.dayrate);
|
||||
const workRate = Number(input.workRateUsed);
|
||||
const row = /^[a-zA-Z0-9_-]{1,40}$/.test(String(input.row ?? '')) ? String(input.row) : `contractor-${index + 1}`;
|
||||
return {
|
||||
row,
|
||||
name,
|
||||
title: text(input.title),
|
||||
company: text(input.company) || '外包',
|
||||
dept: text(input.dept),
|
||||
group: text(input.group),
|
||||
role: CONTRACTOR_ROLE,
|
||||
isManager: false,
|
||||
salary: '',
|
||||
dayrate: Number.isFinite(dayrate) && dayrate >= 0 ? String(Math.round(dayrate)) : '0',
|
||||
h1Start: month(input.h1Start, 1, 6),
|
||||
h1End: month(input.h1End, 1, 6),
|
||||
h2Start: month(input.h2Start, 7, 12),
|
||||
h2End: month(input.h2End, 7, 12),
|
||||
workRateUsed: Number.isFinite(workRate) && workRate > 0 && workRate <= 10 ? workRate : 1.5,
|
||||
source: 'contractor-store',
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeContractors(list) {
|
||||
if (!Array.isArray(list)) throw new TypeError('contractors must be an array');
|
||||
if (list.length > MAX_CONTRACTORS) throw new RangeError('too many contractors');
|
||||
const seen = new Set();
|
||||
return list.map((item, index) => normalizeContractor(item, index)).filter(Boolean).map((item, index) => {
|
||||
// Rows must be unique so the board can address each record.
|
||||
if (seen.has(item.row)) item.row = `contractor-${index + 1}-${seen.size}`;
|
||||
seen.add(item.row);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
+40
-2
@@ -4724,7 +4724,7 @@
|
||||
const label = category === 'contractors' ? '常態型外包' : '試算人員';
|
||||
document.getElementById('personnel-view-title').innerText = `${label}(${dept === 'all' ? '全部門' : dept})`;
|
||||
document.getElementById('personnel-source-note').textContent = category === 'contractors'
|
||||
? '常態型外包目前沿用既有試算名單,獨立維護日薪、合約月份與部門/組別;尚未由 HR Sync 提供。'
|
||||
? '常態型外包不在 HR 系統內,在此獨立維護日薪、合約月份與部門/組別;新增、修改、刪除會自動儲存在本站。'
|
||||
: '2027 HR 試算名單。姓名、職稱、部門/組別與薪資來自 HR;P/A、管理職及未辨識部/組可在此補齊。未完成 P/A 的人會列出,但不納入正式總額。';
|
||||
document.getElementById('personnel-add-button').textContent = `+ 新增${label}`;
|
||||
document.getElementById('personnel-search').value = '';
|
||||
@@ -5318,7 +5318,44 @@
|
||||
if (chevron) chevron.style.transform = isOpen ? 'rotate(0deg)' : 'rotate(180deg)';
|
||||
}
|
||||
|
||||
// --- Regular contractors are saved on the server (not in HR, not in Git) ---
|
||||
let contractorSignature = null;
|
||||
let contractorSaveTimer = null;
|
||||
|
||||
function contractorPayload() {
|
||||
return baseData.filter(p => (p.role || '').startsWith('O')).map(p => ({
|
||||
row: p.row, name: p.name, title: p.title, company: p.company, dept: p.dept, group: p.group,
|
||||
dayrate: p.dayrate, h1Start: p.h1Start, h1End: p.h1End, h2Start: p.h2Start, h2End: p.h2End,
|
||||
workRateUsed: p.workRateUsed,
|
||||
}));
|
||||
}
|
||||
|
||||
function scheduleContractorSave() {
|
||||
if (isSimMode || contractorSignature === null) return;
|
||||
const signature = JSON.stringify(contractorPayload());
|
||||
if (signature === contractorSignature) return;
|
||||
clearTimeout(contractorSaveTimer);
|
||||
contractorSaveTimer = setTimeout(() => saveContractorsToServer(signature), 600);
|
||||
}
|
||||
|
||||
async function saveContractorsToServer(signature) {
|
||||
const banner = document.getElementById('data-source-banner');
|
||||
try {
|
||||
const response = await fetch('/api/cost-model/contractors', {
|
||||
method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ contractors: JSON.parse(signature) }),
|
||||
});
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
contractorSignature = signature;
|
||||
} catch (error) {
|
||||
console.error('Unable to save contractors', error);
|
||||
banner.textContent = '常態型外包儲存失敗,請重新整理後再試;剛才的外包修改尚未保存。';
|
||||
banner.style.color = 'var(--accent-danger)';
|
||||
}
|
||||
}
|
||||
|
||||
function saveAndRefresh() {
|
||||
scheduleContractorSave();
|
||||
globalParams.orgStructure = null; // Force rebuild with correct order and fresh data
|
||||
renderDashboard();
|
||||
renderPersonnel();
|
||||
@@ -5833,10 +5870,11 @@
|
||||
}
|
||||
baseData = payload.baseData;
|
||||
globalParams = payload.globalParams;
|
||||
contractorSignature = JSON.stringify(contractorPayload());
|
||||
const banner = document.getElementById('data-source-banner');
|
||||
if (payload.source === 'hr-sync-2027-planning') {
|
||||
const summary = payload.summary || {};
|
||||
banner.textContent = `2027 HR 試算|已轉入 ${summary.activeEmployees || 0} 位 HR 在職人員;${summary.needsReview || 0} 位待確認 P/A、管理職或薪資,暫不納入正式總額。時薪先按每週 5 天、每天 8 小時計算;H1 預設為 1–6 月。常態型外包 ${summary.legacyContractors || 0} 位沿用既有試算名單。`;
|
||||
banner.textContent = `2027 HR 試算|已轉入 ${summary.activeEmployees || 0} 位 HR 在職人員;${summary.needsReview || 0} 位待確認 P/A、管理職或薪資,暫不納入正式總額。時薪先按每週 5 天、每天 8 小時計算;H1 預設為 1–6 月。常態型外包 ${summary.legacyContractors || 0} 位,在本站手動維護並儲存。`;
|
||||
} else {
|
||||
banner.textContent = '合成資料預覽|姓名、薪資與參數皆為虛構資料;修改只保留在目前頁面工作階段。';
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { canAccess } from './access.js';
|
||||
import { HrError, hrConfig, hrFetch } from './hr-sync.js';
|
||||
import { splitOrganization } from './hr-org.js';
|
||||
import { normalizeOverride, toCostPerson } from './cost-model.js';
|
||||
import { normalizeContractors } from './contractor-store.js';
|
||||
|
||||
const root = fileURLToPath(new URL('.', import.meta.url));
|
||||
const port = Number(process.env.PORT || 8080);
|
||||
@@ -17,6 +18,7 @@ const isProduction = process.env.NODE_ENV === 'production';
|
||||
const demoPath = resolve(root, 'seed/demo.json');
|
||||
const costModelDataDir = process.env.COST_MODEL_DATA_DIR;
|
||||
const costOverridesPath = costModelDataDir ? resolve(costModelDataDir, 'cost-overrides.json') : null;
|
||||
const contractorsPath = costModelDataDir ? resolve(costModelDataDir, 'contractors.json') : null;
|
||||
const oidc = {
|
||||
issuer: process.env.OIDC_ISSUER?.replace(/\/+$/, ''),
|
||||
clientId: process.env.OIDC_CLIENT_ID,
|
||||
@@ -30,6 +32,8 @@ let discoveryCache;
|
||||
let jwksCache;
|
||||
let persistedOverrides;
|
||||
let overrideWrite = Promise.resolve();
|
||||
let persistedContractors;
|
||||
let contractorWrite = Promise.resolve();
|
||||
|
||||
const allowedStaticFiles = new Map([
|
||||
['/2022_Moonshine_Logo_MS_logo_w_EN.png', ['2022_Moonshine_Logo_MS_logo_w_EN.png', 'image/png']],
|
||||
@@ -295,6 +299,37 @@ async function clearCostOverrideField(employeeNumber, field) {
|
||||
await overrideWrite;
|
||||
}
|
||||
|
||||
// Contractors saved on the board live in COST_MODEL_DATA_DIR. Before anything is saved,
|
||||
// local previews show the synthetic seed contractors; production shows none rather than
|
||||
// presenting synthetic people as real ones.
|
||||
async function getContractors(demo) {
|
||||
if (persistedContractors) return persistedContractors;
|
||||
if (contractorsPath) {
|
||||
try {
|
||||
persistedContractors = normalizeContractors(JSON.parse(await readFile(contractorsPath, 'utf8')));
|
||||
return persistedContractors;
|
||||
} catch (error) {
|
||||
if (error?.code !== 'ENOENT') throw error;
|
||||
}
|
||||
}
|
||||
if (isProduction) return [];
|
||||
return normalizeContractors((demo?.baseData || []).filter(person => String(person.role || '').startsWith('O')));
|
||||
}
|
||||
|
||||
async function saveContractors(list) {
|
||||
persistedContractors = normalizeContractors(list);
|
||||
if (!contractorsPath) return persistedContractors;
|
||||
const write = async () => {
|
||||
await mkdir(costModelDataDir, { recursive: true });
|
||||
const temporaryPath = `${contractorsPath}.${process.pid}.tmp`;
|
||||
await writeFile(temporaryPath, JSON.stringify(persistedContractors, null, 2), { mode: 0o600 });
|
||||
await rename(temporaryPath, contractorsPath);
|
||||
};
|
||||
contractorWrite = contractorWrite.then(write, write);
|
||||
await contractorWrite;
|
||||
return persistedContractors;
|
||||
}
|
||||
|
||||
async function getCostModel(session) {
|
||||
if (session.costModelCache?.expiresAt > Date.now()) return session.costModelCache.payload;
|
||||
const [records, organizations, demo] = await Promise.all([
|
||||
@@ -313,11 +348,9 @@ async function getCostModel(session) {
|
||||
...person,
|
||||
...splitOrganization(person, organizations),
|
||||
}, salaryResults[index], overrides.get(person.employeeNumber)));
|
||||
// Regular contractors have no HR counterpart yet. Keep the existing cost-model records
|
||||
// Regular contractors have no HR counterpart. They are maintained on the board and kept
|
||||
// separate from the HR roster so their source is visible in every response.
|
||||
const contractors = demo.baseData
|
||||
.filter(person => String(person.role || '').startsWith('O'))
|
||||
.map(person => ({ ...person, company: person.company || '外包', source: 'legacy-contractor' }));
|
||||
const contractors = await getContractors(demo);
|
||||
const payload = {
|
||||
source: 'hr-sync-2027-planning',
|
||||
reportYear: 2027,
|
||||
@@ -330,17 +363,18 @@ async function getCostModel(session) {
|
||||
needsReview: people.filter(person => !person.calculationReady).length,
|
||||
hourlyEmployees: people.filter(person => person.salaryType === 'hourly').length,
|
||||
legacyContractors: contractors.length,
|
||||
contractorsSaved: Boolean(persistedContractors && contractorsPath),
|
||||
},
|
||||
};
|
||||
session.costModelCache = { payload, expiresAt: Date.now() + 60_000 };
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function readJson(request) {
|
||||
async function readJson(request, limit = 20_000) {
|
||||
let raw = '';
|
||||
for await (const chunk of request) {
|
||||
raw += chunk;
|
||||
if (raw.length > 20_000) throw new HrError('invalid_request', 400);
|
||||
if (raw.length > limit) throw new HrError('invalid_request', 400);
|
||||
}
|
||||
try { return JSON.parse(raw || '{}'); } catch { throw new HrError('invalid_request', 400); }
|
||||
}
|
||||
@@ -350,7 +384,7 @@ const server = createServer(async (request, response) => {
|
||||
|
||||
try {
|
||||
if (request.method === 'GET' && url.pathname === '/api/health') {
|
||||
return sendJson(response, 200, { status: 'ok', release: 'hr-company-filter-v7' });
|
||||
return sendJson(response, 200, { status: 'ok', release: 'contractor-store-v8' });
|
||||
}
|
||||
|
||||
if (request.method === 'GET' && url.pathname === '/api/auth/login') {
|
||||
@@ -477,6 +511,22 @@ const server = createServer(async (request, response) => {
|
||||
return sendJson(response, 200, { ok: true });
|
||||
}
|
||||
|
||||
if (request.method === 'PUT' && url.pathname === '/api/cost-model/contractors') {
|
||||
const session = requireAuth(request, response, true);
|
||||
if (!session) return;
|
||||
if (isProduction && !canAccess(session.claims)) return sendJson(response, 403, { error: 'access_denied' });
|
||||
const body = await readJson(request, 400_000);
|
||||
let saved;
|
||||
try {
|
||||
saved = await saveContractors(body.contractors);
|
||||
} catch (error) {
|
||||
if (error instanceof TypeError || error instanceof RangeError) return sendJson(response, 400, { error: 'invalid_contractors' });
|
||||
throw error;
|
||||
}
|
||||
session.costModelCache = null;
|
||||
return sendJson(response, 200, { ok: true, count: saved.length });
|
||||
}
|
||||
|
||||
if (request.method === 'DELETE' && /^\/api\/hr\/cost-model\/employees\/[^/]+\/overrides\/[^/]+$/.test(url.pathname)) {
|
||||
const session = requireAuth(request, response, true);
|
||||
if (!session) return;
|
||||
@@ -502,7 +552,8 @@ const server = createServer(async (request, response) => {
|
||||
return sendJson(response, 200, await getCostModel(session));
|
||||
}
|
||||
const demo = JSON.parse(await readFile(demoPath, 'utf8'));
|
||||
return sendJson(response, 200, demo);
|
||||
const internal = demo.baseData.filter(person => !String(person.role || '').startsWith('O'));
|
||||
return sendJson(response, 200, { ...demo, baseData: [...internal, ...await getContractors(demo)] });
|
||||
}
|
||||
|
||||
if (request.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html' || url.pathname === '/hr.html')) {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { MAX_CONTRACTORS, normalizeContractor, normalizeContractors } from '../contractor-store.js';
|
||||
|
||||
test('contractor records keep only the fields the board needs', () => {
|
||||
const record = normalizeContractor({
|
||||
row: 39, name: ' 測試外包 ', title: '特約藝術家', dept: '視效部', group: '合成組', role: 'P - 製作',
|
||||
dayrate: '3000.4', h1Start: 1, h1End: 6, h2Start: 7, h2End: 12, workRateUsed: 1.5, totalCost: 999, token: 'x',
|
||||
});
|
||||
assert.equal(record.name, '測試外包');
|
||||
assert.equal(record.role, 'O - 外包');
|
||||
assert.equal(record.dayrate, '3000');
|
||||
assert.equal(record.row, '39');
|
||||
assert.equal(record.company, '外包');
|
||||
assert.equal(record.totalCost, undefined);
|
||||
assert.equal(record.token, undefined);
|
||||
});
|
||||
|
||||
test('invalid months, rates and nameless rows are rejected or reset', () => {
|
||||
const [record] = normalizeContractors([
|
||||
{ name: 'A', dayrate: -5, h1Start: 9, h2End: 3, workRateUsed: 50 },
|
||||
{ name: ' ' },
|
||||
]);
|
||||
assert.equal(record.dayrate, '0');
|
||||
assert.equal(record.h1Start, '');
|
||||
assert.equal(record.h2End, '');
|
||||
assert.equal(record.workRateUsed, 1.5);
|
||||
assert.throws(() => normalizeContractors('nope'), TypeError);
|
||||
assert.throws(() => normalizeContractors(Array.from({ length: MAX_CONTRACTORS + 1 }, () => ({ name: 'x' }))), RangeError);
|
||||
});
|
||||
|
||||
test('duplicate rows are made unique', () => {
|
||||
const rows = normalizeContractors([{ row: 'a', name: 'A' }, { row: 'a', name: 'B' }]).map(item => item.row);
|
||||
assert.equal(new Set(rows).size, 2);
|
||||
});
|
||||
@@ -234,3 +234,33 @@ test('a signed-in session is revoked by logout and cannot be replayed', async (t
|
||||
const returnedPage = await fetch(`${base}/logged-out`, { headers: { cookie: returnedCookie } });
|
||||
assert.match(await returnedPage.text(), /已從 MoonShine 公司帳號登出/);
|
||||
});
|
||||
|
||||
test('contractors saved on the board persist across restarts in COST_MODEL_DATA_DIR', async (t) => {
|
||||
const dataDir = await mkdtemp(join(tmpdir(), 'pm-board-contractors-'));
|
||||
t.after(() => rm(dataDir, { recursive: true, force: true }));
|
||||
const env = { PORT: '18089', HOST: '127.0.0.1', NODE_ENV: 'development', COST_MODEL_DATA_DIR: dataDir };
|
||||
let child = start(env);
|
||||
await waitFor('http://127.0.0.1:18089/api/health');
|
||||
const saved = await fetch('http://127.0.0.1:18089/api/cost-model/contractors', {
|
||||
method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ contractors: [{ name: '測試外包', dept: '視效部', group: '合成組', dayrate: 3000, h1Start: 1, h1End: 6 }] }),
|
||||
});
|
||||
assert.equal(saved.status, 200);
|
||||
assert.equal((await saved.json()).count, 1);
|
||||
const invalid = await fetch('http://127.0.0.1:18089/api/cost-model/contractors', {
|
||||
method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ contractors: 'x' }),
|
||||
});
|
||||
assert.equal(invalid.status, 400);
|
||||
child.kill();
|
||||
await new Promise(resolve => child.once('exit', resolve));
|
||||
|
||||
child = start(env);
|
||||
t.after(() => child.kill());
|
||||
await waitFor('http://127.0.0.1:18089/api/health');
|
||||
const bootstrap = await (await fetch('http://127.0.0.1:18089/api/bootstrap')).json();
|
||||
const contractors = bootstrap.baseData.filter(person => person.role.startsWith('O'));
|
||||
assert.deepEqual(contractors.map(person => person.name), ['測試外包']);
|
||||
assert.equal(contractors[0].dayrate, '3000');
|
||||
const file = JSON.parse(await readFile(join(dataDir, 'contractors.json'), 'utf8'));
|
||||
assert.equal(file.length, 1);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user