190 lines
8.9 KiB
TypeScript
190 lines
8.9 KiB
TypeScript
import { z } from 'zod'
|
||
import { readArtPointDashboard } from './art-workflow-point-configuration'
|
||
import { SalaryError } from './personnel-salary'
|
||
import { currentSalaryMonth } from './performance-salary-templates'
|
||
import type { ArtPointPerson } from './art-workflow-points'
|
||
|
||
const string = z.string().trim().nullish()
|
||
const sourceNumber = z.union([z.number().finite(), z.string()]).nullish()
|
||
const contributionSchema = z.object({
|
||
name: z.string().trim().min(1),
|
||
workflowKey: z.string().trim().min(1),
|
||
finalPoints: z.number().finite(),
|
||
manualAdditionPoints: sourceNumber,
|
||
manualDeductionPoints: sourceNumber,
|
||
manualAdditionReasons: string,
|
||
manualDeductionReasons: string,
|
||
})
|
||
const manualRows = z.array(z.object({
|
||
workflowKey: string, processInstanceId: string, businessId: string, name: string, reason: string,
|
||
type: string, adjustmentType: string, action: string, enabled: z.boolean().optional(),
|
||
points: sourceNumber, score: sourceNumber, deductionPoints: sourceNumber,
|
||
}).nullable()).nullish()
|
||
const dashboardSchema = z.object({
|
||
generatedAt: z.string().trim().min(1),
|
||
workflows: z.array(z.object({
|
||
businessId: string, processInstanceId: string, workflowKey: string, reviewFinishTime: string,
|
||
scoreContributions: z.array(contributionSchema),
|
||
})),
|
||
manualDeductions: manualRows,
|
||
meta: z.object({ manualDeductions: manualRows }).nullish(),
|
||
historicalScores: z.record(sourceNumber).nullish(),
|
||
historicalOvertimePenalties: z.record(sourceNumber).nullish(),
|
||
})
|
||
|
||
type PointPerson = Pick<ArtPointPerson, 'id' | 'realName' | 'flowerName'>
|
||
type MonthPoints = { points: Map<string, number>; ambiguousEmployeeIds: Set<string> }
|
||
type ManualRows = z.infer<typeof manualRows>
|
||
type ManualAdjustment = { key: string; workflowKey: string; date: string; name: string; type: 'add' | 'deduct'; points: number; reason: string }
|
||
|
||
const roundPoints = (value: number) => Math.round(value * 100) / 100
|
||
const personWorkflowKey = (workflowKey: string, name: string) => JSON.stringify([workflowKey, name])
|
||
const additionTypes = new Set(['add', 'addition', 'plus', '加分'])
|
||
|
||
function parseNumber(value: unknown) {
|
||
const number = Number(value)
|
||
return Number.isFinite(number) ? number : 0
|
||
}
|
||
|
||
function reviewMonth(value: string | null | undefined) {
|
||
if (!value) return
|
||
const local = /^(\d{4}-\d{2}-\d{2})(?:[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?)?$/.exec(value)
|
||
const date = new Date(local ? `${local[1]}T00:00:00Z` : value)
|
||
if (!Number.isFinite(date.getTime()) || (local && !date.toISOString().startsWith(local[1]))) {
|
||
throw new Error('Invalid dashboard review date')
|
||
}
|
||
// The dashboard's unzoned text is already a displayed Shanghai calendar date.
|
||
return local ? local[1].slice(0, 7) : currentSalaryMonth(date)
|
||
}
|
||
|
||
function normalizeManualAdjustments(rows: ManualRows): ManualAdjustment[] {
|
||
return (rows ?? []).flatMap(row => {
|
||
if (!row || row.enabled === false) return []
|
||
const workflowKey = row.workflowKey || row.processInstanceId || row.businessId
|
||
const name = row.name
|
||
const points = roundPoints(Math.max(0, parseNumber(row.points ?? row.score ?? row.deductionPoints)))
|
||
if (!workflowKey || !name || !points) return []
|
||
const type = additionTypes.has((row.type || row.adjustmentType || row.action || '').toLowerCase()) ? 'add' : 'deduct'
|
||
const reason = row.reason || ''
|
||
const match = /^(\d{4})(\d{2})(\d{2})/.exec(workflowKey)
|
||
const date = match ? `${match[1]}-${match[2]}-${match[3]}` : ''
|
||
return [{ key: JSON.stringify([workflowKey, name, type, points, reason]), workflowKey, date, name, type, points, reason }]
|
||
})
|
||
}
|
||
|
||
// The ranking matches embedded adjustments by reason first, then by amount in source order.
|
||
function appliedAdjustments(rows: ManualAdjustment[], amount: number, reasons: string | null | undefined) {
|
||
const points = roundPoints(amount)
|
||
if (!points) return []
|
||
const reasonParts = new Set(reasons?.split(/[;;]/).map(part => part.trim()).filter(Boolean))
|
||
const byReason = rows.filter(row => row.reason && reasonParts.has(row.reason))
|
||
if (byReason.length) return byReason
|
||
|
||
const matched: ManualAdjustment[] = []
|
||
let remaining = points
|
||
for (const row of rows) {
|
||
const next = roundPoints(remaining - row.points)
|
||
if (next < 0) continue
|
||
matched.push(row)
|
||
remaining = next
|
||
if (remaining === 0) return matched
|
||
}
|
||
return rows.filter(row => row.points === points)
|
||
}
|
||
|
||
export function collectSalaryDashboardPoints(payload: unknown, months: string[], people: readonly PointPerson[]) {
|
||
const dashboard = dashboardSchema.parse(payload)
|
||
const monthsByWorkflow = new Map<string, string | undefined>()
|
||
const workflowsByMonth = new Map<string, typeof dashboard.workflows>()
|
||
const requestedMonths = new Set(months)
|
||
for (const workflow of dashboard.workflows) {
|
||
const key = workflow.businessId || workflow.processInstanceId || workflow.workflowKey
|
||
if (!key || monthsByWorkflow.has(key) || workflow.scoreContributions.some(item => item.workflowKey !== key)) {
|
||
throw new Error('Invalid dashboard workflow identity')
|
||
}
|
||
const month = reviewMonth(workflow.reviewFinishTime)
|
||
monthsByWorkflow.set(key, month)
|
||
if (!month || !requestedMonths.has(month)) continue
|
||
const workflows = workflowsByMonth.get(month) ?? []
|
||
workflows.push(workflow)
|
||
workflowsByMonth.set(month, workflows)
|
||
}
|
||
|
||
const adjustments = normalizeManualAdjustments(dashboard.manualDeductions ?? dashboard.meta?.manualDeductions)
|
||
const adjustmentsByPersonWorkflow = new Map<string, ManualAdjustment[]>()
|
||
for (const adjustment of adjustments) {
|
||
const key = personWorkflowKey(adjustment.workflowKey, adjustment.name)
|
||
const rows = adjustmentsByPersonWorkflow.get(key) ?? []
|
||
rows.push(adjustment)
|
||
adjustmentsByPersonWorkflow.set(key, rows)
|
||
}
|
||
const idsByName = new Map<string, Set<string>>()
|
||
for (const person of people) {
|
||
for (const alias of [person.realName?.trim(), person.flowerName?.trim()]) {
|
||
if (!alias) continue
|
||
const ids = idsByName.get(alias) ?? new Set<string>()
|
||
ids.add(person.id)
|
||
idsByName.set(alias, ids)
|
||
}
|
||
}
|
||
|
||
const result = new Map<string, MonthPoints>()
|
||
for (const month of Array.from(requestedMonths)) {
|
||
const byName = new Map<string, number>()
|
||
const addPoints = (name: string, points: number) => byName.set(name, (byName.get(name) ?? 0) + points)
|
||
const applied = new Set<string>()
|
||
for (const workflow of workflowsByMonth.get(month) ?? []) {
|
||
for (const contribution of workflow.scoreContributions) {
|
||
addPoints(contribution.name, contribution.finalPoints)
|
||
const rows = adjustmentsByPersonWorkflow.get(personWorkflowKey(contribution.workflowKey, contribution.name)) ?? []
|
||
for (const adjustment of [
|
||
...appliedAdjustments(rows.filter(row => row.type === 'add'), parseNumber(contribution.manualAdditionPoints), contribution.manualAdditionReasons),
|
||
...appliedAdjustments(rows.filter(row => row.type === 'deduct'), parseNumber(contribution.manualDeductionPoints), contribution.manualDeductionReasons),
|
||
]) applied.add(adjustment.key)
|
||
}
|
||
}
|
||
const [year, calendarMonth] = month.split('-').map(Number)
|
||
const lastDay = new Date(Date.UTC(year, calendarMonth, 0)).getUTCDate()
|
||
for (const adjustment of adjustments) {
|
||
if (applied.has(adjustment.key) || adjustment.date < '2026-06-01') continue
|
||
const included = monthsByWorkflow.has(adjustment.workflowKey)
|
||
? monthsByWorkflow.get(adjustment.workflowKey) === month
|
||
: adjustment.date >= `${month}-01` && adjustment.date <= `${month}-${lastDay}`
|
||
if (included) addPoints(adjustment.name, adjustment.type === 'add' ? adjustment.points : -adjustment.points)
|
||
}
|
||
if (month <= '2026-04') {
|
||
for (const [name, score] of Object.entries(dashboard.historicalScores ?? {})) {
|
||
addPoints(name.trim(), Math.max(0, parseNumber(score) - parseNumber(dashboard.historicalOvertimePenalties?.[name])))
|
||
}
|
||
}
|
||
|
||
const centsByEmployee = new Map<string, number>()
|
||
const ambiguousEmployeeIds = new Set<string>()
|
||
byName.forEach((score, name) => {
|
||
const ids = idsByName.get(name)
|
||
if (!ids?.size) return
|
||
if (ids.size > 1) {
|
||
ids.forEach(id => ambiguousEmployeeIds.add(id))
|
||
return
|
||
}
|
||
const [id] = Array.from(ids)
|
||
centsByEmployee.set(id, (centsByEmployee.get(id) ?? 0) + Math.round(score * 100))
|
||
})
|
||
ambiguousEmployeeIds.forEach(id => centsByEmployee.delete(id))
|
||
const points = new Map(Array.from(centsByEmployee, ([id, cents]) => [id, cents / 100]))
|
||
result.set(month, { points, ambiguousEmployeeIds })
|
||
}
|
||
return result
|
||
}
|
||
|
||
export async function readSalaryDashboardPoints(
|
||
months: string[], people: PromiseLike<readonly PointPerson[]>, dashboard = readArtPointDashboard(),
|
||
) {
|
||
try {
|
||
const [payload, identities] = await Promise.all([dashboard, people])
|
||
return collectSalaryDashboardPoints(payload, months, identities)
|
||
} catch {
|
||
throw new SalaryError('美术流程积分暂时无法读取,请稍后重试。', 503, 'SALARY_POINTS_UNAVAILABLE')
|
||
}
|
||
}
|