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 { resolvePersonnelPerformance, personnelPositions, performancePositions, percentageBasisPoints, positionAtMonth, CREATIVE_MANAGER_POSITION_ID, CREATIVE_PLANNING_POSITION_ID, type SalaryPosition, } from './salary-position-contract' import { performanceVersionOrder, serializePosition } from './salary-positions' import { calculatePositionScore, 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 | 'all' phase: 'base' | 'full' onProgress?: (details: SalaryDetails) => void signal?: AbortSignal } type MonthState = ReturnType 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(), artDeliveryCounts: 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 = { 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[], month: string, role?: SalaryRole) { const matches = bases.map(base => ({ base, match: resolvePersonnelPerformance(base.positionId, base.jobGrade, configuration, month) })) 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, performanceVersion: undefined, 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, performanceVersions: undefined }, 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 { await requireSalaryAccess(userId) const displayMonth = resolveSalaryMonth(month) const previousMonth = previousSalaryMonth(displayMonth) const role = scope?.role === 'all' ? undefined : scope?.role const sourceStatuses = new Map() 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, ...(role ? { salaryRole: role } : {}) }, include: { performanceVersions: performanceVersionOrder }, orderBy: [{ createdAt: 'asc' }, { id: 'asc' }], }) const configuration = positions.map(serializePosition) const bases = await db.personnelSalaryBase.findMany({ where: { deletedAt: null, ...(role ? { positionId: { in: personnelPositions(configuration).map(position => position.id) } } : {}), }, select: baseFields, orderBy: [{ createdAt: 'asc' }, { id: 'asc' }], }) return { configuration, bases } }, { isolationLevel: 'RepeatableRead' }) const { configuration, bases } = snapshot const months = [displayMonth, previousMonth] const assignments = new Map(months.map(month => [month, assignedSalaries( bases, configuration.map(position => positionAtMonth(position, month)), month, role, )])) const { assigned, groupPositions } = assignments.get(displayMonth)! 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 metricsByMonth = new Map(Array.from(assignments, ([month, { assigned }]) => [month, assigned.map(assignment => ({ ...assignment, metrics: visitMetrics(assignment, scope) }))])) const metrics = Array.from(metricsByMonth.values()).flat() 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 states = await Promise.all(months.map(async salaryMonth => { const testFallback = scope?.role !== 'all' && monthFallbackEnabled() const count = testFallback && salaryMonth === '2026-10' ? await prisma.performanceSurveyResponse.count({ where: surveyFilter(salaryMonth) }) : 0 return resolveSalarySourceMonth(salaryMonth, count, process.env.NODE_ENV, testFallback ? 'true' : undefined) })) const sourceStates = (source: SalaryDataSource) => states.filter(state => metricsByMonth.get(state.displayMonth)!.some(({ metrics }) => metrics.some(metric => metric.source.kind === source))) const surveyStates = sourceStates('survey') const deliveryStates = sourceStates('on-time') const marketStates = sourceStates('market-intent-top3') const wantsDelivery = deliveryStates.length > 0 const wantsMarket = marketStates.length > 0 const departmentNeeded = managerIds.length > 0 const wantsPeople = surveyStates.length > 0 || wantsDelivery || wantsPoints || wantsMarket // 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 = 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(deliveryStates.map(state => state.sourceMonth))).reverse() const marketMonths = marketStates.map(state => previousSalaryMonth(state.displayMonth)).reverse() let matchSurveyPerson = createSalarySurveyPersonMatcher([]) let deliveryDepartments = new Map() let marketDepartments = new Map(deliveryDepartments) const scores = new Map>() let workflowsByMonth = new Map() let pointsByMonth: Awaited> = new Map() let marketByMonth = new Map>() for (const state of surveyStates) recordSource('survey', state, 'pending') for (const state of deliveryStates) recordSource('on-time', state, 'pending') for (const state of marketStates) recordSource('market-intent-top3', state, 'pending') if (wantsPoints) recordSource('points', states[0], 'pending') async function loadSource(source: SalaryDataSource, sourceStates: MonthState[], read: () => Promise) { 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 = surveyStates.length ? loadSource('survey', surveyStates, async () => { matchSurveyPerson = createSalarySurveyPersonMatcher(await peopleTask) await Promise.all(Array.from(new Set(surveyStates.map(state => state.sourceMonth)), async sourceMonth => { const surveyAssignments = surveyStates.filter(state => state.sourceMonth === sourceMonth) .flatMap(state => metricsByMonth.get(state.displayMonth)!) .filter(({ metrics }) => metrics.some(metric => metric.source.kind === 'survey')) const surveyTargets = Array.from(new Set(surveyAssignments.flatMap(({ base }) => { const id = matchSurveyPerson(base).employeeProfileId return id ? [id] : [] }))) if (!surveyTargets.length) return const surveyCodes = Array.from(new Set(surveyAssignments.flatMap(({ metrics }) => metrics.flatMap(metric => metric.source.kind === 'survey' ? [metric.source.templateCode] : [])))) const where = surveyFilter(sourceMonth) try { const responses = await prisma.performanceSurveyResponse.findMany({ where: { ...where, target: { employeeProfileId: { in: surveyTargets } }, survey: { ...where.survey, templateCode: { in: surveyCodes } }, }, select: surveyFields, }) scores.set(sourceMonth, collectSalarySurveyScores(responses)) } catch (error) { if (!scope) throw error for (const state of surveyStates.filter(state => state.sourceMonth === sourceMonth)) recordSource('survey', state, 'failed', error) } })) }) : undefined const snapshots = wantsDelivery || wantsMarket ? readSalaryWorkflowSnapshots(!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', deliveryStates, 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', marketStates, 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 marketStates.filter(state => previousSalaryMonth(state.displayMonth) === month)) recordSource('market-intent-top3', state, 'failed', error) } : undefined, scope?.signal) }) : undefined function calculateMonth(state: MonthState): SalaryDetails { const { assigned, groupPositions } = assignments.get(state.displayMonth)! 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() const surveyMatchIssues: NonNullable = [] const pointsMatchIssues: NonNullable = [] const pointResult = pointsByMonth.get(state.displayMonth) const departmentMatchIssues: NonNullable = [] 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 artOnlyDelivery = base.positionId === CREATIVE_MANAGER_POSITION_ID || base.positionId === CREATIVE_PLANNING_POSITION_ID const deliveryCounts = artOnlyDelivery ? workflows.artDeliveryCounts : workflows.deliveryCounts 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, deliveryCounts, artOnlyDelivery ? 'art-only' : undefined) : 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') { const artCounts = artOnlyDelivery ? deliveryCounts.get(base.employeeProfileId) : undefined const personalRate = artOnlyDelivery ? artCounts ? artCounts.onTime / artCounts.total * 100 : null : workflows.onTimeRates.get(base.employeeProfileId) ?? null row.metrics[metric.id] = !ready('on-time') ? null : deliveryEvidence ? deliveryEvidence.rawScore : personalRate 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]) scope?.signal?.throwIfAborted() return buildResult('full') }