Files
leadboard/external-api.js
2026-11-23 06:40:49 +00:00

131 lines
7.2 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.
// 對外接口 /api/external/v1/{invoice,coda}(EXTERNAL-API-SPEC.md 第 8 節、AUTHENTIK-HANDOFF.md 第 2 節)。
// - 驗證:Authorization: Bearer <token>,Authentik LeadBoard provider 簽發(iss = API_ISSUER),aud = leadboard-api,scope 含 leadboard:read。
// - 資料只來自定錨:第一次定錨之前一律 503 not_anchored。不含任何個人資料。
import { createPublicKey, verify } from 'node:crypto';
export const API_AUDIENCE = 'leadboard-api';
export const API_SCOPE = 'leadboard:read';
// 簽發者與金鑰(JWKS);與登入用的 OIDC_ISSUER 分開,避免兩邊的設定互相牽動。
export const API_ISSUER = 'https://auth.moonshine-studio.net/application/o/leadboard/';
export const API_JWKS_URI = `${API_ISSUER}jwks/`;
export const CALC_VERSION = 3;
export const CALC_CHANGELOG = Object.freeze([
{ calcVersion: 1, date: '2026-10-28', change: '初版(含夢境現實 CODA 分攤;指標 3 為 P 輕重,依 A:P 成本比)', reason: '對外接口開始提供' },
{ calcVersion: 2, date: '2027-01', change: '發票半年定錨、只增不減;部門調動依生效月份移轉發票', reason: '避免減人降低發票與部門間零和' },
{ calcVersion: 3, date: '2027-01', change: '實際 CODA 與定錨 CODA;實習生 × 1 只進發票;工讀以外包計(日薪=時薪×8);管理職以 HR 組織主管為準', reason: '定錨 CODA 與發票一起半年定錨,實際 CODA 仍即時反映供定價' },
]);
const INVOICE_COMPANY = '夢想創造';
const REALITY_COMPANY = '夢境現實';
const RD_DEPT = '研發部';
export class ApiError extends Error {
constructor(status, code, message) { super(message || code); this.status = status; this.code = code; }
}
const decode = (segment) => JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));
// getKeys(force) 回傳 JWKS;找不到 kid 時強制重抓一次(金鑰輪替)。
export async function verifyApiToken(authorization, { issuer, getKeys, now = Date.now() }) {
const match = /^Bearer\s+([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/.exec(String(authorization || ''));
if (!match) throw new ApiError(401, 'token_required');
const [head, body, signature] = match[1].split('.');
let header; let payload;
try { header = decode(head); payload = decode(body); } catch { throw new ApiError(401, 'invalid_token'); }
if (header.alg !== 'RS256') throw new ApiError(401, 'invalid_token');
let keys = await getKeys(false);
let jwk = keys?.keys?.find(key => key.kid === header.kid && key.kty === 'RSA');
if (!jwk) { keys = await getKeys(true); jwk = keys?.keys?.find(key => key.kid === header.kid && key.kty === 'RSA'); }
if (!jwk) throw new ApiError(401, 'invalid_token');
const valid = verify('RSA-SHA256', Buffer.from(`${head}.${body}`), createPublicKey({ key: jwk, format: 'jwk' }), Buffer.from(signature, 'base64url'));
const audience = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
const expected = `${String(issuer).replace(/\/+$/, '')}/`;
if (!valid || payload.iss !== expected || !audience.includes(API_AUDIENCE)) throw new ApiError(401, 'invalid_token');
if (!payload.exp || payload.exp * 1000 <= now) throw new ApiError(401, 'token_expired');
const scopes = String(payload.scope || '').split(/\s+/);
if (!scopes.includes(API_SCOPE)) throw new ApiError(403, 'insufficient_scope');
return { sub: payload.sub, actorType: payload.actor_type || null, employeeNumber: payload.employee_number || null };
}
// HR 組織代碼:依名稱與層級找。
function codes(organizations) {
const dept = new Map();
const group = new Map();
for (const unit of organizations || []) {
const level = String(unit.levelName || '').trim();
if (['部', '部門'].includes(level)) dept.set(unit.deptName, unit.deptCode);
if (['組', '組別'].includes(level)) group.set(`${unit.upperDeptCode}|${unit.deptName}`, unit.deptCode);
}
return { dept, group };
}
const round = (value) => Math.round(Number(value) || 0);
function anchoredBlock(v, half) {
if (!v) return null;
return {
annual: round(v.value ?? v.annual), h1: round(v.h1), h1Settled: half === 'H2',
h2: half === 'H2' ? round(v.h2) : round((v.value ?? v.annual) - v.h1), h2Provisional: half !== 'H2',
};
}
export function buildExternal(model, anchors, { organizations = [], generatedAt = new Date().toISOString(), opMultiplier = 2 } = {}) {
if (!anchors?.active) throw new ApiError(503, 'not_anchored', '尚未定錨');
const half = anchors.active.half;
const common = {
year: anchors.year,
dataVersion: `v${anchors.active.version || anchors.anchors.length}`,
anchoredAt: anchors.active.at,
calcVersion: CALC_VERSION,
half,
generatedAt,
calcChangelog: CALC_CHANGELOG,
};
const code = codes(organizations);
const companyOf = model.deptCompany || {};
const invoiceDepts = Object.keys(model.allocations?.deptData || {}).filter(d => companyOf[d] === INVOICE_COMPANY);
const departments = invoiceDepts.map(dept => {
const v = anchors.invoice?.[dept] || { anchored: 0, transferNet: 0, peak: 0, annual: 0, h1: 0, h2: null };
return {
company: INVOICE_COMPANY, deptCode: code.dept.get(dept) || null, dept,
anchorAnnual: round(v.anchored + v.transferNet), increase: round(v.peak), annual: round(v.annual),
h1: { target: round(v.h1), settled: half === 'H2' },
h2: { target: round(half === 'H2' ? v.h2 : v.annual - v.h1), provisional: half !== 'H2' },
};
});
const rdCost = model.people
.filter(p => (p.dept || '').trim() === RD_DEPT && !String(p.role || '').startsWith('O') && !p.invoiceCost)
.reduce((sum, p) => sum + (Number(p.realSalaryTotal) || 0), 0) * opMultiplier;
const invoice = {
...common, company: INVOICE_COMPANY,
invoiceTotal: departments.reduce((sum, d) => sum + d.annual, 0),
departments,
rdDeptCost: { company: INVOICE_COMPANY, deptCode: code.dept.get(RD_DEPT) || null, dept: RD_DEPT, cost: round(rdCost) },
};
const deptBlock = (dept, withGroups) => {
const actual = model.codaGroups?.[dept] || { coda: 0, avgDailyCoda: 0, groups: {} };
const anchored = anchors.coda?.[dept];
const deptCode = code.dept.get(dept) || null;
const block = { deptCode, dept, actualCoda: round(actual.coda), avgDailyCoda: round(actual.avgDailyCoda), anchoredCoda: anchoredBlock(anchored, half) };
if (withGroups) {
block.groups = Object.entries(actual.groups).map(([group, g]) => ({
groupCode: code.group.get(`${deptCode}|${group}`) || null, group,
actualCoda: round(g.coda), avgDailyCoda: round(g.avgDailyCoda),
anchoredCoda: anchoredBlock(anchored?.groups?.[group], half),
}));
}
return block;
};
const dream = invoiceDepts.map(d => deptBlock(d, true));
const realityDepts = Object.keys(model.codaGroups || {}).filter(d => companyOf[d] === REALITY_COMPANY && round(model.codaGroups[d].coda) > 0);
const reality = realityDepts.map(d => deptBlock(d, false));
const coda = {
...common,
companies: [
{ company: INVOICE_COMPANY, actualCoda: dream.reduce((s, d) => s + d.actualCoda, 0), departments: dream },
{ company: REALITY_COMPANY, actualCoda: reality.reduce((s, d) => s + d.actualCoda, 0), departments: reality },
],
};
return { invoice, coda };
}