import { prisma } from './prisma' import { requireSalaryAccess } from './personnel-salary' import { resolveSalaryMonth, previousSalaryMonth, getPositionSalaryTemplate } from './performance-salary-templates' import { resolveSalarySourceMonth, roundSalaryScore } from './performance-salary-calculation' import { collectSalarySurveyScores, createSalarySurveyPersonMatcher, surveyMatchMessages } from './salary-survey-scores' import { readSalaryWorkflowMetrics } from './performance-salary-workflows' import { readSalaryMarketIntent } from './salary-market-intent' import { calculatePositionScore, resolvePersonnelPerformance, personnelPositions, performancePositions } from './salary-position-contract' import { serializePosition } from './salary-positions' import { calculateSalaryPay } from './performance-salary-pay' import { buildSalaryDepartmentScopes, summarizeDepartmentDelivery, summarizeDepartmentMarketIntent } from './salary-department-metrics' import { SALARY_DEPARTMENT_UNRESOLVED } from './salary-department-contract' import type { SalaryDetails, SalaryDetailRow, SalaryCell } from './performance-salary-details-contract' export async function getPerformanceSalaryDetails(userId: string, month: unknown): Promise { await requireSalaryAccess(userId) const displayMonth = resolveSalaryMonth(month) // One snapshot owns personnel, configuration revisions and submitted scores. const { state, responses, people, bases, positions, units } = await prisma.$transaction(async db => { const count = await db.performanceSurveyResponse.count({ where: { survey: { assessmentMonth: displayMonth, status: { notIn: ['draft', 'cancelled'] } }, assignment: { status: 'submitted' } } }) const state = resolveSalarySourceMonth(displayMonth, count, process.env.NODE_ENV, process.env.PERFORMANCE_SALARY_LOCAL_TEST_FALLBACK) const [responses, people, bases, positions, units] = await Promise.all([ db.performanceSurveyResponse.findMany({ where: { survey: { assessmentMonth: state.sourceMonth, status: { notIn: ['draft', 'cancelled'] } }, assignment: { status: 'submitted' } }, select: { 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 } } } }), db.performanceSurveyEmployeeProfile.findMany({ include: { departmentMemberships: true } }), db.personnelSalaryBase.findMany({ where: { deletedAt: null }, orderBy: [{ createdAt: 'asc' }, { id: 'asc' }] }), db.salaryPositionConfig.findMany({ where: { deletedAt: null }, orderBy: [{ createdAt: 'asc' }, { id: 'asc' }] }), db.organizationUnit.findMany({ where: { isActive: true }, select: { sourceDeptId: true, name: true, path: true } }), ]) return { state, responses, people, bases, positions, units } }, { isolationLevel: 'RepeatableRead' }) const configuration = positions.map(serializePosition) const matches = new Map(bases.map(base => [base.id, resolvePersonnelPerformance(base.positionId, base.jobGrade, configuration)])) const marketPositionIds = new Set(configuration.filter(position => position.dimensions.some(dimension => dimension.metrics.some(metric => metric.source.kind === 'market-intent-top3'))).map(position => position.id)) const roots = personnelPositions(configuration) const plannerPositionIds = new Set(roots.filter(position => position.salaryRole === 'ai-planning').map(position => position.id)) const managerPositionIds = new Set(roots.filter(position => position.salaryRole === 'management').map(position => position.id)) const managerBases = bases.filter(base => managerPositionIds.has(base.positionId ?? '')) const departmentScopes = buildSalaryDepartmentScopes(managerBases.map(base => base.employeeProfileId), people, units, new Set(bases.filter(base => plannerPositionIds.has(base.positionId ?? '')).map(base => base.employeeProfileId))) const marketEmployeeIds = new Set(bases.filter(base => marketPositionIds.has(matches.get(base.id)?.id ?? '') && !managerPositionIds.has(base.positionId ?? '')).map(base => base.employeeProfileId)) for (const base of managerBases) if (marketPositionIds.has(matches.get(base.id)?.id ?? '')) { for (const member of departmentScopes.get(base.employeeProfileId)!.planners) marketEmployeeIds.add(member.employeeProfileId) } // Market validation assesses last month's completed flows; other metrics keep their own source month. const marketSourceMonth = previousSalaryMonth(displayMonth) const [workflows, market] = await Promise.all([ readSalaryWorkflowMetrics(state.sourceMonth, people), readSalaryMarketIntent(marketSourceMonth, people, Array.from(marketEmployeeIds)), ]) const scores = collectSalarySurveyScores(responses) const matchSurveyPerson = createSalarySurveyPersonMatcher(people) const surveyMatchIssues: NonNullable = [] const departmentMatchIssues: NonNullable = [] const roles: SalaryDetails['roles'] = { 'ai-planning': [], photography: [], 'spatial-visual': [], management: [], 'ai-technical': [] } const unmatchedIds = new Set(bases.filter(base => !matches.get(base.id)).map(base => base.positionId)) const groupPositions = [...performancePositions(configuration).filter(position => !unmatchedIds.has(position.id)), ...roots.filter(position => unmatchedIds.has(position.id)).map(position => ({ ...position, dimensions: [] }))] const positionGroups = groupPositions.map(position => { return { position, template: getPositionSalaryTemplate(position, displayMonth), rows: [] as SalaryDetailRow[] } }) const groupById = new Map(positionGroups.map(group => [group.position.id, group])) for (const base of bases) { const match = matches.get(base.id) const group = groupById.get(match?.id ?? base.positionId ?? '') if (!group) continue const surveyPerson = matchSurveyPerson(base) const raw = surveyPerson.employeeProfileId ? scores.get(surveyPerson.employeeProfileId) : undefined if (surveyPerson.reason && group.position.dimensions.some(d => d.metrics.some(m => m.source.kind === 'survey'))) { surveyMatchIssues.push({ employeeProfileId: base.employeeProfileId, employeeLabel: base.flowerName || base.name, salaryRole: group.position.salaryRole, reason: surveyPerson.reason, message: surveyMatchMessages[surveyPerson.reason] }) } const metrics: Record = {} const scope = group.position.salaryRole === 'management' ? departmentScopes.get(base.employeeProfileId) : undefined const hasMarket = group.position.dimensions.some(d => d.metrics.some(m => m.source.kind === 'market-intent-top3')) const hasDelivery = group.position.dimensions.some(d => d.metrics.some(m => m.source.kind === 'on-time')) const marketEvidence = scope && hasMarket ? summarizeDepartmentMarketIntent(marketSourceMonth, scope, market) : market.get(base.employeeProfileId) const deliveryEvidence = scope && hasDelivery ? summarizeDepartmentDelivery(state.sourceMonth, scope, workflows.deliveryCounts) : undefined if (scope && !scope.department && (hasMarket || hasDelivery)) departmentMatchIssues.push({ employeeProfileId: base.employeeProfileId, employeeLabel: base.flowerName || base.name, message: SALARY_DEPARTMENT_UNRESOLVED }) for (const dimension of group.position.dimensions) for (const metric of dimension.metrics) { metrics[metric.id] = metric.source.kind === 'survey' ? raw?.get(metric.source.templateCode) ?? null : metric.source.kind === 'on-time' ? (deliveryEvidence ? deliveryEvidence.rawScore : workflows.onTimeRates.get(base.employeeProfileId) ?? null) : metric.source.kind === 'market-intent-top3' ? marketEvidence?.rawScore ?? null : null } const result = calculatePositionScore(group.position.dimensions, metrics) const values: Record = { 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), points: workflows.points.has(base.employeeProfileId) ? roundSalaryScore(workflows.points.get(base.employeeProfileId)!) : null, performanceScore: result.totalScore, ...calculateSalaryPay(result.totalScore, base), } for (const key of Object.keys(metrics)) { values[`${key}RawValue`] = metrics[key] values[`${key}Score`] = result.contributions[key] } const metricEvidence: NonNullable = {} for (const dimension of group.position.dimensions) for (const metric of dimension.metrics) { if (metric.source.kind === 'market-intent-top3' && marketEvidence) metricEvidence[metric.id] = marketEvidence if (metric.source.kind === 'on-time' && deliveryEvidence) metricEvidence[metric.id] = deliveryEvidence } const row: SalaryDetailRow = { employeeProfileId: base.employeeProfileId, employeeLabel: base.flowerName || base.name, hasSalaryBase: true, positionGroupCode: `salary:${group.position.id}`, positionId: base.positionId ?? undefined, jobGrade: base.jobGrade, performancePositionId: match?.id ?? null, performanceMatch: match ? 'matched' : 'unmatched', metrics, metricEvidence, values, totalScore: result.totalScore } 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, roles, positionGroups, surveyMatchIssues, departmentMatchIssues } }