gongxiangp2/lib/performance-salary-details.ts

360 lines
22 KiB
TypeScript

import type { Prisma } from '@prisma/client'
import { prisma } from './prisma'
import { requireSalaryAccess, SalaryError } from './personnel-salary'
import { resolveSalaryMonth, previousSalaryMonth, getPositionSalaryTemplate } from './performance-salary-templates'
import { resolveSalarySourceMonth } from './performance-salary-calculation'
import { collectSalarySurveyScores, createSalarySurveyPersonMatcher, surveyMatchMessages } from './salary-survey-scores'
import { readSalaryWorkflowMetricsBatch, type SalaryWorkflowMetrics } from './performance-salary-workflows'
import { readSalaryMarketIntentBatch } from './salary-market-intent'
import { readSalaryWorkflowSnapshots } from './salary-workflow-source'
import { readArtPointDashboard, readArtPointOvertimeExemptions } from './art-workflow-point-configuration'
import { readSalaryDashboardPoints } from './salary-dashboard-points'
import {
calculatePositionScore, resolvePersonnelPerformance, personnelPositions, performancePositions, percentageBasisPoints,
type SalaryPosition,
} from './salary-position-contract'
import { serializePosition } from './salary-positions'
import { calculateSalaryPay, calculateSalaryDifference } from './performance-salary-pay'
import { buildSalaryDepartmentScopes, summarizeDepartmentDelivery, summarizeDepartmentMarketIntent } from './salary-department-metrics'
import { SALARY_DEPARTMENT_UNRESOLVED, type SalaryDepartmentScope } from './salary-department-contract'
import type { MarketIntentEvidence } from './salary-market-intent-contract'
import type { SalaryDetails, SalaryDetailRow, SalaryCell, SalaryDataSource, SalarySourceStatus, SalaryPhase } from './performance-salary-details-contract'
import type { SalaryRole } from './performance-salary-roles'
type DetailsScope = {
role: SalaryRole
phase: 'base' | 'full'
onProgress?: (details: SalaryDetails) => void
signal?: AbortSignal
}
type MonthState = ReturnType<typeof resolveSalarySourceMonth>
type SalaryBase = Prisma.PersonnelSalaryBaseGetPayload<{ select: typeof baseFields }>
type AssignedSalary = { base: SalaryBase; position: SalaryPosition; matched: boolean }
const baseFields = {
id: true, employeeProfileId: true, positionId: true, jobGrade: true, name: true, flowerName: true,
department: true, brand: true, baseSalary: true, gradeSalary: true, performanceSalary: true,
} as const
const identityFields = { id: true, realName: true, flowerName: true, displayName: true, dingtalkUserId: true } as const
const departmentFields = {
departmentPath: true, sourcePayload: true, employmentState: true,
departmentMemberships: { select: { sourceDeptId: true, departmentPath: true, isPrimary: true } },
} as const
const surveyFilter = (month: string) => ({
survey: { assessmentMonth: month, status: { notIn: ['draft', 'cancelled'] } },
assignment: { status: 'submitted' },
})
const surveyFields = {
id: true, totalScore: true, createdAt: true, scores: true,
assignment: { select: { workflowStageKey: true, reviewerSource: true, evaluatorSnapshot: true } },
target: { select: { employeeProfileId: true } },
survey: { select: { templateCode: true, templateSnapshot: true } },
} as const
const emptyWorkflowMetrics = (): SalaryWorkflowMetrics => ({
sourceMonth: '', points: new Map(), deliveryCounts: new Map(), onTimeRates: new Map(),
})
const emptyRoles = (): SalaryDetails['roles'] => ({
'ai-planning': [], photography: [], 'spatial-visual': [], management: [], 'ai-technical': [],
})
const monthFallbackEnabled = () => process.env.NODE_ENV === 'development' && process.env.PERFORMANCE_SALARY_LOCAL_TEST_FALLBACK === 'true'
const sourceFallbacks: Record<SalaryDataSource, { code: string; message: string }> = {
survey: { code: 'SALARY_SURVEY_UNAVAILABLE', message: '绩效调研暂时无法读取。' },
'on-time': { code: 'SALARY_DELIVERY_UNAVAILABLE', message: '按时交付率暂时无法读取。' },
'market-intent-top3': { code: 'MARKET_INTENT_UNAVAILABLE', message: '市场验证数据暂时无法读取。' },
points: { code: 'SALARY_POINTS_UNAVAILABLE', message: '积分暂时无法读取。' },
}
function assignedSalaries(bases: SalaryBase[], configuration: SalaryPosition[], role?: SalaryRole) {
const matches = bases.map(base => ({ base, match: resolvePersonnelPerformance(base.positionId, base.jobGrade, configuration) }))
const unmatchedIds = new Set(matches.filter(({ match }) => !match).map(({ base }) => base.positionId))
const groupPositions = [
...performancePositions(configuration).filter(position => !unmatchedIds.has(position.id)),
...personnelPositions(configuration).filter(position => unmatchedIds.has(position.id)).map(position => ({ ...position, dimensions: [] })),
].filter(position => !role || position.salaryRole === role)
const byId = new Map(groupPositions.map(position => [position.id, position]))
const assigned = matches.flatMap(({ base, match }) => {
const position = byId.get(match?.id ?? base.positionId ?? '')
return position ? [{ base, position, matched: Boolean(match) }] : []
})
return { groupPositions, assigned }
}
function visitMetrics(assignment: AssignedSalary, scope?: DetailsScope) {
return assignment.position.dimensions.flatMap(dimension => dimension.metrics.filter(metric =>
!scope || (percentageBasisPoints(dimension.weight) > 0 && percentageBasisPoints(metric.weight) > 0)))
}
function makeSalaryDetails(state: MonthState, groupPositions: SalaryPosition[], rows: SalaryDetailRow[]): SalaryDetails {
const roles = emptyRoles()
const positionGroups = groupPositions.map(position => ({
position: { ...position }, template: getPositionSalaryTemplate(position, state.displayMonth), rows: [] as SalaryDetailRow[],
}))
const byId = new Map(positionGroups.map(group => [group.position.id, group]))
for (const row of rows) {
const group = byId.get(row.performancePositionId ?? row.positionId ?? '')!
group.rows.push(row)
roles[group.position.salaryRole].push(row)
}
for (const group of positionGroups) {
group.rows.sort((a, b) => String(a.values.name).localeCompare(String(b.values.name), 'zh-CN'))
group.position.personnelCount = group.rows.length
}
return { ...state, marketSourceMonth: previousSalaryMonth(state.displayMonth), roles, positionGroups }
}
function makeSalaryRow({ base, position, matched }: AssignedSalary): SalaryDetailRow {
return {
employeeProfileId: base.employeeProfileId, employeeLabel: base.flowerName || base.name,
hasSalaryBase: true, positionGroupCode: `salary:${position.id}`, positionId: base.positionId ?? undefined,
jobGrade: base.jobGrade, performancePositionId: matched ? position.id : null,
performanceMatch: matched ? 'matched' : 'unmatched', metrics: {}, metricEvidence: {}, totalScore: null,
values: {
name: base.name, nickname: base.flowerName, jobGrade: base.jobGrade, department: base.department, brand: base.brand,
baseSalary: base.baseSalary.toFixed(2), gradeSalary: base.gradeSalary.toFixed(2),
performanceSalary: base.performanceSalary.toFixed(2), baseSalaryBasis: base.baseSalary.toFixed(2),
performanceSalaryBasis: base.performanceSalary.toFixed(2),
},
}
}
export async function getPerformanceSalaryDetails(userId: string, month: unknown, scope?: DetailsScope): Promise<SalaryDetails> {
await requireSalaryAccess(userId)
const displayMonth = resolveSalaryMonth(month)
const previousMonth = previousSalaryMonth(displayMonth)
const sourceStatuses = new Map<string, SalarySourceStatus>()
function recordSource(source: SalaryDataSource, state: MonthState, status: 'pending' | 'ready' | 'failed', error?: unknown) {
if (!scope) return
const sourceMonth = source === 'market-intent-top3' ? previousSalaryMonth(state.displayMonth)
: source === 'points' ? state.displayMonth : state.sourceMonth
const identity = { source, salaryMonth: state.displayMonth, sourceMonth }
const key = `${source}:${state.displayMonth}`
if (sourceStatuses.get(key)?.status === 'failed') return
sourceStatuses.set(key, status === 'failed' ? {
...identity, status, ...(error instanceof SalaryError ? { code: error.code, message: error.message } : sourceFallbacks[source]),
} : { ...identity, status })
}
const withScope = (data: SalaryDetails, phase: SalaryPhase) => scope
? { ...data, scope: { role: scope.role, phase, sources: Array.from(sourceStatuses.values()) } }
: data
const snapshot = await prisma.$transaction(async db => {
const positions = await db.salaryPositionConfig.findMany({
where: { deletedAt: null, ...(scope ? { salaryRole: scope.role } : {}) },
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
})
const configuration = positions.map(serializePosition)
const bases = await db.personnelSalaryBase.findMany({
where: {
deletedAt: null,
...(scope ? { positionId: { in: personnelPositions(configuration).map(position => position.id) } } : {}),
},
select: baseFields,
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
})
const assignments = assignedSalaries(bases, configuration, scope?.role)
return { ...assignments, configuration, bases }
}, { isolationLevel: 'RepeatableRead' })
const { assigned, groupPositions, configuration, bases } = snapshot
const base = withScope(makeSalaryDetails({ displayMonth, sourceMonth: displayMonth, isFallback: false },
groupPositions, assigned.map(makeSalaryRow)), 'base')
if (scope?.phase === 'base') return base
scope?.onProgress?.(base)
scope?.signal?.throwIfAborted()
const metrics = assigned.map(assignment => ({ ...assignment, metrics: visitMetrics(assignment, scope) }))
const surveyCodes = Array.from(new Set(metrics.flatMap(({ metrics }) => metrics.flatMap(metric =>
metric.source.kind === 'survey' ? [metric.source.templateCode] : []))))
const surveyAssignments = metrics.filter(({ metrics }) => metrics.some(metric => metric.source.kind === 'survey'))
const wantsSurvey = !scope || surveyCodes.length > 0
const wantsDelivery = !scope || metrics.some(({ metrics }) => metrics.some(metric => metric.source.kind === 'on-time'))
const wantsPoints = assigned.some(({ position }) => position.salaryRole === 'ai-planning')
const marketAssignments = metrics.filter(({ metrics }) => metrics.some(metric => metric.source.kind === 'market-intent-top3'))
const managerIds = metrics.filter(({ position, metrics }) => position.salaryRole === 'management'
&& metrics.some(metric => metric.source.kind === 'on-time' || metric.source.kind === 'market-intent-top3'))
.map(({ base }) => base.employeeProfileId)
const departmentNeeded = !scope || managerIds.length > 0
const wantsPeople = wantsSurvey || wantsDelivery || wantsPoints || marketAssignments.length > 0
const states = await Promise.all([displayMonth, previousMonth].map(async salaryMonth => {
const count = monthFallbackEnabled() && salaryMonth === '2026-10'
? await prisma.performanceSurveyResponse.count({ where: surveyFilter(salaryMonth) }) : 0
return resolveSalarySourceMonth(salaryMonth, count, process.env.NODE_ENV, process.env.PERFORMANCE_SALARY_LOCAL_TEST_FALLBACK)
}))
// Only personnel and position configuration need a single database snapshot for both salary months.
const peopleTask = wantsPeople ? prisma.performanceSurveyEmployeeProfile.findMany({
select: { ...identityFields, ...(departmentNeeded ? departmentFields : {}) },
}) : Promise.resolve([])
const unitsTask = departmentNeeded ? prisma.organizationUnit.findMany({
where: { isActive: true }, select: { sourceDeptId: true, name: true, path: true },
}) : Promise.resolve([])
const plannerPositions = new Set(personnelPositions(configuration).filter(position => position.salaryRole === 'ai-planning').map(position => position.id))
const plannerTask = scope?.role === 'management' && marketAssignments.length
? prisma.personnelSalaryBase.findMany({
where: { deletedAt: null, position: { deletedAt: null, personnelPositionId: null, salaryRole: 'ai-planning' } },
select: { employeeProfileId: true },
}) : Promise.resolve(bases.filter(row => plannerPositions.has(row.positionId ?? '')))
const workflowMonths = Array.from(new Set(states.map(state => state.sourceMonth))).reverse()
const marketMonths = states.map(state => previousSalaryMonth(state.displayMonth)).reverse()
let matchSurveyPerson = createSalarySurveyPersonMatcher([])
let deliveryDepartments = new Map<string, SalaryDepartmentScope>()
let marketDepartments = new Map(deliveryDepartments)
const scores = new Map<string, ReturnType<typeof collectSalarySurveyScores>>()
let workflowsByMonth = new Map<string, SalaryWorkflowMetrics>()
let pointsByMonth: Awaited<ReturnType<typeof readSalaryDashboardPoints>> = new Map()
let marketByMonth = new Map<string, Map<string, MarketIntentEvidence>>()
const wantsMarket = !scope || marketAssignments.length > 0
for (const state of states) {
if (wantsSurvey) recordSource('survey', state, 'pending')
if (wantsDelivery) recordSource('on-time', state, 'pending')
if (wantsMarket) recordSource('market-intent-top3', state, 'pending')
}
if (wantsPoints) recordSource('points', states[0], 'pending')
async function loadSource(source: SalaryDataSource, sourceStates: MonthState[], read: () => Promise<void>) {
try {
await read()
for (const state of sourceStates) recordSource(source, state, 'ready')
} catch (error) {
if (!scope) throw error
for (const state of sourceStates) recordSource(source, state, 'failed', error)
}
if (scope?.onProgress && !scope.signal?.aborted && Array.from(sourceStatuses.values()).some(item => item.status === 'pending')) {
scope.onProgress(buildResult('partial'))
}
}
const surveys = wantsSurvey ? loadSource('survey', states, async () => {
matchSurveyPerson = createSalarySurveyPersonMatcher(await peopleTask)
const surveyTargets = Array.from(new Set(surveyAssignments.flatMap(({ base }) => {
const id = matchSurveyPerson(base).employeeProfileId
return id ? [id] : []
})))
if (scope && !surveyTargets.length) return
await Promise.all(Array.from(new Set(states.map(state => state.sourceMonth)), async sourceMonth => {
const where = surveyFilter(sourceMonth)
try {
const responses = await prisma.performanceSurveyResponse.findMany({
where: scope ? {
...where, target: { employeeProfileId: { in: surveyTargets } },
survey: { ...where.survey, templateCode: { in: surveyCodes } },
} : where,
select: surveyFields,
})
scores.set(sourceMonth, collectSalarySurveyScores(responses))
} catch (error) {
if (!scope) throw error
for (const state of states.filter(state => state.sourceMonth === sourceMonth)) recordSource('survey', state, 'failed', error)
}
}))
}) : undefined
const snapshots = wantsDelivery || wantsMarket
? readSalaryWorkflowSnapshots(Boolean(scope && !wantsDelivery)) : undefined
// Points always read fresh source results. Delivery retains its exemption-only cache.
const dashboard = wantsPoints ? readArtPointDashboard() : undefined
const exemptions = wantsDelivery ? readArtPointOvertimeExemptions(dashboard) : undefined
const workflows = [
wantsDelivery && loadSource('on-time', states, async () => {
const [people, units, rows, overtimeExemptions] = await Promise.all([peopleTask, unitsTask, snapshots, exemptions])
deliveryDepartments = buildSalaryDepartmentScopes(managerIds, people, units, new Set())
workflowsByMonth = await readSalaryWorkflowMetricsBatch(workflowMonths, people, rows, {
delivery: true, pointsMonths: [], overtimeExemptions,
})
}),
wantsPoints && loadSource('points', [states[0]], async () => {
pointsByMonth = await readSalaryDashboardPoints([displayMonth], peopleTask, dashboard)
}),
]
const market = wantsMarket ? loadSource('market-intent-top3', states, async () => {
const [people, units, plannerBases, rows] = await Promise.all([peopleTask, unitsTask, plannerTask, snapshots])
marketDepartments = buildSalaryDepartmentScopes(managerIds, people, units, new Set(plannerBases.map(item => item.employeeProfileId)))
const marketEmployeeIds = new Set(marketAssignments.flatMap(({ base, position }) => position.salaryRole === 'management'
? (marketDepartments.get(base.employeeProfileId)?.planners ?? []).map(member => member.employeeProfileId)
: [base.employeeProfileId]))
marketByMonth = await readSalaryMarketIntentBatch(marketMonths, people, Array.from(marketEmployeeIds), rows, scope ? (month, error) => {
for (const state of states.filter(state => previousSalaryMonth(state.displayMonth) === month)) recordSource('market-intent-top3', state, 'failed', error)
} : undefined, scope?.signal)
}) : undefined
function calculateMonth(state: MonthState): SalaryDetails {
const marketSourceMonth = previousSalaryMonth(state.displayMonth)
const ready = (source: SalaryDataSource) => !scope || sourceStatuses.get(`${source}:${state.displayMonth}`)?.status === 'ready'
const workflows = workflowsByMonth.get(state.sourceMonth) ?? emptyWorkflowMetrics()
const market = marketByMonth.get(marketSourceMonth) ?? new Map<string, MarketIntentEvidence>()
const surveyMatchIssues: NonNullable<SalaryDetails['surveyMatchIssues']> = []
const pointsMatchIssues: NonNullable<SalaryDetails['pointsMatchIssues']> = []
const pointResult = pointsByMonth.get(state.displayMonth)
const departmentMatchIssues: NonNullable<SalaryDetails['departmentMatchIssues']> = []
const rows = assigned.map(assignment => {
const { base, position } = assignment
const row = makeSalaryRow(assignment)
const surveyPerson = matchSurveyPerson(base)
const raw = surveyPerson.employeeProfileId ? scores.get(state.sourceMonth)?.get(surveyPerson.employeeProfileId) : undefined
const relevant = visitMetrics(assignment, scope)
if (surveyPerson.reason && ready('survey') && relevant.some(metric => metric.source.kind === 'survey')) {
surveyMatchIssues.push({ employeeProfileId: base.employeeProfileId, employeeLabel: row.employeeLabel, salaryRole: position.salaryRole,
reason: surveyPerson.reason, message: surveyMatchMessages[surveyPerson.reason] })
}
const deliveryDepartment = deliveryDepartments.get(base.employeeProfileId)
const marketDepartment = marketDepartments.get(base.employeeProfileId)
const hasMarket = relevant.some(metric => metric.source.kind === 'market-intent-top3')
const hasDelivery = relevant.some(metric => metric.source.kind === 'on-time')
const marketEvidence = !ready('market-intent-top3') ? undefined : marketDepartment && hasMarket
? summarizeDepartmentMarketIntent(marketSourceMonth, marketDepartment, market) : market.get(base.employeeProfileId)
const deliveryEvidence = ready('on-time') && deliveryDepartment && hasDelivery
? summarizeDepartmentDelivery(state.sourceMonth, deliveryDepartment, workflows.deliveryCounts) : undefined
if ((hasMarket && marketDepartment?.department === null) || (hasDelivery && deliveryDepartment?.department === null)) {
departmentMatchIssues.push({ employeeProfileId: base.employeeProfileId, employeeLabel: row.employeeLabel, message: SALARY_DEPARTMENT_UNRESOLVED })
}
for (const metric of relevant) {
const source = metric.source
if (source.kind === 'survey') row.metrics[metric.id] = ready('survey') ? raw?.get(source.templateCode) ?? null : null
else if (source.kind === 'on-time') {
row.metrics[metric.id] = !ready('on-time') ? null : deliveryEvidence ? deliveryEvidence.rawScore : workflows.onTimeRates.get(base.employeeProfileId) ?? null
if (deliveryEvidence) row.metricEvidence![metric.id] = deliveryEvidence
} else if (source.kind === 'market-intent-top3') {
row.metrics[metric.id] = marketEvidence?.rawScore ?? null
if (marketEvidence) row.metricEvidence![metric.id] = marketEvidence
} else row.metrics[metric.id] = null
}
const { totalScore, contributions } = calculatePositionScore(position.dimensions, row.metrics)
row.totalScore = totalScore
const points = pointResult?.points.get(base.employeeProfileId)
if (position.salaryRole === 'ai-planning' && pointResult?.ambiguousEmployeeIds.has(base.employeeProfileId)) {
pointsMatchIssues.push({ employeeProfileId: base.employeeProfileId, employeeLabel: row.employeeLabel,
message: '姓名或花名对应多个人员,请核对人员档案与美术看板的积分归属。' })
}
Object.assign(row.values, {
points: points === undefined || position.salaryRole !== 'ai-planning' ? null : points,
performanceScore: totalScore,
...calculateSalaryPay(totalScore, base),
})
for (const id of Object.keys(row.metrics)) {
row.values[`${id}RawValue`] = row.metrics[id]
row.values[`${id}Score`] = contributions[id]
}
return row
})
return { ...makeSalaryDetails(state, groupPositions, rows), surveyMatchIssues, pointsMatchIssues, departmentMatchIssues }
}
function buildResult(phase: SalaryPhase) {
const [current, previous] = states.map(calculateMonth)
const previousByEmployee = new Map(Object.values(previous.roles).flat().map(row => [row.employeeProfileId, row.values.currentTotal as string | null]))
for (const row of Object.values(current.roles).flat()) {
const previousTotal = previousByEmployee.get(row.employeeProfileId) ?? null
row.values.previousTotal = previousTotal
row.values.salaryDifference = calculateSalaryDifference(row.values.currentTotal as string | null, previousTotal)
}
return withScope(current, phase)
}
await Promise.all([surveys, market, ...workflows])
return buildResult('full')
}