1050 lines
33 KiB
TypeScript
1050 lines
33 KiB
TypeScript
import { randomUUID } from 'crypto'
|
|
import type { Session } from 'next-auth'
|
|
import { prisma } from '@/lib/prisma'
|
|
import {
|
|
calculateAggregateScore,
|
|
calculateResponseScores,
|
|
getPerformanceSurveyTemplate,
|
|
listPerformanceSurveyTemplates,
|
|
type PerformanceSurveyTemplateShape,
|
|
} from '@/lib/performance-survey-templates'
|
|
import {
|
|
ensurePerformanceSurveyNotificationWorkerStarted,
|
|
queueDuePerformanceSurveyReminders,
|
|
queueSurveyAssignmentNotifications,
|
|
queueSurveyCreatorNotification,
|
|
queueSurveyResultNotifications,
|
|
recoverDuePerformanceSurveyNotifications,
|
|
retryPerformanceSurveyNotification,
|
|
} from '@/lib/performance-survey-notifications'
|
|
import {
|
|
ensurePerformanceSurveyDailyEmployeeSyncStarted,
|
|
ensurePerformanceSurveyEmployeeProfileForUser,
|
|
syncPerformanceSurveyEmployees,
|
|
} from '@/lib/performance-survey-report-sync'
|
|
|
|
export class PerformanceSurveyApiError extends Error {
|
|
status: number
|
|
|
|
constructor(message: string, status = 400) {
|
|
super(message)
|
|
this.status = status
|
|
}
|
|
}
|
|
|
|
type UserContext = {
|
|
user: {
|
|
id: string
|
|
username: string
|
|
email: string
|
|
role: string
|
|
department: string | null
|
|
managedDepartment: string | null
|
|
isSuperAdmin: boolean
|
|
dingtalkUserId: string | null
|
|
realName: string | null
|
|
}
|
|
employee: any | null
|
|
isSystemAdmin: boolean
|
|
isDepartmentAdmin: boolean
|
|
isLeadership: boolean
|
|
scopeDepartment: string | null
|
|
evaluatorKey: string
|
|
}
|
|
|
|
function clean(value: unknown) {
|
|
const normalized = String(value ?? '').trim()
|
|
return normalized.length > 0 ? normalized : null
|
|
}
|
|
|
|
function normalizeList(value: unknown): string[] {
|
|
if (!Array.isArray(value)) return []
|
|
return Array.from(new Set(value.map((item) => clean(item)).filter((item): item is string => Boolean(item))))
|
|
}
|
|
|
|
function toDate(value: unknown) {
|
|
const normalized = clean(value)
|
|
if (!normalized) return null
|
|
const date = new Date(normalized)
|
|
return Number.isNaN(date.getTime()) ? null : date
|
|
}
|
|
|
|
function getDisplayName(user: { username: string; realName?: string | null }) {
|
|
return clean(user.realName) || clean(user.username) || '未知用户'
|
|
}
|
|
|
|
function getEmployeeDisplayName(employee: any) {
|
|
return clean(employee?.displayName) || clean(employee?.flowerName) || clean(employee?.realName) || clean(employee?.jobNumber) || '未知员工'
|
|
}
|
|
|
|
function getEmployeeSnapshot(employee: any) {
|
|
if (!employee) return {}
|
|
return {
|
|
id: employee.id,
|
|
dingtalkUserId: employee.dingtalkUserId,
|
|
dingEmail: employee.dingEmail,
|
|
jobNumber: employee.jobNumber,
|
|
flowerName: employee.flowerName,
|
|
realName: employee.realName,
|
|
displayName: employee.displayName,
|
|
departmentName: employee.departmentName,
|
|
departmentPath: employee.departmentPath,
|
|
positionTitle: employee.positionTitle,
|
|
positionLevel: employee.positionLevel,
|
|
levelType: employee.levelType,
|
|
isLeadership: employee.isLeadership,
|
|
managerDingtalkUserId: employee.managerDingtalkUserId,
|
|
managerJobNumber: employee.managerJobNumber,
|
|
managerName: employee.managerName,
|
|
employmentStatus: employee.employmentStatus,
|
|
workPlace: employee.workPlace,
|
|
snapshotAt: new Date().toISOString(),
|
|
}
|
|
}
|
|
|
|
function getEvaluatorKey(input: {
|
|
employeeId?: string | null
|
|
userId?: string | null
|
|
dingtalkUserId?: string | null
|
|
}) {
|
|
if (input.dingtalkUserId) return `ding:${input.dingtalkUserId}`
|
|
if (input.userId) return `user:${input.userId}`
|
|
if (input.employeeId) return `employee:${input.employeeId}`
|
|
return `unknown:${randomUUID()}`
|
|
}
|
|
|
|
function ensureManager(ctx: UserContext) {
|
|
if (!ctx.isDepartmentAdmin) {
|
|
throw new PerformanceSurveyApiError('无权限管理考核调研', 403)
|
|
}
|
|
}
|
|
|
|
function isLeadershipProfile(employee: any) {
|
|
const levelType = clean(employee?.levelType)?.toUpperCase()
|
|
const positionLevel = clean(employee?.positionLevel)?.toUpperCase()
|
|
return Boolean(employee?.isLeadership || levelType === 'M' || positionLevel?.startsWith('M'))
|
|
}
|
|
|
|
function isSurveyInManagerScope(ctx: UserContext, survey: { creatorUserId: string; departmentName?: string | null }) {
|
|
if (ctx.isSystemAdmin) return true
|
|
if (survey.creatorUserId === ctx.user.id) return true
|
|
if (!ctx.scopeDepartment) return false
|
|
return survey.departmentName === ctx.scopeDepartment
|
|
}
|
|
|
|
function ensureSurveyManageScope(ctx: UserContext, survey: { creatorUserId: string; departmentName?: string | null }) {
|
|
if (!isSurveyInManagerScope(ctx, survey)) {
|
|
throw new PerformanceSurveyApiError('无权限管理该考核调研', 403)
|
|
}
|
|
}
|
|
|
|
export async function getPerformanceSurveyContext(session: Session | null): Promise<UserContext> {
|
|
ensurePerformanceSurveyNotificationWorkerStarted()
|
|
ensurePerformanceSurveyDailyEmployeeSyncStarted()
|
|
|
|
const sessionUserId = (session?.user as any)?.id
|
|
if (!sessionUserId) {
|
|
throw new PerformanceSurveyApiError('请先登录', 401)
|
|
}
|
|
|
|
const user = await prisma.user.findUnique({
|
|
where: { id: sessionUserId },
|
|
select: {
|
|
id: true,
|
|
username: true,
|
|
email: true,
|
|
role: true,
|
|
department: true,
|
|
managedDepartment: true,
|
|
isSuperAdmin: true,
|
|
dingtalkUserId: true,
|
|
realName: true,
|
|
},
|
|
})
|
|
|
|
if (!user) {
|
|
throw new PerformanceSurveyApiError('登录用户不存在', 401)
|
|
}
|
|
|
|
const employee = await ensurePerformanceSurveyEmployeeProfileForUser({
|
|
userId: user.id,
|
|
dingtalkUserId: user.dingtalkUserId,
|
|
email: user.email,
|
|
username: user.username,
|
|
realName: user.realName,
|
|
displayName: getDisplayName(user),
|
|
})
|
|
|
|
const isSystemAdmin = Boolean(user.isSuperAdmin || user.role === 'ADMIN' || user.role === 'SYSTEM_ADMIN')
|
|
const isLeadership = isLeadershipProfile(employee)
|
|
const isDepartmentAdmin = Boolean(isSystemAdmin || user.role === 'DEPT_ADMIN' || isLeadership)
|
|
const scopeDepartment = clean(user.managedDepartment) || clean(employee?.departmentName) || clean(user.department)
|
|
|
|
return {
|
|
user,
|
|
employee,
|
|
isSystemAdmin,
|
|
isDepartmentAdmin,
|
|
isLeadership,
|
|
scopeDepartment,
|
|
evaluatorKey: getEvaluatorKey({
|
|
employeeId: employee?.id,
|
|
userId: user.id,
|
|
dingtalkUserId: user.dingtalkUserId,
|
|
}),
|
|
}
|
|
}
|
|
|
|
export async function getPerformanceSurveyMe(session: Session | null) {
|
|
const ctx = await getPerformanceSurveyContext(session)
|
|
return {
|
|
user: {
|
|
id: ctx.user.id,
|
|
name: getDisplayName(ctx.user),
|
|
email: ctx.user.email,
|
|
role: ctx.user.role,
|
|
department: ctx.user.department,
|
|
managedDepartment: ctx.user.managedDepartment,
|
|
dingtalkUserId: ctx.user.dingtalkUserId,
|
|
},
|
|
employee: ctx.employee ? getEmployeeSnapshot(ctx.employee) : null,
|
|
permissions: {
|
|
isSystemAdmin: ctx.isSystemAdmin,
|
|
isDepartmentAdmin: ctx.isDepartmentAdmin,
|
|
isLeadership: ctx.isLeadership,
|
|
scopeDepartment: ctx.scopeDepartment,
|
|
},
|
|
}
|
|
}
|
|
|
|
export async function getPerformanceSurveyTemplates(session: Session | null) {
|
|
await getPerformanceSurveyContext(session)
|
|
return listPerformanceSurveyTemplates()
|
|
}
|
|
|
|
export async function searchPerformanceSurveyEmployees(session: Session | null, params: URLSearchParams) {
|
|
const ctx = await getPerformanceSurveyContext(session)
|
|
if (!ctx.isDepartmentAdmin) {
|
|
if (!ctx.employee) return []
|
|
return [serializeEmployee(ctx.employee)]
|
|
}
|
|
|
|
const search = clean(params.get('search')) || ''
|
|
const department = clean(params.get('department'))
|
|
const limit = Math.max(1, Math.min(Number(params.get('limit') || 50), 200))
|
|
|
|
const where: any = {}
|
|
if (department) where.departmentName = department
|
|
if (!ctx.isSystemAdmin && ctx.scopeDepartment) {
|
|
where.departmentName = ctx.scopeDepartment
|
|
}
|
|
if (search) {
|
|
where.OR = [
|
|
{ displayName: { contains: search, mode: 'insensitive' } },
|
|
{ flowerName: { contains: search, mode: 'insensitive' } },
|
|
{ realName: { contains: search, mode: 'insensitive' } },
|
|
{ jobNumber: { contains: search, mode: 'insensitive' } },
|
|
{ dingEmail: { contains: search, mode: 'insensitive' } },
|
|
{ departmentName: { contains: search, mode: 'insensitive' } },
|
|
{ positionLevel: { contains: search, mode: 'insensitive' } },
|
|
{ levelType: { contains: search, mode: 'insensitive' } },
|
|
{ managerName: { contains: search, mode: 'insensitive' } },
|
|
]
|
|
}
|
|
|
|
const employees = await prisma.performanceSurveyEmployeeProfile.findMany({
|
|
where,
|
|
orderBy: [{ departmentName: 'asc' }, { displayName: 'asc' }],
|
|
take: limit,
|
|
})
|
|
|
|
return employees.map(serializeEmployee)
|
|
}
|
|
|
|
export async function listPerformanceSurveyDepartments(session: Session | null) {
|
|
const ctx = await getPerformanceSurveyContext(session)
|
|
ensureManager(ctx)
|
|
|
|
const where =
|
|
!ctx.isSystemAdmin && ctx.scopeDepartment
|
|
? { name: ctx.scopeDepartment }
|
|
: undefined
|
|
|
|
const departments = await prisma.performanceSurveyDepartmentProfile.findMany({
|
|
where,
|
|
orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }],
|
|
})
|
|
|
|
if (departments.length > 0) {
|
|
return departments.map((department) => ({
|
|
id: department.id,
|
|
name: department.name,
|
|
parentName: department.parentName,
|
|
employeeCount: department.employeeCount,
|
|
syncedAt: department.syncedAt,
|
|
}))
|
|
}
|
|
|
|
const grouped = await prisma.performanceSurveyEmployeeProfile.groupBy({
|
|
by: ['departmentName'],
|
|
where: {
|
|
departmentName: ctx.isSystemAdmin
|
|
? { not: null }
|
|
: ctx.scopeDepartment
|
|
? ctx.scopeDepartment
|
|
: { not: null },
|
|
} as any,
|
|
_count: { _all: true },
|
|
orderBy: { departmentName: 'asc' },
|
|
})
|
|
|
|
return grouped
|
|
.filter((item) => item.departmentName)
|
|
.map((item) => ({
|
|
id: item.departmentName!,
|
|
name: item.departmentName!,
|
|
parentName: null,
|
|
employeeCount: item._count._all,
|
|
syncedAt: null,
|
|
}))
|
|
}
|
|
|
|
export async function listPerformanceSurveys(session: Session | null) {
|
|
const ctx = await getPerformanceSurveyContext(session)
|
|
|
|
const pendingAssignments = await prisma.performanceSurveyAssignment.findMany({
|
|
where: {
|
|
evaluatorKey: ctx.evaluatorKey,
|
|
},
|
|
include: {
|
|
survey: true,
|
|
target: true,
|
|
},
|
|
orderBy: { createdAt: 'desc' },
|
|
take: 100,
|
|
})
|
|
|
|
const managerWhere = ctx.isDepartmentAdmin
|
|
? ctx.isSystemAdmin
|
|
? {}
|
|
: {
|
|
OR: [
|
|
{ creatorUserId: ctx.user.id },
|
|
...(ctx.scopeDepartment ? [{ departmentName: ctx.scopeDepartment }] : []),
|
|
],
|
|
}
|
|
: { creatorUserId: ctx.user.id }
|
|
|
|
const createdSurveys = await prisma.performanceSurvey.findMany({
|
|
where: managerWhere as any,
|
|
include: {
|
|
_count: {
|
|
select: { targets: true, assignments: true, responses: true },
|
|
},
|
|
},
|
|
orderBy: { createdAt: 'desc' },
|
|
take: 100,
|
|
})
|
|
|
|
const resultTargets = ctx.employee
|
|
? await prisma.performanceSurveyTarget.findMany({
|
|
where: {
|
|
employeeProfileId: ctx.employee.id,
|
|
survey: { status: 'closed' },
|
|
},
|
|
include: { survey: true },
|
|
orderBy: { createdAt: 'desc' },
|
|
take: 100,
|
|
})
|
|
: []
|
|
|
|
return {
|
|
pending: pendingAssignments.map((assignment) => ({
|
|
assignmentId: assignment.id,
|
|
surveyId: assignment.surveyId,
|
|
targetId: assignment.targetId,
|
|
title: assignment.survey.title,
|
|
status: assignment.status,
|
|
surveyStatus: assignment.survey.status,
|
|
dueAt: assignment.survey.dueAt,
|
|
targetName: assignment.target.targetName,
|
|
templateCode: assignment.survey.templateCode,
|
|
submittedAt: assignment.submittedAt,
|
|
})),
|
|
created: createdSurveys.map((survey) => ({
|
|
id: survey.id,
|
|
title: survey.title,
|
|
description: survey.description,
|
|
surveyKind: survey.surveyKind,
|
|
templateCode: survey.templateCode,
|
|
status: survey.status,
|
|
departmentName: survey.departmentName,
|
|
dueAt: survey.dueAt,
|
|
openedAt: survey.openedAt,
|
|
closedAt: survey.closedAt,
|
|
createdAt: survey.createdAt,
|
|
counts: survey._count,
|
|
})),
|
|
results: resultTargets.map((target) => ({
|
|
surveyId: target.surveyId,
|
|
targetId: target.id,
|
|
title: target.survey.title,
|
|
targetName: target.targetName,
|
|
closedAt: target.survey.closedAt,
|
|
})),
|
|
permissions: {
|
|
isSystemAdmin: ctx.isSystemAdmin,
|
|
isDepartmentAdmin: ctx.isDepartmentAdmin,
|
|
scopeDepartment: ctx.scopeDepartment,
|
|
},
|
|
}
|
|
}
|
|
|
|
export async function createPerformanceSurvey(session: Session | null, body: any) {
|
|
const ctx = await getPerformanceSurveyContext(session)
|
|
ensureManager(ctx)
|
|
|
|
const title = clean(body?.title)
|
|
if (!title) throw new PerformanceSurveyApiError('调研标题不能为空')
|
|
|
|
const templateCode = clean(body?.templateCode) || 'cross_department'
|
|
const template = await getPerformanceSurveyTemplate(templateCode)
|
|
const surveyKind = clean(body?.surveyKind) || template.surveyType
|
|
const dueAt = toDate(body?.dueAt)
|
|
const openNow = Boolean(body?.openNow || body?.status === 'open')
|
|
const departmentName = clean(body?.departmentName) || ctx.scopeDepartment
|
|
|
|
if (!ctx.isSystemAdmin && ctx.scopeDepartment && departmentName !== ctx.scopeDepartment) {
|
|
throw new PerformanceSurveyApiError('部门管理员只能创建本部门考核调研', 403)
|
|
}
|
|
|
|
const targets = await resolveSurveyTargets(body, surveyKind)
|
|
if (targets.length === 0) {
|
|
throw new PerformanceSurveyApiError('请至少选择 1 个考核对象')
|
|
}
|
|
|
|
const evaluators = await resolveSurveyEvaluators(body, ctx)
|
|
if (evaluators.length === 0) {
|
|
throw new PerformanceSurveyApiError('请至少选择 1 个评价人')
|
|
}
|
|
|
|
const surveyId = randomUUID()
|
|
const targetRows = targets.map((target: any, index: number) => ({
|
|
id: randomUUID(),
|
|
surveyId,
|
|
targetType: target.targetType,
|
|
employeeProfileId: target.employee?.id || null,
|
|
targetName: target.targetName,
|
|
targetSnapshot: target.employee ? getEmployeeSnapshot(target.employee) : target.snapshot,
|
|
sortOrder: index,
|
|
}))
|
|
|
|
const assignmentRows: any[] = []
|
|
for (const target of targetRows) {
|
|
for (const evaluator of evaluators) {
|
|
if (
|
|
surveyKind === 'person_period' &&
|
|
target.employeeProfileId &&
|
|
evaluator.employee?.id === target.employeeProfileId
|
|
) {
|
|
continue
|
|
}
|
|
|
|
assignmentRows.push({
|
|
id: randomUUID(),
|
|
surveyId,
|
|
targetId: target.id,
|
|
evaluatorEmployeeId: evaluator.employee?.id || null,
|
|
evaluatorUserId: evaluator.userId || null,
|
|
evaluatorDingtalkUserId: evaluator.dingtalkUserId || null,
|
|
evaluatorKey: evaluator.evaluatorKey,
|
|
evaluatorName: evaluator.name,
|
|
evaluatorSnapshot: evaluator.employee ? getEmployeeSnapshot(evaluator.employee) : evaluator.snapshot,
|
|
status: 'pending',
|
|
})
|
|
}
|
|
}
|
|
|
|
if (assignmentRows.length === 0) {
|
|
throw new PerformanceSurveyApiError('评价人不能全部等于被考核人,请调整评价范围')
|
|
}
|
|
|
|
await prisma.$transaction(async (tx) => {
|
|
await tx.performanceSurvey.create({
|
|
data: {
|
|
id: surveyId,
|
|
title,
|
|
description: clean(body?.description),
|
|
surveyKind,
|
|
templateCode: template.code,
|
|
templateSnapshot: template as any,
|
|
status: openNow ? 'open' : 'draft',
|
|
creatorUserId: ctx.user.id,
|
|
creatorName: getDisplayName(ctx.user),
|
|
creatorEmployeeId: ctx.employee?.id || null,
|
|
departmentName,
|
|
dueAt,
|
|
openedAt: openNow ? new Date() : null,
|
|
},
|
|
})
|
|
await tx.performanceSurveyTarget.createMany({ data: targetRows })
|
|
await tx.performanceSurveyAssignment.createMany({ data: assignmentRows, skipDuplicates: true })
|
|
})
|
|
|
|
if (openNow) {
|
|
await queueSurveyAssignmentNotifications(surveyId)
|
|
}
|
|
|
|
return getPerformanceSurveyDetail(session, surveyId)
|
|
}
|
|
|
|
export async function getPerformanceSurveyDetail(session: Session | null, surveyId: string) {
|
|
const ctx = await getPerformanceSurveyContext(session)
|
|
const survey = await prisma.performanceSurvey.findUnique({
|
|
where: { id: surveyId },
|
|
include: {
|
|
targets: {
|
|
orderBy: { sortOrder: 'asc' },
|
|
include: {
|
|
assignments: {
|
|
select: {
|
|
id: true,
|
|
evaluatorName: true,
|
|
evaluatorEmployeeId: true,
|
|
status: true,
|
|
submittedAt: true,
|
|
},
|
|
orderBy: { createdAt: 'asc' },
|
|
},
|
|
responses: true,
|
|
},
|
|
},
|
|
assignments: {
|
|
where: { evaluatorKey: ctx.evaluatorKey },
|
|
},
|
|
_count: {
|
|
select: { assignments: true, responses: true, targets: true },
|
|
},
|
|
},
|
|
})
|
|
|
|
if (!survey) {
|
|
throw new PerformanceSurveyApiError('调研不存在或无权限', 404)
|
|
}
|
|
|
|
const isAssigned = survey.assignments.length > 0
|
|
const canManage = ctx.isDepartmentAdmin && isSurveyInManagerScope(ctx, survey)
|
|
const isTarget = Boolean(
|
|
ctx.employee && survey.targets.some((target) => target.employeeProfileId === ctx.employee?.id),
|
|
)
|
|
|
|
if (!canManage && !isAssigned && !isTarget && survey.creatorUserId !== ctx.user.id) {
|
|
throw new PerformanceSurveyApiError('调研不存在或无权限', 404)
|
|
}
|
|
|
|
const currentAssignments = new Map(survey.assignments.map((assignment) => [assignment.targetId, assignment]))
|
|
|
|
return {
|
|
id: survey.id,
|
|
title: survey.title,
|
|
description: survey.description,
|
|
surveyKind: survey.surveyKind,
|
|
templateCode: survey.templateCode,
|
|
template: survey.templateSnapshot,
|
|
status: survey.status,
|
|
creatorName: survey.creatorName,
|
|
departmentName: survey.departmentName,
|
|
dueAt: survey.dueAt,
|
|
openedAt: survey.openedAt,
|
|
closedAt: survey.closedAt,
|
|
counts: survey._count,
|
|
canManage,
|
|
canSubmit: isAssigned && survey.status === 'open',
|
|
canViewResults: canManage || survey.creatorUserId === ctx.user.id || (survey.status === 'closed' && isTarget),
|
|
targets: survey.targets.map((target) => {
|
|
const currentAssignment = currentAssignments.get(target.id)
|
|
return {
|
|
id: target.id,
|
|
targetType: target.targetType,
|
|
targetName: target.targetName,
|
|
targetSnapshot: target.targetSnapshot,
|
|
responseCount: target.responses.length,
|
|
assignmentCount: target.assignments.length,
|
|
currentAssignment: currentAssignment
|
|
? {
|
|
id: currentAssignment.id,
|
|
status: currentAssignment.status,
|
|
submittedAt: currentAssignment.submittedAt,
|
|
}
|
|
: null,
|
|
assignments: canManage
|
|
? target.assignments.map((assignment) => ({
|
|
id: assignment.id,
|
|
evaluatorName: assignment.evaluatorName,
|
|
status: assignment.status,
|
|
submittedAt: assignment.submittedAt,
|
|
}))
|
|
: [],
|
|
}
|
|
}),
|
|
}
|
|
}
|
|
|
|
export async function updatePerformanceSurvey(session: Session | null, surveyId: string, body: any) {
|
|
const ctx = await getPerformanceSurveyContext(session)
|
|
ensureManager(ctx)
|
|
|
|
const survey = await prisma.performanceSurvey.findUnique({ where: { id: surveyId } })
|
|
if (!survey) throw new PerformanceSurveyApiError('调研不存在', 404)
|
|
ensureSurveyManageScope(ctx, survey)
|
|
|
|
const nextStatus = clean(body?.status)
|
|
const data: any = {}
|
|
|
|
if (body?.title != null) data.title = clean(body.title) || survey.title
|
|
if (body?.description !== undefined) data.description = clean(body.description)
|
|
if (body?.dueAt !== undefined) data.dueAt = toDate(body.dueAt)
|
|
|
|
if (nextStatus === 'open' && survey.status === 'draft') {
|
|
data.status = 'open'
|
|
data.openedAt = new Date()
|
|
} else if (nextStatus === 'closed' && survey.status !== 'closed') {
|
|
data.status = 'closed'
|
|
data.closedAt = new Date()
|
|
} else if (nextStatus && !['draft', 'open', 'closed'].includes(nextStatus)) {
|
|
throw new PerformanceSurveyApiError('无效的调研状态')
|
|
}
|
|
|
|
await prisma.performanceSurvey.update({
|
|
where: { id: surveyId },
|
|
data,
|
|
})
|
|
|
|
if (data.status === 'open') {
|
|
await queueSurveyAssignmentNotifications(surveyId)
|
|
}
|
|
if (data.status === 'closed') {
|
|
await queueSurveyResultNotifications(surveyId)
|
|
await queueSurveyCreatorNotification(surveyId, 'survey.creator.closed')
|
|
}
|
|
|
|
return getPerformanceSurveyDetail(session, surveyId)
|
|
}
|
|
|
|
export async function submitPerformanceSurveyResponse(session: Session | null, surveyId: string, body: any) {
|
|
const ctx = await getPerformanceSurveyContext(session)
|
|
const targetId = clean(body?.targetId)
|
|
if (!targetId) throw new PerformanceSurveyApiError('缺少评价对象')
|
|
|
|
const survey = await prisma.performanceSurvey.findUnique({
|
|
where: { id: surveyId },
|
|
})
|
|
if (!survey) throw new PerformanceSurveyApiError('调研不存在', 404)
|
|
if (survey.status !== 'open') throw new PerformanceSurveyApiError('调研未开放或已关闭')
|
|
if (survey.dueAt && survey.dueAt.getTime() < Date.now()) {
|
|
throw new PerformanceSurveyApiError('调研已超过截止时间')
|
|
}
|
|
|
|
const assignment = await prisma.performanceSurveyAssignment.findFirst({
|
|
where: {
|
|
surveyId,
|
|
targetId,
|
|
evaluatorKey: ctx.evaluatorKey,
|
|
},
|
|
include: {
|
|
target: true,
|
|
response: true,
|
|
},
|
|
})
|
|
|
|
if (!assignment) throw new PerformanceSurveyApiError('你没有该评价对象的填写权限', 403)
|
|
if (assignment.response || assignment.status === 'submitted') {
|
|
throw new PerformanceSurveyApiError('你已经提交过该评价,不能重复提交')
|
|
}
|
|
|
|
const template = survey.templateSnapshot as PerformanceSurveyTemplateShape
|
|
const scoreResult = calculateResponseScores(template, body?.scores || {})
|
|
|
|
const response = await prisma.$transaction(async (tx) => {
|
|
const created = await tx.performanceSurveyResponse.create({
|
|
data: {
|
|
id: randomUUID(),
|
|
surveyId,
|
|
targetId,
|
|
assignmentId: assignment.id,
|
|
respondentUserId: ctx.user.id,
|
|
respondentEmployeeId: ctx.employee?.id || null,
|
|
respondentName: getDisplayName(ctx.user),
|
|
respondentSnapshot: ctx.employee
|
|
? getEmployeeSnapshot(ctx.employee)
|
|
: {
|
|
userId: ctx.user.id,
|
|
displayName: getDisplayName(ctx.user),
|
|
departmentName: ctx.user.department,
|
|
snapshotAt: new Date().toISOString(),
|
|
},
|
|
scores: body?.scores || {},
|
|
comment: clean(body?.comment),
|
|
totalScore: scoreResult.totalScore,
|
|
achievementScore: scoreResult.achievementScore,
|
|
kpiScore: scoreResult.kpiScore,
|
|
weightedScore: scoreResult.weightedScore,
|
|
},
|
|
})
|
|
|
|
await tx.performanceSurveyAssignment.update({
|
|
where: { id: assignment.id },
|
|
data: {
|
|
status: 'submitted',
|
|
submittedAt: new Date(),
|
|
},
|
|
})
|
|
|
|
return created
|
|
})
|
|
|
|
const pendingCount = await prisma.performanceSurveyAssignment.count({
|
|
where: { surveyId, status: 'pending' },
|
|
})
|
|
if (pendingCount === 0) {
|
|
await queueSurveyCreatorNotification(surveyId, 'survey.creator.completed')
|
|
}
|
|
|
|
return {
|
|
id: response.id,
|
|
message: '提交成功',
|
|
}
|
|
}
|
|
|
|
export async function getPerformanceSurveyResults(
|
|
session: Session | null,
|
|
surveyId: string,
|
|
params?: URLSearchParams,
|
|
) {
|
|
const ctx = await getPerformanceSurveyContext(session)
|
|
const targetIdFilter = clean(params?.get('targetId'))
|
|
|
|
const survey = await prisma.performanceSurvey.findUnique({
|
|
where: { id: surveyId },
|
|
include: {
|
|
targets: {
|
|
where: targetIdFilter ? { id: targetIdFilter } : undefined,
|
|
orderBy: { sortOrder: 'asc' },
|
|
include: {
|
|
responses: {
|
|
include: {
|
|
assignment: true,
|
|
},
|
|
orderBy: { createdAt: 'asc' },
|
|
},
|
|
},
|
|
},
|
|
_count: {
|
|
select: { assignments: true, responses: true, targets: true },
|
|
},
|
|
},
|
|
})
|
|
|
|
if (!survey) throw new PerformanceSurveyApiError('调研不存在或无权限', 404)
|
|
|
|
const canManage = ctx.isDepartmentAdmin && isSurveyInManagerScope(ctx, survey)
|
|
const isCreator = survey.creatorUserId === ctx.user.id
|
|
const isTarget = Boolean(
|
|
ctx.employee && survey.targets.some((target) => target.employeeProfileId === ctx.employee?.id),
|
|
)
|
|
const canView = canManage || isCreator || (survey.status === 'closed' && isTarget)
|
|
if (!canView) throw new PerformanceSurveyApiError('无权限查看结果', 403)
|
|
if (survey.status !== 'closed' && !canManage) {
|
|
throw new PerformanceSurveyApiError('调研关闭后才能查看结果', 403)
|
|
}
|
|
|
|
const template = survey.templateSnapshot as PerformanceSurveyTemplateShape
|
|
const showRealRespondent = canManage
|
|
|
|
return {
|
|
survey: {
|
|
id: survey.id,
|
|
title: survey.title,
|
|
description: survey.description,
|
|
status: survey.status,
|
|
templateCode: survey.templateCode,
|
|
template,
|
|
dueAt: survey.dueAt,
|
|
closedAt: survey.closedAt,
|
|
counts: survey._count,
|
|
},
|
|
targets: survey.targets.map((target) => {
|
|
const aggregate = calculateAggregateScore(
|
|
target.responses.map((response) => ({
|
|
totalScore: response.totalScore,
|
|
createdAt: response.createdAt,
|
|
})),
|
|
template.scoreBands,
|
|
template.weight,
|
|
)
|
|
|
|
return {
|
|
id: target.id,
|
|
targetType: target.targetType,
|
|
targetName: target.targetName,
|
|
targetSnapshot: target.targetSnapshot,
|
|
aggregate,
|
|
responses: target.responses.map((response, index) => ({
|
|
id: response.id,
|
|
respondentName: showRealRespondent ? response.respondentName : `匿名评价 ${index + 1}`,
|
|
scores: response.scores,
|
|
comment: response.comment,
|
|
totalScore: response.totalScore,
|
|
achievementScore: response.achievementScore,
|
|
kpiScore: response.kpiScore,
|
|
weightedScore: response.weightedScore,
|
|
createdAt: response.createdAt,
|
|
})),
|
|
}
|
|
}),
|
|
permissions: {
|
|
showRealRespondent,
|
|
canManage,
|
|
},
|
|
}
|
|
}
|
|
|
|
export async function syncPerformanceSurveyEmployeeProfiles(session: Session | null, body: any) {
|
|
const ctx = await getPerformanceSurveyContext(session)
|
|
if (!ctx.isSystemAdmin) throw new PerformanceSurveyApiError('需要系统管理员权限', 403)
|
|
const result = await syncPerformanceSurveyEmployees({ limit: Number(body?.limit || 3000) })
|
|
return result
|
|
}
|
|
|
|
export async function exportPerformanceSurveyCsv(session: Session | null) {
|
|
const ctx = await getPerformanceSurveyContext(session)
|
|
ensureManager(ctx)
|
|
|
|
const where = ctx.isSystemAdmin
|
|
? {}
|
|
: {
|
|
OR: [
|
|
{ creatorUserId: ctx.user.id },
|
|
...(ctx.scopeDepartment ? [{ departmentName: ctx.scopeDepartment }] : []),
|
|
],
|
|
}
|
|
|
|
const responses = await prisma.performanceSurveyResponse.findMany({
|
|
where: {
|
|
survey: where as any,
|
|
},
|
|
include: {
|
|
survey: true,
|
|
target: true,
|
|
assignment: true,
|
|
},
|
|
orderBy: { createdAt: 'desc' },
|
|
take: 5000,
|
|
})
|
|
|
|
const rows = [
|
|
['调研ID', '调研标题', '状态', '评价对象', '评价人', '总分', 'KPI分', '加权分', '提交时间', '评论'],
|
|
...responses.map((response) => [
|
|
response.surveyId,
|
|
response.survey.title,
|
|
response.survey.status,
|
|
response.target.targetName,
|
|
response.respondentName,
|
|
String(response.totalScore),
|
|
String(response.kpiScore),
|
|
String(response.weightedScore),
|
|
response.createdAt.toISOString(),
|
|
response.comment || '',
|
|
]),
|
|
]
|
|
|
|
return rows.map((row) => row.map(escapeCsv).join(',')).join('\n')
|
|
}
|
|
|
|
export async function listPerformanceSurveyNotifications(session: Session | null, params: URLSearchParams) {
|
|
const ctx = await getPerformanceSurveyContext(session)
|
|
ensureManager(ctx)
|
|
|
|
const status = clean(params.get('status'))
|
|
const limit = Math.max(1, Math.min(Number(params.get('limit') || 50), 200))
|
|
const where: any = {}
|
|
if (status && status !== 'all') where.status = status
|
|
|
|
if (!ctx.isSystemAdmin && ctx.scopeDepartment) {
|
|
where.survey = { departmentName: ctx.scopeDepartment }
|
|
}
|
|
|
|
const notifications = await prisma.performanceSurveyNotification.findMany({
|
|
where,
|
|
orderBy: { createdAt: 'desc' },
|
|
take: limit,
|
|
})
|
|
|
|
return notifications.map((item) => ({
|
|
id: item.id,
|
|
surveyId: item.surveyId,
|
|
recipientName: item.recipientName,
|
|
eventType: item.eventType,
|
|
title: item.title,
|
|
status: item.status,
|
|
attemptCount: item.attemptCount,
|
|
maxAttempts: item.maxAttempts,
|
|
nextRetryAt: item.nextRetryAt,
|
|
lastError: item.lastError,
|
|
sentAt: item.sentAt,
|
|
completedAt: item.completedAt,
|
|
createdAt: item.createdAt,
|
|
}))
|
|
}
|
|
|
|
export async function retryPerformanceSurveyNotificationById(session: Session | null, notificationId: string) {
|
|
const ctx = await getPerformanceSurveyContext(session)
|
|
ensureManager(ctx)
|
|
const notification = await prisma.performanceSurveyNotification.findUnique({
|
|
where: { id: notificationId },
|
|
include: { survey: true },
|
|
})
|
|
if (!notification) throw new PerformanceSurveyApiError('通知记录不存在', 404)
|
|
if (notification.survey && !isSurveyInManagerScope(ctx, notification.survey)) {
|
|
throw new PerformanceSurveyApiError('无权限补发该通知', 403)
|
|
}
|
|
await retryPerformanceSurveyNotification(notificationId)
|
|
return { message: '已加入补发队列' }
|
|
}
|
|
|
|
export async function runPerformanceSurveyNotificationMaintenance(session: Session | null) {
|
|
const ctx = await getPerformanceSurveyContext(session)
|
|
ensureManager(ctx)
|
|
const reminderIds = await queueDuePerformanceSurveyReminders()
|
|
const recovered = await recoverDuePerformanceSurveyNotifications()
|
|
return { reminderCount: reminderIds.length, recovered }
|
|
}
|
|
|
|
async function resolveSurveyTargets(body: any, surveyKind: string) {
|
|
const targetEmployeeIds = normalizeList(body?.targetEmployeeIds)
|
|
const itemTargets = Array.isArray(body?.targetItems)
|
|
? body.targetItems
|
|
.map((item: any) => ({
|
|
targetType: 'item',
|
|
targetName: clean(item?.name || item?.targetName),
|
|
snapshot: {
|
|
name: clean(item?.name || item?.targetName),
|
|
description: clean(item?.description),
|
|
snapshotAt: new Date().toISOString(),
|
|
},
|
|
}))
|
|
.filter((item: any) => item.targetName)
|
|
: []
|
|
|
|
const employeeTargets =
|
|
targetEmployeeIds.length > 0
|
|
? await prisma.performanceSurveyEmployeeProfile.findMany({
|
|
where: { id: { in: targetEmployeeIds } },
|
|
})
|
|
: []
|
|
|
|
const targets = employeeTargets.map((employee) => ({
|
|
targetType: 'employee',
|
|
targetName: getEmployeeDisplayName(employee),
|
|
employee,
|
|
snapshot: getEmployeeSnapshot(employee),
|
|
}))
|
|
|
|
if (surveyKind === 'item_course') {
|
|
return [
|
|
...itemTargets,
|
|
...targets,
|
|
]
|
|
}
|
|
|
|
return targets.length > 0 ? targets : itemTargets
|
|
}
|
|
|
|
async function resolveSurveyEvaluators(body: any, ctx: UserContext) {
|
|
const evaluatorEmployeeIds = normalizeList(body?.evaluatorEmployeeIds)
|
|
const evaluatorDepartmentNames = normalizeList(body?.evaluatorDepartmentNames)
|
|
|
|
const or: any[] = []
|
|
if (evaluatorEmployeeIds.length > 0) {
|
|
or.push({ id: { in: evaluatorEmployeeIds } })
|
|
}
|
|
if (evaluatorDepartmentNames.length > 0) {
|
|
or.push({ departmentName: { in: evaluatorDepartmentNames } })
|
|
}
|
|
|
|
if (or.length === 0 && ctx.employee) {
|
|
or.push({ id: ctx.employee.id })
|
|
}
|
|
|
|
const where: any = { OR: or }
|
|
if (!ctx.isSystemAdmin && ctx.scopeDepartment) {
|
|
where.departmentName = ctx.scopeDepartment
|
|
}
|
|
|
|
const employees = or.length > 0
|
|
? await prisma.performanceSurveyEmployeeProfile.findMany({ where, orderBy: { displayName: 'asc' } })
|
|
: []
|
|
|
|
const usersByDing = employees.length > 0
|
|
? await prisma.user.findMany({
|
|
where: {
|
|
dingtalkUserId: {
|
|
in: employees.map((employee) => employee.dingtalkUserId).filter((item): item is string => Boolean(item)),
|
|
},
|
|
},
|
|
select: { id: true, dingtalkUserId: true },
|
|
})
|
|
: []
|
|
const userIdByDing = new Map(usersByDing.map((user) => [user.dingtalkUserId, user.id]))
|
|
|
|
const deduped = new Map<string, any>()
|
|
for (const employee of employees) {
|
|
const dingtalkUserId = employee.dingtalkUserId || null
|
|
const userId = dingtalkUserId ? userIdByDing.get(dingtalkUserId) || null : null
|
|
const evaluatorKey = getEvaluatorKey({
|
|
employeeId: employee.id,
|
|
userId,
|
|
dingtalkUserId,
|
|
})
|
|
deduped.set(evaluatorKey, {
|
|
employee,
|
|
userId,
|
|
dingtalkUserId,
|
|
evaluatorKey,
|
|
name: getEmployeeDisplayName(employee),
|
|
snapshot: getEmployeeSnapshot(employee),
|
|
})
|
|
}
|
|
|
|
return Array.from(deduped.values())
|
|
}
|
|
|
|
function serializeEmployee(employee: any) {
|
|
return {
|
|
id: employee.id,
|
|
dingtalkUserId: employee.dingtalkUserId,
|
|
dingEmail: employee.dingEmail,
|
|
jobNumber: employee.jobNumber,
|
|
flowerName: employee.flowerName,
|
|
realName: employee.realName,
|
|
displayName: employee.displayName,
|
|
departmentName: employee.departmentName,
|
|
departmentPath: employee.departmentPath,
|
|
positionTitle: employee.positionTitle,
|
|
positionLevel: employee.positionLevel,
|
|
levelType: employee.levelType,
|
|
isLeadership: employee.isLeadership,
|
|
managerDingtalkUserId: employee.managerDingtalkUserId,
|
|
managerJobNumber: employee.managerJobNumber,
|
|
managerName: employee.managerName,
|
|
employmentStatus: employee.employmentStatus,
|
|
workPlace: employee.workPlace,
|
|
syncedAt: employee.syncedAt,
|
|
}
|
|
}
|
|
|
|
function escapeCsv(value: string) {
|
|
const text = String(value ?? '')
|
|
return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text
|
|
}
|