gongxiangp2/lib/performance-survey-templates.ts

281 lines
11 KiB
TypeScript

import { prisma } from '@/lib/prisma'
export type PerformanceSurveyQuestion = {
id: string
title: string
description?: string
}
export type PerformanceSurveyScoreBand = {
min: number
max: number
score?: number
outMin?: number
outMax?: number
label?: string
}
export type PerformanceSurveyTemplateShape = {
code: string
name: string
shortName?: string
description: string
surveyType: string
weight: number
weightLabel?: string
maxTotal?: number
achievementLabel?: string
achievementSuffix?: string
questions: PerformanceSurveyQuestion[]
scoreBands: PerformanceSurveyScoreBand[]
}
export const DEFAULT_PERFORMANCE_SURVEY_TEMPLATES: PerformanceSurveyTemplateShape[] = [
{
code: 'course_share',
name: '课程分享满意度调研',
shortName: '课程分享',
description: '适用于课程培训、经验分享、内部活动后的满意度与效果反馈。',
surveyType: 'item_course',
weight: 0.3,
weightLabel: '30%',
maxTotal: 100,
achievementLabel: '满意度',
achievementSuffix: '%',
questions: [
{ id: 'usefulness', title: '内容实用度', description: '听完能用上吗?' },
{ id: 'insight', title: '见解深度', description: '有没有独到洞察?' },
{ id: 'clarity', title: '结构清晰度', description: '听得懂、跟得上吗?' },
{ id: 'caseQuality', title: '案例质量', description: '有真实例支撑吗?' },
{ id: 'interaction', title: '互动参与感', description: '有参与感还是全程被动?' },
],
scoreBands: [
{ min: 95, max: 100, outMin: 100, outMax: 120, label: '满意度 95% 以上,对应 120-100 分' },
{ min: 89, max: 94, outMin: 85, outMax: 100, label: '满意度 94%-89%,对应 100-85 分' },
{ min: 81, max: 88, outMin: 70, outMax: 84, label: '满意度 88%-81%,对应 84-70 分' },
{ min: 77, max: 80, outMin: 60, outMax: 69, label: '满意度 80%-77%,对应 69-60 分' },
],
},
{
code: 'cross_department',
name: '跨部门协同满意度调研',
shortName: '跨部门协同',
description: '适用于跨部门项目、流程配合、协同响应等人员周期考核。',
surveyType: 'person_period',
weight: 0.2,
weightLabel: '20%',
maxTotal: 120,
achievementLabel: '协作得分',
achievementSuffix: '',
questions: [
{ id: 'requirementClarity', title: '需求清晰度', description: '目标、需求与验收口径是否清晰?' },
{ id: 'deliveryStandard', title: '交付规范性', description: '交付物是否规范、完整、可复用?' },
{ id: 'responseSpeed', title: '响应时效性', description: '响应是否及时,关键节点是否不拖延?' },
{ id: 'collaborationFit', title: '协作配合度', description: '跨部门配合是否主动、顺畅?' },
{ id: 'communicationEffect', title: '沟通有效性', description: '信息传递是否准确、减少反复?' },
{ id: 'processControl', title: '过程可控性', description: '过程是否有预警、有节奏、有闭环?' },
],
scoreBands: [
{ min: 100, max: 120, outMin: 100, outMax: 120, label: '非常满意,并给予高度评价,对应 120-100 分' },
{ min: 85, max: 99.9, outMin: 85, outMax: 100, label: '满意,基本达到标准,对应 100-85 分' },
{ min: 70, max: 84.9, outMin: 70, outMax: 84, label: '评价尚可,还有进步空间,对应 84-70 分' },
{ min: 60, max: 69.9, outMin: 60, outMax: 69, label: '评价一般,有较大进步空间,对应 69-60 分' },
],
},
{
code: 'work_cooperation',
name: '工作配合度满意度调研',
shortName: '工作配合度',
description: '适用于常规工作协作、服务支持、团队内互评。',
surveyType: 'person_period',
weight: 0.2,
weightLabel: '20%',
maxTotal: 120,
achievementLabel: '配合度得分',
achievementSuffix: '',
questions: [
{ id: 'executionDepth', title: '执行落实度', description: '交办的事放心吗?' },
{ id: 'ownership', title: '主动担责', description: '推一步走一步还是自己跑?' },
{ id: 'reportCommunication', title: '汇报沟通', description: '进度看得见吗?出事早知道吗?' },
{ id: 'adaptability', title: '灵活应变', description: '变了能不能跟着转?' },
{ id: 'teamAlignment', title: '团队补位', description: '别人忙不过来会搭把手吗?' },
{ id: 'emotionalStability', title: '情绪稳定度', description: '压力下解决问题还是制造情绪?' },
],
scoreBands: [
{ min: 100, max: 120, outMin: 100, outMax: 120, label: '非常满意,并给予高度评价,对应 120-100 分' },
{ min: 85, max: 99.9, outMin: 85, outMax: 100, label: '满意,基本达到标准,对应 100-85 分' },
{ min: 70, max: 84.9, outMin: 70, outMax: 84, label: '评价尚可,还有进步空间,对应 84-70 分' },
{ min: 60, max: 69.9, outMin: 60, outMax: 69, label: '评价一般,有较大进步空间,对应 69-60 分' },
],
},
]
export async function ensurePerformanceSurveyTemplates() {
for (const template of DEFAULT_PERFORMANCE_SURVEY_TEMPLATES) {
await prisma.performanceSurveyTemplate.upsert({
where: { code: template.code },
update: {
name: template.name,
description: template.description,
surveyType: template.surveyType,
weight: template.weight,
questions: template.questions,
scoreBands: template.scoreBands,
isActive: true,
},
create: {
code: template.code,
name: template.name,
description: template.description,
surveyType: template.surveyType,
weight: template.weight,
questions: template.questions,
scoreBands: template.scoreBands,
isActive: true,
},
})
}
}
export async function listPerformanceSurveyTemplates() {
await ensurePerformanceSurveyTemplates()
const templates = await prisma.performanceSurveyTemplate.findMany({
where: { isActive: true },
orderBy: [{ surveyType: 'asc' }, { createdAt: 'asc' }],
})
return templates.map((template) => withDefaultTemplateMeta({
code: template.code,
name: template.name,
description: template.description || '',
surveyType: template.surveyType,
weight: template.weight,
questions: template.questions as PerformanceSurveyQuestion[],
scoreBands: template.scoreBands as PerformanceSurveyScoreBand[],
}))
}
export async function getPerformanceSurveyTemplate(code: string) {
await ensurePerformanceSurveyTemplates()
const template = await prisma.performanceSurveyTemplate.findUnique({
where: { code },
})
if (!template || !template.isActive) {
throw new Error('考核调研模板不存在')
}
return withDefaultTemplateMeta({
code: template.code,
name: template.name,
description: template.description || '',
surveyType: template.surveyType,
weight: template.weight,
questions: template.questions as PerformanceSurveyQuestion[],
scoreBands: template.scoreBands as PerformanceSurveyScoreBand[],
})
}
function withDefaultTemplateMeta(template: PerformanceSurveyTemplateShape): PerformanceSurveyTemplateShape {
const matchedDefault = DEFAULT_PERFORMANCE_SURVEY_TEMPLATES.find((item) => item.code === template.code)
return {
...template,
shortName: matchedDefault?.shortName,
weightLabel: matchedDefault?.weightLabel || `${Math.round(Number(template.weight || 0) * 100)}%`,
maxTotal: matchedDefault?.maxTotal,
achievementLabel: matchedDefault?.achievementLabel,
achievementSuffix: matchedDefault?.achievementSuffix,
}
}
export function calculateResponseScores(
template: Pick<PerformanceSurveyTemplateShape, 'questions' | 'scoreBands' | 'weight'>,
scores: Record<string, unknown>,
) {
const questionScores = template.questions.map((question) => {
const value = Number(scores[question.id])
if (!Number.isFinite(value) || value < 0 || value > 20) {
throw new Error(`评分项「${question.title}」必须是 0-20 分`)
}
return value
})
const totalScore =
questionScores.length > 0
? questionScores.reduce((sum, score) => sum + score, 0)
: 0
const kpiScore = mapAchievementToKpiScore(totalScore, template.scoreBands)
return {
totalScore: roundScore(totalScore),
achievementScore: roundScore(totalScore),
kpiScore: roundScore(kpiScore),
weightedScore: roundScore(kpiScore * Number(template.weight || 1)),
}
}
export function calculateAggregateScore(
responses: Array<{ totalScore: number; createdAt: Date | string }>,
scoreBands: PerformanceSurveyScoreBand[],
weight: number,
) {
const sorted = [...responses].sort((left, right) => {
const scoreDiff = Number(left.totalScore || 0) - Number(right.totalScore || 0)
if (scoreDiff !== 0) return scoreDiff
return new Date(String(left.createdAt)).getTime() - new Date(String(right.createdAt)).getTime()
})
const effective =
sorted.length >= 3
? sorted.slice(1, -1)
: sorted
const achievementScore =
effective.length > 0
? effective.reduce((sum, response) => sum + Number(response.totalScore || 0), 0) / effective.length
: 0
const kpiScore = mapAchievementToKpiScore(achievementScore, scoreBands)
return {
responseCount: responses.length,
effectiveCount: effective.length,
droppedHighestLowest: sorted.length >= 3,
achievementScore: roundScore(achievementScore),
kpiScore: roundScore(kpiScore),
weightedScore: roundScore(kpiScore * Number(weight || 1)),
}
}
function mapAchievementToKpiScore(value: number, bands: PerformanceSurveyScoreBand[]) {
const normalizedBands = [...bands].sort((left, right) => left.min - right.min)
const matched = normalizedBands.find((band) => value >= band.min && value <= band.max)
if (!matched) {
if (value < normalizedBands[0]?.min) return 0
const last = normalizedBands[normalizedBands.length - 1]
return last?.outMax ?? last?.score ?? 0
}
if (matched.outMin != null && matched.outMax != null) {
const ratio = (value - matched.min) / (matched.max - matched.min)
return matched.outMin + ratio * (matched.outMax - matched.outMin)
}
const previous = normalizedBands
.filter((band) => band.max <= matched.min)
.sort((left, right) => right.max - left.max)[0]
if (!previous || matched.max === matched.min) {
return matched.score ?? 0
}
const ratio = (value - matched.min) / (matched.max - matched.min)
return (previous.score ?? 0) + ratio * ((matched.score ?? 0) - (previous.score ?? 0))
}
function roundScore(value: number) {
return Math.round(Number(value || 0) * 100) / 100
}