修复考核调研权限与月度评分规则
This commit is contained in:
parent
993a92dd3f
commit
49cfcf3ff7
404
lib/__tests__/performance-survey-service-policy.test.ts
Normal file
404
lib/__tests__/performance-survey-service-policy.test.ts
Normal file
@ -0,0 +1,404 @@
|
||||
/** @jest-environment node */
|
||||
|
||||
import type { Session } from 'next-auth'
|
||||
import {
|
||||
PerformanceSurveyApiError,
|
||||
createPerformanceSurvey,
|
||||
getPerformanceSurveyDashboardDetail,
|
||||
updatePerformanceSurvey,
|
||||
} from '@/lib/performance-survey-service'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { ensurePerformanceSurveyEmployeeProfileForUser } from '@/lib/performance-survey-report-sync'
|
||||
import { getPerformanceSurveyTemplate } from '@/lib/performance-survey-templates'
|
||||
|
||||
jest.mock('@/lib/prisma', () => ({
|
||||
prisma: {
|
||||
user: { findUnique: jest.fn() },
|
||||
performanceSurvey: {
|
||||
findUnique: jest.fn(),
|
||||
update: jest.fn(),
|
||||
count: jest.fn(),
|
||||
},
|
||||
performanceSurveyTarget: { findMany: jest.fn() },
|
||||
performanceSurveyEmployeeProfile: {
|
||||
findFirst: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
count: jest.fn(),
|
||||
},
|
||||
$transaction: jest.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
jest.mock('@/lib/performance-survey-templates', () => {
|
||||
const actual = jest.requireActual('@/lib/performance-survey-templates')
|
||||
return {
|
||||
...actual,
|
||||
getPerformanceSurveyTemplate: jest.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
jest.mock('@/lib/performance-survey-report-sync', () => ({
|
||||
ensurePerformanceSurveyDailyEmployeeSyncStarted: jest.fn(),
|
||||
ensurePerformanceSurveyEmployeeProfileForUser: jest.fn(),
|
||||
getPerformanceSurveyAccountProfileWhere: jest.fn(async () => ({ id: { not: '__hidden__' } })),
|
||||
syncPerformanceSurveyEmployees: jest.fn(),
|
||||
}))
|
||||
|
||||
jest.mock('@/lib/performance-survey-notifications', () => ({
|
||||
ensurePerformanceSurveyNotificationWorkerStarted: jest.fn(),
|
||||
queueDuePerformanceSurveyReminders: jest.fn(),
|
||||
queueSurveyAssignmentNotifications: jest.fn(),
|
||||
queueSurveyCreatorNotification: jest.fn(),
|
||||
queueSurveyResultNotifications: jest.fn(),
|
||||
queueSurveyTargetConfirmationNotifications: jest.fn(),
|
||||
recoverDuePerformanceSurveyNotifications: jest.fn(),
|
||||
refreshPerformanceSurveyNotificationReadStatuses: jest.fn(),
|
||||
retryPerformanceSurveyNotification: jest.fn(),
|
||||
}))
|
||||
|
||||
jest.mock('@/lib/dingtalk-client', () => ({
|
||||
getDingtalkWorkNoticeConfigStatus: jest.fn(() => ({ configured: true })),
|
||||
}))
|
||||
|
||||
jest.mock('@/lib/s3', () => ({
|
||||
deleteFromS3: jest.fn(),
|
||||
uploadToS3: jest.fn(),
|
||||
}))
|
||||
|
||||
const session = { user: { id: 'user-1' } } as Session
|
||||
|
||||
const baseUser = {
|
||||
id: 'user-1',
|
||||
username: 'tester',
|
||||
email: 'tester@example.com',
|
||||
role: 'USER',
|
||||
department: '策划部',
|
||||
managedDepartment: null,
|
||||
isSuperAdmin: false,
|
||||
dingtalkUserId: 'ding-user-1',
|
||||
realName: '测试人员',
|
||||
avatar: null,
|
||||
}
|
||||
|
||||
const baseEmployee = {
|
||||
id: 'employee-1',
|
||||
displayName: '测试人员',
|
||||
departmentName: '策划部',
|
||||
departmentPath: '集团A/品牌中心/策划部',
|
||||
levelType: 'P',
|
||||
positionLevel: 'P5',
|
||||
isLeadership: false,
|
||||
}
|
||||
|
||||
function buildSurvey(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'survey-1',
|
||||
title: '2026年6月 · 课程分享',
|
||||
description: null,
|
||||
surveyKind: 'person_period',
|
||||
templateCode: 'course_share',
|
||||
templateSnapshot: {
|
||||
code: 'course_share',
|
||||
name: '课程分享月度考核',
|
||||
shortName: '课程分享',
|
||||
questions: [],
|
||||
},
|
||||
status: 'draft',
|
||||
creatorUserId: 'user-1',
|
||||
creatorName: '测试人员',
|
||||
creatorEmployeeId: 'employee-1',
|
||||
departmentName: '策划部',
|
||||
assessmentMonth: '2026-06',
|
||||
dueAt: null,
|
||||
openedAt: null,
|
||||
closedAt: null,
|
||||
createdAt: new Date('2026-06-01T00:00:00.000Z'),
|
||||
targets: [{
|
||||
id: 'target-1',
|
||||
employeeProfileId: 'employee-1',
|
||||
targetType: 'employee',
|
||||
targetName: '测试人员',
|
||||
targetSnapshot: {},
|
||||
responses: [],
|
||||
assignments: [],
|
||||
workItems: [],
|
||||
}],
|
||||
assignments: [],
|
||||
_count: { assignments: 0, responses: 0, targets: 1 },
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
const transactionClient = {
|
||||
$queryRawUnsafe: jest.fn(),
|
||||
performanceSurveyTarget: { findMany: jest.fn(), createMany: jest.fn() },
|
||||
performanceSurvey: { update: jest.fn(), create: jest.fn() },
|
||||
performanceSurveyAssignment: { createMany: jest.fn() },
|
||||
}
|
||||
|
||||
describe('performance survey service policies', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
;(prisma.user.findUnique as jest.Mock).mockResolvedValue(baseUser)
|
||||
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockResolvedValue(baseEmployee)
|
||||
;(prisma.performanceSurvey.findUnique as jest.Mock).mockResolvedValue(buildSurvey())
|
||||
;(prisma.performanceSurvey.update as jest.Mock).mockResolvedValue({})
|
||||
;(prisma.performanceSurveyEmployeeProfile.findFirst as jest.Mock).mockResolvedValue(null)
|
||||
;(prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock).mockResolvedValue([])
|
||||
;(prisma.performanceSurveyEmployeeProfile.count as jest.Mock).mockResolvedValue(0)
|
||||
;(prisma.performanceSurvey.count as jest.Mock).mockResolvedValue(0)
|
||||
;(getPerformanceSurveyTemplate as jest.Mock).mockResolvedValue({
|
||||
code: 'course_share',
|
||||
name: '课程分享月度考核',
|
||||
shortName: '课程分享',
|
||||
description: '',
|
||||
surveyType: 'person_period',
|
||||
weight: 0.3,
|
||||
questions: [],
|
||||
scoreBands: [],
|
||||
})
|
||||
transactionClient.$queryRawUnsafe.mockResolvedValue([{ locked: '' }])
|
||||
transactionClient.performanceSurveyTarget.findMany.mockResolvedValue([])
|
||||
transactionClient.performanceSurveyTarget.createMany.mockResolvedValue({ count: 1 })
|
||||
transactionClient.performanceSurvey.update.mockResolvedValue({})
|
||||
transactionClient.performanceSurvey.create.mockResolvedValue({})
|
||||
transactionClient.performanceSurveyAssignment.createMany.mockResolvedValue({ count: 1 })
|
||||
;(prisma.$transaction as jest.Mock).mockImplementation(async (callback) => callback(transactionClient))
|
||||
})
|
||||
|
||||
test('M级详情权限只按完整组织路径及其子路径判断,不再按重名部门叶子判断', async () => {
|
||||
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockResolvedValue({
|
||||
...baseEmployee,
|
||||
levelType: 'M',
|
||||
positionLevel: 'M1',
|
||||
isLeadership: true,
|
||||
})
|
||||
;(prisma.performanceSurveyEmployeeProfile.findFirst as jest.Mock).mockResolvedValue({
|
||||
id: 'employee-other',
|
||||
displayName: '另一组织员工',
|
||||
departmentName: '策划部',
|
||||
departmentPath: '集团B/品牌中心/策划部',
|
||||
})
|
||||
|
||||
const request = new URLSearchParams({
|
||||
month: '2026-07',
|
||||
employeeId: 'employee-other',
|
||||
templateCode: 'course_share',
|
||||
})
|
||||
|
||||
await expect(getPerformanceSurveyDashboardDetail(session, request)).rejects.toEqual(
|
||||
new PerformanceSurveyApiError('无权限查看该人员考核明细', 403),
|
||||
)
|
||||
|
||||
const scopeWhere = (prisma.performanceSurveyEmployeeProfile.count as jest.Mock).mock.calls[0][0].where.AND[1]
|
||||
expect(scopeWhere).toEqual({
|
||||
OR: [
|
||||
{ departmentPath: '集团A/品牌中心/策划部' },
|
||||
{ departmentPath: { startsWith: '集团A/品牌中心/策划部/' } },
|
||||
],
|
||||
})
|
||||
expect(JSON.stringify(scopeWhere)).not.toContain('departmentName')
|
||||
expect(JSON.stringify(scopeWhere)).not.toContain('contains')
|
||||
expect(JSON.stringify(scopeWhere)).not.toContain('endsWith')
|
||||
})
|
||||
|
||||
test('M级档案缺少完整组织路径时默认拒绝打开他人详情', async () => {
|
||||
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockResolvedValue({
|
||||
...baseEmployee,
|
||||
departmentPath: null,
|
||||
levelType: 'M',
|
||||
positionLevel: 'M1',
|
||||
isLeadership: true,
|
||||
})
|
||||
;(prisma.performanceSurveyEmployeeProfile.findFirst as jest.Mock).mockResolvedValue({
|
||||
id: 'employee-other',
|
||||
displayName: '其他员工',
|
||||
departmentName: '策划部',
|
||||
departmentPath: '集团B/品牌中心/策划部',
|
||||
})
|
||||
|
||||
await expect(getPerformanceSurveyDashboardDetail(session, new URLSearchParams({
|
||||
month: '2026-07',
|
||||
employeeId: 'employee-other',
|
||||
templateCode: 'course_share',
|
||||
}))).rejects.toThrow('无权限查看该人员考核明细')
|
||||
|
||||
expect(prisma.performanceSurveyEmployeeProfile.count).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('M级不会因本组织员工只是评价人而获得整份调研管理权', async () => {
|
||||
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockResolvedValue({
|
||||
...baseEmployee,
|
||||
levelType: 'M',
|
||||
positionLevel: 'M1',
|
||||
isLeadership: true,
|
||||
})
|
||||
;(prisma.performanceSurvey.findUnique as jest.Mock).mockResolvedValue(buildSurvey({
|
||||
creatorUserId: 'user-other',
|
||||
}))
|
||||
|
||||
await expect(
|
||||
updatePerformanceSurvey(session, 'survey-1', { title: '试图越权修改' }),
|
||||
).rejects.toThrow('无权限管理该考核调研')
|
||||
|
||||
const managerScope = (prisma.performanceSurvey.count as jest.Mock).mock.calls[0][0].where.AND[1]
|
||||
expect(managerScope).toEqual({
|
||||
AND: [
|
||||
{ targets: { some: { targetType: 'employee' } } },
|
||||
{
|
||||
targets: {
|
||||
none: {
|
||||
targetType: 'employee',
|
||||
OR: [
|
||||
{ employeeProfileId: null },
|
||||
{
|
||||
employeeProfile: {
|
||||
isNot: {
|
||||
OR: [
|
||||
{ departmentPath: '集团A/品牌中心/策划部' },
|
||||
{ departmentPath: { startsWith: '集团A/品牌中心/策划部/' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
expect(JSON.stringify(managerScope)).not.toContain('assignments')
|
||||
expect(JSON.stringify(managerScope)).not.toContain('evaluatorEmployee')
|
||||
expect(JSON.stringify(managerScope)).not.toContain('creatorEmployeeId')
|
||||
})
|
||||
|
||||
test('固定月度模板拒绝自定义标题覆盖', async () => {
|
||||
await updatePerformanceSurvey(session, 'survey-1', { title: '自定义标题' })
|
||||
|
||||
expect(prisma.performanceSurvey.update).toHaveBeenCalledWith({
|
||||
where: { id: 'survey-1' },
|
||||
data: { title: '2026年6月 · 课程分享' },
|
||||
})
|
||||
})
|
||||
|
||||
test('修改月份时先加事务锁、排除当前调研,再同步月份和固定标题', async () => {
|
||||
await updatePerformanceSurvey(session, 'survey-1', { assessmentMonth: '2026-07' })
|
||||
|
||||
expect(transactionClient.$queryRawUnsafe).toHaveBeenCalledTimes(2)
|
||||
expect(transactionClient.$queryRawUnsafe.mock.calls.map((call) => call[1])).toEqual([
|
||||
'performance-survey-monthly:course_share:2026-06:employee-1',
|
||||
'performance-survey-monthly:course_share:2026-07:employee-1',
|
||||
])
|
||||
expect(transactionClient.$queryRawUnsafe.mock.calls[0][0]).toContain('::text AS locked')
|
||||
|
||||
const duplicateWhere = transactionClient.performanceSurveyTarget.findMany.mock.calls[0][0].where
|
||||
expect(duplicateWhere.survey.AND).toContainEqual({ id: { not: 'survey-1' } })
|
||||
expect(transactionClient.performanceSurvey.update).toHaveBeenCalledWith({
|
||||
where: { id: 'survey-1' },
|
||||
data: {
|
||||
assessmentMonth: '2026-07',
|
||||
title: '2026年7月 · 课程分享',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
test('创建月度调研时在同一事务内先加锁和查重,再写入调研', async () => {
|
||||
const evaluator = {
|
||||
...baseEmployee,
|
||||
id: 'employee-2',
|
||||
displayName: '评价人员',
|
||||
dingtalkUserId: null,
|
||||
dingEmail: null,
|
||||
}
|
||||
;(prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock)
|
||||
.mockResolvedValueOnce([baseEmployee])
|
||||
.mockResolvedValueOnce([evaluator])
|
||||
|
||||
await createPerformanceSurvey(session, {
|
||||
templateCode: 'course_share',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: ['employee-1'],
|
||||
evaluatorEmployeeIds: ['employee-2'],
|
||||
openNow: false,
|
||||
})
|
||||
|
||||
expect(transactionClient.$queryRawUnsafe).toHaveBeenCalledWith(
|
||||
expect.stringContaining('::text AS locked'),
|
||||
'performance-survey-monthly:course_share:2026-07:employee-1',
|
||||
)
|
||||
expect(transactionClient.performanceSurveyTarget.findMany).toHaveBeenCalledTimes(1)
|
||||
expect(transactionClient.performanceSurvey.create).toHaveBeenCalledTimes(1)
|
||||
expect(transactionClient.$queryRawUnsafe.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
transactionClient.performanceSurveyTarget.findMany.mock.invocationCallOrder[0],
|
||||
)
|
||||
expect(transactionClient.performanceSurveyTarget.findMany.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
transactionClient.performanceSurvey.create.mock.invocationCallOrder[0],
|
||||
)
|
||||
})
|
||||
|
||||
test('创建接口拒绝直接传入组织范围外的被考核人 ID', async () => {
|
||||
;(prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock).mockResolvedValueOnce([baseEmployee])
|
||||
|
||||
await expect(createPerformanceSurvey(session, {
|
||||
templateCode: 'course_share',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: ['employee-outside'],
|
||||
evaluatorEmployeeIds: ['employee-2'],
|
||||
openNow: false,
|
||||
})).rejects.toEqual(
|
||||
new PerformanceSurveyApiError('部分被考核人不在当前组织权限范围内', 403),
|
||||
)
|
||||
|
||||
const targetQuery = (prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock).mock.calls[0][0]
|
||||
expect(targetQuery.where.AND).toContainEqual({
|
||||
OR: [
|
||||
{ id: 'employee-1' },
|
||||
{
|
||||
OR: [
|
||||
{ departmentPath: '集团A/品牌中心/策划部' },
|
||||
{ departmentPath: { startsWith: '集团A/品牌中心/策划部/' } },
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('写入被考核人范围时不使用重名部门叶子回退', async () => {
|
||||
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockResolvedValue({
|
||||
...baseEmployee,
|
||||
departmentPath: null,
|
||||
})
|
||||
;(prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock).mockResolvedValueOnce([{
|
||||
...baseEmployee,
|
||||
departmentPath: null,
|
||||
}])
|
||||
|
||||
await expect(createPerformanceSurvey(session, {
|
||||
templateCode: 'course_share',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: ['employee-outside'],
|
||||
evaluatorEmployeeIds: ['employee-2'],
|
||||
openNow: false,
|
||||
})).rejects.toThrow('部分被考核人不在当前组织权限范围内')
|
||||
|
||||
const targetWhere = (prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock).mock.calls[0][0].where
|
||||
expect(targetWhere.AND).toContainEqual({ id: 'employee-1' })
|
||||
expect(JSON.stringify(targetWhere)).not.toContain('departmentName')
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('修改月份命中另一条同人同月同模板调研时拒绝更新', async () => {
|
||||
transactionClient.performanceSurveyTarget.findMany.mockResolvedValue([{
|
||||
targetName: '测试人员',
|
||||
employeeProfile: null,
|
||||
survey: { id: 'survey-2' },
|
||||
}])
|
||||
|
||||
await expect(
|
||||
updatePerformanceSurvey(session, 'survey-1', { assessmentMonth: '2026-07' }),
|
||||
).rejects.toThrow('2026-07 已存在该模板考核:测试人员')
|
||||
|
||||
expect(transactionClient.performanceSurvey.update).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@ -15,6 +15,7 @@ describe('performance survey templates', () => {
|
||||
expect(template.questions).toHaveLength(5)
|
||||
expect(template.maxTotal).toBe(100)
|
||||
expect(template.weight).toBe(0.3)
|
||||
expect(template.aggregationStrategy).toBe('trim_extremes')
|
||||
expect(template.itemName).toBe('课程')
|
||||
expect(template.respondentNameFallback).toBe('匿名学员')
|
||||
expect(template.belowBand).toBe('满意度不足 77%,此项考核为 0')
|
||||
@ -99,4 +100,65 @@ describe('performance survey templates', () => {
|
||||
expect(result.kpiScore).toBe(100)
|
||||
expect(result.weightedScore).toBe(20)
|
||||
})
|
||||
|
||||
test('visual scoring keeps a single evaluator score as the direct average', () => {
|
||||
const template = DEFAULT_PERFORMANCE_SURVEY_TEMPLATES.find((item) => item.code === 'visual_brand_tone')!
|
||||
|
||||
const result = calculateAggregateScore(
|
||||
[{ totalScore: 88, createdAt: '2026-07-04T00:00:00.000Z' }],
|
||||
template.scoreBands,
|
||||
template.weight,
|
||||
template,
|
||||
)
|
||||
|
||||
expect(template.aggregationStrategy).toBe('direct_average')
|
||||
expect(result.droppedHighestLowest).toBe(false)
|
||||
expect(result.effectiveCount).toBe(1)
|
||||
expect(result.achievementScore).toBe(88)
|
||||
expect(result.removedHigh).toBeNull()
|
||||
expect(result.removedLow).toBeNull()
|
||||
})
|
||||
|
||||
test('visual scoring directly averages all three evaluator scores without trimming extremes', () => {
|
||||
const template = DEFAULT_PERFORMANCE_SURVEY_TEMPLATES.find((item) => item.code === 'visual_brand_tone')!
|
||||
const legacyTemplateSnapshot = { ...template, aggregationStrategy: undefined }
|
||||
|
||||
const result = calculateAggregateScore(
|
||||
[60, 90, 120].map((totalScore, index) => ({
|
||||
totalScore,
|
||||
createdAt: `2026-07-04T00:0${index}:00.000Z`,
|
||||
})),
|
||||
template.scoreBands,
|
||||
template.weight,
|
||||
legacyTemplateSnapshot,
|
||||
)
|
||||
|
||||
expect(result.droppedHighestLowest).toBe(false)
|
||||
expect(result.effectiveCount).toBe(3)
|
||||
expect(result.rawAverage).toBe(90)
|
||||
expect(result.achievementScore).toBe(90)
|
||||
expect(result.removedHigh).toBeNull()
|
||||
expect(result.removedLow).toBeNull()
|
||||
})
|
||||
|
||||
test('visual scoring directly averages every evaluator score when there are more than three', () => {
|
||||
const template = DEFAULT_PERFORMANCE_SURVEY_TEMPLATES.find((item) => item.code === 'visual_brand_tone')!
|
||||
|
||||
const result = calculateAggregateScore(
|
||||
[60, 70, 80, 100, 120].map((totalScore, index) => ({
|
||||
totalScore,
|
||||
createdAt: `2026-07-04T00:0${index}:00.000Z`,
|
||||
})),
|
||||
template.scoreBands,
|
||||
template.weight,
|
||||
template,
|
||||
)
|
||||
|
||||
expect(result.droppedHighestLowest).toBe(false)
|
||||
expect(result.effectiveCount).toBe(5)
|
||||
expect(result.rawAverage).toBe(86)
|
||||
expect(result.achievementScore).toBe(86)
|
||||
expect(result.removedHigh).toBeNull()
|
||||
expect(result.removedLow).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@ -69,6 +69,7 @@ type UserContext = {
|
||||
isDepartmentAdmin: boolean
|
||||
isLeadership: boolean
|
||||
scopeDepartment: string | null
|
||||
scopeDepartmentPath: string | null
|
||||
evaluatorKey: string
|
||||
}
|
||||
|
||||
@ -205,18 +206,98 @@ function getDepartmentNodeId(departmentPath: string) {
|
||||
return `dept:${encodeDepartmentPart(departmentPath)}`
|
||||
}
|
||||
|
||||
function getScopeDepartmentWhere(scopeDepartment: string) {
|
||||
function getScopeDepartmentPathWhere(scopeDepartmentPath: string) {
|
||||
return {
|
||||
OR: [
|
||||
{ departmentName: scopeDepartment },
|
||||
{ departmentPath: scopeDepartment },
|
||||
{ departmentPath: { startsWith: `${scopeDepartment}/` } },
|
||||
{ departmentPath: { contains: `/${scopeDepartment}/` } },
|
||||
{ departmentPath: { endsWith: `/${scopeDepartment}` } },
|
||||
{ departmentPath: scopeDepartmentPath },
|
||||
{ departmentPath: { startsWith: `${scopeDepartmentPath}/` } },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function getContextScopeDepartmentWhere(ctx: UserContext) {
|
||||
if (ctx.scopeDepartmentPath) {
|
||||
return getScopeDepartmentPathWhere(ctx.scopeDepartmentPath)
|
||||
}
|
||||
|
||||
// 普通员工的旧档案可能只有部门名。管理权限不能使用这个回退,
|
||||
// 否则同名叶子部门会跨组织命中。
|
||||
if (!ctx.isDepartmentAdmin && ctx.scopeDepartment) {
|
||||
return { departmentName: ctx.scopeDepartment }
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function normalizeDepartmentPath(value?: string | null) {
|
||||
const parts = parseDepartmentPathParts(value)
|
||||
return parts.length > 0 ? parts.join('/') : null
|
||||
}
|
||||
|
||||
function getManagedDepartmentPathFromEmployeePath(
|
||||
managedDepartment: string,
|
||||
employeeDepartmentPath?: string | null,
|
||||
) {
|
||||
const normalizedManagedPath = normalizeDepartmentPath(managedDepartment)
|
||||
if (!normalizedManagedPath) return null
|
||||
|
||||
const managedParts = parseDepartmentPathParts(normalizedManagedPath)
|
||||
if (managedParts.length > 1) return normalizedManagedPath
|
||||
|
||||
const managedName = managedParts[0]
|
||||
const employeeParts = parseDepartmentPathParts(employeeDepartmentPath)
|
||||
const matchedIndex = employeeParts.lastIndexOf(managedName)
|
||||
return matchedIndex >= 0 ? employeeParts.slice(0, matchedIndex + 1).join('/') : null
|
||||
}
|
||||
|
||||
async function resolveManagedDepartmentPath(
|
||||
managedDepartment: string,
|
||||
employeeDepartmentPath?: string | null,
|
||||
) {
|
||||
const pathFromEmployee = getManagedDepartmentPathFromEmployeePath(
|
||||
managedDepartment,
|
||||
employeeDepartmentPath,
|
||||
)
|
||||
if (pathFromEmployee) return pathFromEmployee
|
||||
|
||||
const managedName = clean(managedDepartment)
|
||||
if (!managedName) return null
|
||||
|
||||
const profiles = await prisma.performanceSurveyEmployeeProfile.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ departmentName: managedName },
|
||||
{ departmentPath: managedName },
|
||||
{ departmentPath: { startsWith: `${managedName}/` } },
|
||||
{ departmentPath: { contains: `/${managedName}/` } },
|
||||
{ departmentPath: { endsWith: `/${managedName}` } },
|
||||
],
|
||||
},
|
||||
select: {
|
||||
departmentName: true,
|
||||
departmentPath: true,
|
||||
},
|
||||
take: 10_000,
|
||||
})
|
||||
|
||||
const candidatePaths = new Set<string>()
|
||||
for (const profile of profiles) {
|
||||
const profileParts = parseDepartmentPathParts(profile.departmentPath)
|
||||
if (profileParts.length === 0) continue
|
||||
const matchedIndex = profileParts.lastIndexOf(managedName)
|
||||
if (matchedIndex >= 0) {
|
||||
candidatePaths.add(profileParts.slice(0, matchedIndex + 1).join('/'))
|
||||
continue
|
||||
}
|
||||
if (clean(profile.departmentName) === managedName) {
|
||||
candidatePaths.add(profileParts.join('/'))
|
||||
}
|
||||
}
|
||||
|
||||
// managedDepartment 仍可使用旧的部门名语义,但只有能唯一解析到完整路径时才放行。
|
||||
return candidatePaths.size === 1 ? Array.from(candidatePaths)[0] : null
|
||||
}
|
||||
|
||||
function parseDepartmentSelection(value: string) {
|
||||
const normalizedValue = clean(value)
|
||||
if (
|
||||
@ -479,7 +560,7 @@ function getEvaluatorKey(input: {
|
||||
}
|
||||
|
||||
function ensureManager(ctx: UserContext) {
|
||||
if (!ctx.isDepartmentAdmin) {
|
||||
if (!ctx.isDepartmentAdmin || (!ctx.isSystemAdmin && !ctx.scopeDepartmentPath)) {
|
||||
throw new PerformanceSurveyApiError('无权限管理考核调研', 403)
|
||||
}
|
||||
}
|
||||
@ -490,20 +571,15 @@ function isLeadershipProfile(employee: any) {
|
||||
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
|
||||
}
|
||||
|
||||
async function canManageSurvey(ctx: UserContext, survey: { id: string; creatorUserId: string; departmentName?: string | null }) {
|
||||
if (survey.creatorUserId === ctx.user.id) return true
|
||||
if (ctx.isSystemAdmin) return true
|
||||
if (!ctx.isDepartmentAdmin) return false
|
||||
if (isSurveyInManagerScope(ctx, survey)) return true
|
||||
if (!ctx.scopeDepartment) return false
|
||||
if (!ctx.scopeDepartmentPath) return false
|
||||
|
||||
const scopeWhere = await getSurveyWhereByEmployeeProfileScope(getScopeDepartmentWhere(ctx.scopeDepartment))
|
||||
const scopeWhere = getSurveyWhereByAllEmployeeTargetsInScope(
|
||||
getScopeDepartmentPathWhere(ctx.scopeDepartmentPath),
|
||||
)
|
||||
const count = await prisma.performanceSurvey.count({
|
||||
where: {
|
||||
AND: [
|
||||
@ -527,33 +603,45 @@ function mergeOrClauses(clauses: any[]) {
|
||||
return validClauses.length === 1 ? validClauses[0] : { OR: validClauses }
|
||||
}
|
||||
|
||||
async function getSurveyWhereByEmployeeProfileScope(profileWhere: any) {
|
||||
const employees = await prisma.performanceSurveyEmployeeProfile.findMany({
|
||||
where: profileWhere,
|
||||
select: { id: true },
|
||||
take: 10_000,
|
||||
})
|
||||
const employeeIds = employees.map((employee) => employee.id)
|
||||
const clauses: any[] = [
|
||||
{ targets: { some: { employeeProfile: { is: profileWhere } } } },
|
||||
{ assignments: { some: { evaluatorEmployee: { is: profileWhere } } } },
|
||||
]
|
||||
|
||||
if (employeeIds.length > 0) {
|
||||
clauses.push({ creatorEmployeeId: { in: employeeIds } })
|
||||
function getSurveyWhereByAllEmployeeTargetsInScope(profileWhere: any) {
|
||||
return {
|
||||
AND: [
|
||||
{ targets: { some: { targetType: 'employee' } } },
|
||||
{
|
||||
targets: {
|
||||
none: {
|
||||
targetType: 'employee',
|
||||
OR: [
|
||||
{ employeeProfileId: null },
|
||||
{ employeeProfile: { isNot: profileWhere } },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
return mergeOrClauses(clauses)
|
||||
function getSurveyWhereByAnyEmployeeTargetInScope(profileWhere: any) {
|
||||
return {
|
||||
targets: {
|
||||
some: {
|
||||
targetType: 'employee',
|
||||
employeeProfile: { is: profileWhere },
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function getManagerSurveyBaseWhere(ctx: UserContext) {
|
||||
if (ctx.isSystemAdmin) return {}
|
||||
if (!ctx.scopeDepartment) return { creatorUserId: ctx.user.id }
|
||||
if (!ctx.scopeDepartmentPath) return { creatorUserId: ctx.user.id }
|
||||
|
||||
return mergeOrClauses([
|
||||
{ creatorUserId: ctx.user.id },
|
||||
{ departmentName: ctx.scopeDepartment },
|
||||
await getSurveyWhereByEmployeeProfileScope(getScopeDepartmentWhere(ctx.scopeDepartment)),
|
||||
getSurveyWhereByAllEmployeeTargetsInScope(
|
||||
getScopeDepartmentPathWhere(ctx.scopeDepartmentPath),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
@ -565,7 +653,7 @@ async function getManagerSurveyFilterWhere(ctx: UserContext, params?: URLSearchP
|
||||
if (departmentValue) {
|
||||
const departmentClauses = getDepartmentSelectionWhere([departmentValue])
|
||||
if (departmentClauses.length > 0) {
|
||||
and.push(await getSurveyWhereByEmployeeProfileScope(mergeOrClauses(departmentClauses)))
|
||||
and.push(getSurveyWhereByAnyEmployeeTargetInScope(mergeOrClauses(departmentClauses)))
|
||||
}
|
||||
}
|
||||
|
||||
@ -617,7 +705,14 @@ export async function getPerformanceSurveyContext(session: Session | null): Prom
|
||||
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)
|
||||
const managedDepartment = clean(user.managedDepartment)
|
||||
const managedDepartmentParts = parseDepartmentPathParts(managedDepartment)
|
||||
const scopeDepartment = managedDepartment
|
||||
? managedDepartmentParts[managedDepartmentParts.length - 1] || managedDepartment
|
||||
: clean(employee?.departmentName) || clean(user.department)
|
||||
const scopeDepartmentPath = managedDepartment
|
||||
? await resolveManagedDepartmentPath(managedDepartment, employee?.departmentPath)
|
||||
: normalizeDepartmentPath(employee?.departmentPath)
|
||||
|
||||
return {
|
||||
user,
|
||||
@ -626,6 +721,7 @@ export async function getPerformanceSurveyContext(session: Session | null): Prom
|
||||
isDepartmentAdmin,
|
||||
isLeadership,
|
||||
scopeDepartment,
|
||||
scopeDepartmentPath,
|
||||
evaluatorKey: getEvaluatorKey({
|
||||
employeeId: employee?.id,
|
||||
userId: user.id,
|
||||
@ -653,6 +749,7 @@ export async function getPerformanceSurveyMe(session: Session | null) {
|
||||
isDepartmentAdmin: ctx.isDepartmentAdmin,
|
||||
isLeadership: ctx.isLeadership,
|
||||
scopeDepartment: ctx.scopeDepartment,
|
||||
scopeDepartmentPath: ctx.scopeDepartmentPath,
|
||||
canCreate: true,
|
||||
},
|
||||
}
|
||||
@ -681,8 +778,8 @@ export async function searchPerformanceSurveyEmployees(session: Session | null,
|
||||
and.push({ OR: departmentClauses })
|
||||
}
|
||||
}
|
||||
if (!ctx.isSystemAdmin && ctx.scopeDepartment && !isEvaluatorSearch) {
|
||||
and.push(getScopeDepartmentWhere(ctx.scopeDepartment))
|
||||
if (!ctx.isSystemAdmin && !isEvaluatorSearch) {
|
||||
and.push(getContextScopeDepartmentWhere(ctx) || { id: '__none__' })
|
||||
}
|
||||
if (includeKeyword && search) {
|
||||
and.push({ OR: [
|
||||
@ -745,7 +842,7 @@ export async function listPerformanceSurveyDepartments(session: Session | null,
|
||||
const isEvaluatorPicker = clean(params?.get('purpose')) === 'evaluator'
|
||||
const cacheKey = [
|
||||
isEvaluatorPicker ? 'evaluator' : 'scoped',
|
||||
ctx.isSystemAdmin ? 'system' : ctx.scopeDepartment || ctx.user.id,
|
||||
ctx.isSystemAdmin ? 'system' : ctx.scopeDepartmentPath || ctx.scopeDepartment || ctx.user.id,
|
||||
].join(':')
|
||||
prunePerformanceSurveyDepartmentCache()
|
||||
const cached = performanceSurveyDepartmentCache.get(cacheKey)
|
||||
@ -761,8 +858,8 @@ export async function listPerformanceSurveyDepartments(session: Session | null,
|
||||
accountWhere,
|
||||
{ departmentName: { not: null } },
|
||||
]
|
||||
if (!ctx.isSystemAdmin && ctx.scopeDepartment && !isEvaluatorPicker) {
|
||||
and.push(getScopeDepartmentWhere(ctx.scopeDepartment))
|
||||
if (!ctx.isSystemAdmin && !isEvaluatorPicker) {
|
||||
and.push(getContextScopeDepartmentWhere(ctx) || { id: '__none__' })
|
||||
}
|
||||
|
||||
const employees = await prisma.performanceSurveyEmployeeProfile.findMany({
|
||||
@ -959,13 +1056,13 @@ export async function listPerformanceSurveys(session: Session | null, params?: U
|
||||
const canSeeScopeSummary = Boolean(ctx.isSystemAdmin || ctx.isLeadership)
|
||||
const scopeAssignmentEmployeeWhere = ctx.isSystemAdmin
|
||||
? {}
|
||||
: ctx.scopeDepartment
|
||||
? { evaluatorEmployee: { is: getScopeDepartmentWhere(ctx.scopeDepartment) } }
|
||||
: ctx.scopeDepartmentPath
|
||||
? { evaluatorEmployee: { is: getScopeDepartmentPathWhere(ctx.scopeDepartmentPath) } }
|
||||
: { evaluatorKey: ctx.evaluatorKey }
|
||||
const scopeTargetEmployeeWhere = ctx.isSystemAdmin
|
||||
? {}
|
||||
: ctx.scopeDepartment
|
||||
? { employeeProfile: { is: getScopeDepartmentWhere(ctx.scopeDepartment) } }
|
||||
: ctx.scopeDepartmentPath
|
||||
? { employeeProfile: { is: getScopeDepartmentPathWhere(ctx.scopeDepartmentPath) } }
|
||||
: ctx.employee
|
||||
? { employeeProfileId: ctx.employee.id }
|
||||
: { id: '__none__' }
|
||||
@ -1119,6 +1216,7 @@ export async function listPerformanceSurveys(session: Session | null, params?: U
|
||||
isDepartmentAdmin: ctx.isDepartmentAdmin,
|
||||
isLeadership: ctx.isLeadership,
|
||||
scopeDepartment: ctx.scopeDepartment,
|
||||
scopeDepartmentPath: ctx.scopeDepartmentPath,
|
||||
canCreate: true,
|
||||
},
|
||||
}
|
||||
@ -1241,8 +1339,12 @@ async function getPublicDashboardEmployees(ctx: UserContext, params?: URLSearchP
|
||||
const employeeId = clean(params?.get('employeeId'))
|
||||
const and: any[] = [await getPerformanceSurveyAccountProfileWhere()]
|
||||
|
||||
if (ctx.isLeadership && ctx.scopeDepartment) {
|
||||
and.push(getScopeDepartmentWhere(ctx.scopeDepartment))
|
||||
if (ctx.isLeadership) {
|
||||
and.push(
|
||||
ctx.scopeDepartmentPath
|
||||
? getScopeDepartmentPathWhere(ctx.scopeDepartmentPath)
|
||||
: { id: '__none__' },
|
||||
)
|
||||
}
|
||||
|
||||
if (departmentValue) {
|
||||
@ -1318,9 +1420,11 @@ async function getMonthlyTargets(employeeIds: string[], monthRange: { start: Dat
|
||||
}
|
||||
|
||||
async function assertNoMonthlyAssessmentDuplicate(
|
||||
db: any,
|
||||
templateCode: string,
|
||||
assessmentMonth: string,
|
||||
targetRows: Array<{ employeeProfileId?: string | null }>,
|
||||
excludeSurveyId?: string,
|
||||
) {
|
||||
if (!isMonthlyAssessmentTemplateCode(templateCode)) return
|
||||
const employeeIds = Array.from(new Set(targetRows.map((target) => target.employeeProfileId).filter((id): id is string => Boolean(id))))
|
||||
@ -1328,7 +1432,7 @@ async function assertNoMonthlyAssessmentDuplicate(
|
||||
|
||||
const monthRange = getMonthRange(assessmentMonth)
|
||||
if (!monthRange) throw new PerformanceSurveyApiError('考核月份格式无效')
|
||||
const existingTargets = await prisma.performanceSurveyTarget.findMany({
|
||||
const existingTargets = await db.performanceSurveyTarget.findMany({
|
||||
where: {
|
||||
targetType: 'employee',
|
||||
employeeProfileId: { in: employeeIds },
|
||||
@ -1336,6 +1440,7 @@ async function assertNoMonthlyAssessmentDuplicate(
|
||||
AND: [
|
||||
{ templateCode },
|
||||
getSurveyMonthWhere(monthRange),
|
||||
...(excludeSurveyId ? [{ id: { not: excludeSurveyId } }] : []),
|
||||
],
|
||||
},
|
||||
} as any,
|
||||
@ -1348,7 +1453,7 @@ async function assertNoMonthlyAssessmentDuplicate(
|
||||
|
||||
if (existingTargets.length === 0) return
|
||||
|
||||
const duplicateNames = Array.from(new Set(existingTargets.map((target) => (
|
||||
const duplicateNames = Array.from(new Set(existingTargets.map((target: any) => (
|
||||
target.employeeProfile ? getEmployeeDisplayName(target.employeeProfile) : target.targetName
|
||||
))))
|
||||
|
||||
@ -1357,6 +1462,37 @@ async function assertNoMonthlyAssessmentDuplicate(
|
||||
)
|
||||
}
|
||||
|
||||
async function lockMonthlyAssessmentKeys(
|
||||
db: any,
|
||||
templateCode: string,
|
||||
assessmentMonths: Array<string | null | undefined>,
|
||||
targetRows: Array<{ employeeProfileId?: string | null }>,
|
||||
) {
|
||||
if (!isMonthlyAssessmentTemplateCode(templateCode)) return
|
||||
const employeeIds = Array.from(new Set(
|
||||
targetRows
|
||||
.map((target) => clean(target.employeeProfileId))
|
||||
.filter((id): id is string => Boolean(id)),
|
||||
))
|
||||
const months = Array.from(new Set(
|
||||
assessmentMonths
|
||||
.map((month) => normalizeAssessmentMonth(month))
|
||||
.filter((month): month is string => Boolean(month)),
|
||||
))
|
||||
const lockKeys = employeeIds
|
||||
.flatMap((employeeId) => months.map((month) => (
|
||||
`performance-survey-monthly:${templateCode}:${month}:${employeeId}`
|
||||
)))
|
||||
.sort()
|
||||
|
||||
for (const lockKey of lockKeys) {
|
||||
await db.$queryRawUnsafe(
|
||||
'SELECT pg_advisory_xact_lock(hashtextextended($1, 0))::text AS locked',
|
||||
lockKey,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function getPerformanceSurveyDashboard(session: Session | null, params?: URLSearchParams) {
|
||||
const ctx = await getPerformanceSurveyContext(session)
|
||||
const requestedView = clean(params?.get('view'))
|
||||
@ -1378,7 +1514,9 @@ export async function getPerformanceSurveyDashboard(session: Session | null, par
|
||||
const publicTargets = includePublic
|
||||
? await getMonthlyTargets(publicEmployees.map((employee) => employee.id), monthRange)
|
||||
: []
|
||||
const publicDetailAllowed = Boolean(ctx.isSystemAdmin || ctx.isLeadership)
|
||||
const publicDetailAllowed = Boolean(
|
||||
ctx.isSystemAdmin || (ctx.isLeadership && ctx.scopeDepartmentPath),
|
||||
)
|
||||
const publicTargetsByEmployee = new Map<string, any[]>()
|
||||
for (const target of publicTargets) {
|
||||
const key = clean(target.employeeProfileId)
|
||||
@ -1409,8 +1547,13 @@ export async function getPerformanceSurveyDashboard(session: Session | null, par
|
||||
isSystemAdmin: ctx.isSystemAdmin,
|
||||
isLeadership: ctx.isLeadership,
|
||||
isDepartmentAdmin: ctx.isDepartmentAdmin,
|
||||
scopeMode: ctx.isSystemAdmin ? 'system' : ctx.isLeadership ? 'organization' : 'public-readonly',
|
||||
scopeMode: ctx.isSystemAdmin
|
||||
? 'system'
|
||||
: ctx.isLeadership && ctx.scopeDepartmentPath
|
||||
? 'organization'
|
||||
: 'public-readonly',
|
||||
scopeDepartment: ctx.scopeDepartment,
|
||||
scopeDepartmentPath: ctx.scopeDepartmentPath,
|
||||
canOpenPersonalDetail: Boolean(ctx.employee),
|
||||
canOpenPublicDetail: publicDetailAllowed,
|
||||
},
|
||||
@ -1454,15 +1597,15 @@ export async function getPerformanceSurveyDashboardDetail(session: Session | nul
|
||||
|
||||
const isSelf = employee.id === ctx.employee?.id
|
||||
if (!isSelf) {
|
||||
if (!ctx.isSystemAdmin && !ctx.isLeadership) {
|
||||
if (!ctx.isSystemAdmin && (!ctx.isLeadership || !ctx.scopeDepartmentPath)) {
|
||||
throw new PerformanceSurveyApiError('无权限查看该人员考核明细', 403)
|
||||
}
|
||||
if (!ctx.isSystemAdmin && ctx.scopeDepartment) {
|
||||
if (!ctx.isSystemAdmin && ctx.scopeDepartmentPath) {
|
||||
const count = await prisma.performanceSurveyEmployeeProfile.count({
|
||||
where: {
|
||||
AND: [
|
||||
{ id: employee.id },
|
||||
getScopeDepartmentWhere(ctx.scopeDepartment),
|
||||
getScopeDepartmentPathWhere(ctx.scopeDepartmentPath),
|
||||
],
|
||||
},
|
||||
})
|
||||
@ -1692,7 +1835,7 @@ export async function createPerformanceSurvey(session: Session | null, body: any
|
||||
throw new PerformanceSurveyApiError('当前账户尚未匹配考核人员档案,暂时无法发起调研', 409)
|
||||
}
|
||||
|
||||
const targets = await resolveSurveyTargets(body, surveyKind, ctx.employee?.id)
|
||||
const targets = await resolveSurveyTargets(body, surveyKind, ctx)
|
||||
if (targets.length === 0) {
|
||||
throw new PerformanceSurveyApiError(
|
||||
surveyKind === 'item_course'
|
||||
@ -1717,8 +1860,6 @@ export async function createPerformanceSurvey(session: Session | null, body: any
|
||||
sortOrder: index,
|
||||
}))
|
||||
|
||||
await assertNoMonthlyAssessmentDuplicate(template.code, assessmentMonth, targetRows)
|
||||
|
||||
const assignmentRows: any[] = []
|
||||
for (const target of targetRows) {
|
||||
for (const evaluator of evaluators) {
|
||||
@ -1750,6 +1891,13 @@ export async function createPerformanceSurvey(session: Session | null, body: any
|
||||
}
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await lockMonthlyAssessmentKeys(tx, template.code, [assessmentMonth], targetRows)
|
||||
await assertNoMonthlyAssessmentDuplicate(
|
||||
tx,
|
||||
template.code,
|
||||
assessmentMonth,
|
||||
targetRows,
|
||||
)
|
||||
await tx.performanceSurvey.create({
|
||||
data: {
|
||||
id: surveyId,
|
||||
@ -1932,23 +2080,37 @@ export async function getPerformanceSurveyDetail(session: Session | null, survey
|
||||
export async function updatePerformanceSurvey(session: Session | null, surveyId: string, body: any) {
|
||||
const ctx = await getPerformanceSurveyContext(session)
|
||||
|
||||
const survey = await prisma.performanceSurvey.findUnique({ where: { id: surveyId } })
|
||||
const survey = await prisma.performanceSurvey.findUnique({
|
||||
where: { id: surveyId },
|
||||
include: {
|
||||
targets: {
|
||||
select: { employeeProfileId: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!survey) throw new PerformanceSurveyApiError('调研不存在', 404)
|
||||
await ensureSurveyManageScope(ctx, survey)
|
||||
|
||||
const nextStatus = clean(body?.status)
|
||||
const data: any = {}
|
||||
const isMonthlyAssessment = isMonthlyAssessmentTemplateCode(survey.templateCode)
|
||||
const currentAssessmentMonth = normalizeAssessmentMonth(survey.assessmentMonth)
|
||||
|| getMonthValueFromDate(survey.dueAt || survey.createdAt)
|
||||
|
||||
if (body?.title != null) data.title = clean(body.title) || survey.title
|
||||
if (body?.title != null && !isMonthlyAssessment) {
|
||||
data.title = clean(body.title) || survey.title
|
||||
}
|
||||
if (body?.description !== undefined) data.description = clean(body.description)
|
||||
if (body?.assessmentMonth !== undefined) {
|
||||
const assessmentMonth = normalizeAssessmentMonth(body.assessmentMonth)
|
||||
if (!assessmentMonth) throw new PerformanceSurveyApiError('考核月份格式无效')
|
||||
data.assessmentMonth = assessmentMonth
|
||||
if (isMonthlyAssessmentTemplateCode(survey.templateCode)) {
|
||||
const template = survey.templateSnapshot as PerformanceSurveyTemplateShape
|
||||
data.title = formatAssessmentMonthTitle(assessmentMonth, template.shortName || template.name)
|
||||
}
|
||||
}
|
||||
if (isMonthlyAssessment && (body?.title != null || body?.assessmentMonth !== undefined)) {
|
||||
const template = survey.templateSnapshot as PerformanceSurveyTemplateShape
|
||||
const effectiveAssessmentMonth = data.assessmentMonth || currentAssessmentMonth
|
||||
const templateName = clean(template.shortName) || clean(template.name) || survey.templateCode
|
||||
data.title = formatAssessmentMonthTitle(effectiveAssessmentMonth, templateName)
|
||||
}
|
||||
if (body?.dueAt !== undefined) {
|
||||
const requestedDueAt = clean(body.dueAt)
|
||||
@ -1972,10 +2134,32 @@ export async function updatePerformanceSurvey(session: Session | null, surveyId:
|
||||
throw new PerformanceSurveyApiError('截止时间必须晚于当前时间')
|
||||
}
|
||||
|
||||
await prisma.performanceSurvey.update({
|
||||
where: { id: surveyId },
|
||||
data,
|
||||
})
|
||||
if (isMonthlyAssessment && body?.assessmentMonth !== undefined) {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await lockMonthlyAssessmentKeys(
|
||||
tx,
|
||||
survey.templateCode,
|
||||
[currentAssessmentMonth, data.assessmentMonth],
|
||||
survey.targets,
|
||||
)
|
||||
await assertNoMonthlyAssessmentDuplicate(
|
||||
tx,
|
||||
survey.templateCode,
|
||||
data.assessmentMonth,
|
||||
survey.targets,
|
||||
survey.id,
|
||||
)
|
||||
await tx.performanceSurvey.update({
|
||||
where: { id: surveyId },
|
||||
data,
|
||||
})
|
||||
})
|
||||
} else {
|
||||
await prisma.performanceSurvey.update({
|
||||
where: { id: surveyId },
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
if (data.status === 'open') {
|
||||
await queueSurveyAssignmentNotifications(surveyId)
|
||||
@ -2546,14 +2730,7 @@ 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 where = await getManagerSurveyBaseWhere(ctx)
|
||||
|
||||
const responses = await prisma.performanceSurveyResponse.findMany({
|
||||
where: {
|
||||
@ -2615,8 +2792,8 @@ export async function listPerformanceSurveyNotifications(session: Session | null
|
||||
const where: any = {}
|
||||
if (status && status !== 'all') where.status = status
|
||||
|
||||
if (!ctx.isSystemAdmin && ctx.scopeDepartment) {
|
||||
where.survey = { departmentName: ctx.scopeDepartment }
|
||||
if (!ctx.isSystemAdmin) {
|
||||
where.survey = await getManagerSurveyBaseWhere(ctx)
|
||||
}
|
||||
|
||||
const notifications = await prisma.performanceSurveyNotification.findMany({
|
||||
@ -2650,8 +2827,8 @@ export async function getPerformanceSurveyNotificationStatus(session: Session |
|
||||
ensureManager(ctx)
|
||||
|
||||
const where: any = {}
|
||||
if (!ctx.isSystemAdmin && ctx.scopeDepartment) {
|
||||
where.survey = { departmentName: ctx.scopeDepartment }
|
||||
if (!ctx.isSystemAdmin) {
|
||||
where.survey = await getManagerSurveyBaseWhere(ctx)
|
||||
}
|
||||
|
||||
const grouped = await prisma.performanceSurveyNotification.groupBy({
|
||||
@ -2690,7 +2867,8 @@ export async function runPerformanceSurveyNotificationMaintenance(session: Sessi
|
||||
return { reminderCount: reminderIds.length, recovered, readStatusRefreshed }
|
||||
}
|
||||
|
||||
async function resolveSurveyTargets(body: any, surveyKind: string, currentEmployeeId?: string | null) {
|
||||
async function resolveSurveyTargets(body: any, surveyKind: string, ctx: UserContext) {
|
||||
const currentEmployeeId = ctx.employee?.id
|
||||
const targetEmployeeIds = getPerformanceSurveyTargetEmployeeIds({
|
||||
requestedEmployeeIds: body?.targetEmployeeIds,
|
||||
currentEmployeeId,
|
||||
@ -2710,17 +2888,39 @@ async function resolveSurveyTargets(body: any, surveyKind: string, currentEmploy
|
||||
.filter((item: any) => item.targetName)
|
||||
: []
|
||||
|
||||
const employeeTargets =
|
||||
targetEmployeeIds.length > 0
|
||||
? await prisma.performanceSurveyEmployeeProfile.findMany({
|
||||
where: {
|
||||
AND: [
|
||||
await getPerformanceSurveyAccountProfileWhere(),
|
||||
{ id: { in: targetEmployeeIds } },
|
||||
],
|
||||
},
|
||||
})
|
||||
: []
|
||||
// 写入权限只接受完整组织路径;旧档案的部门名回退仅用于普通查询,
|
||||
// 不能用来决定跨人员的被考核人范围。
|
||||
const targetScopeWhere = ctx.scopeDepartmentPath
|
||||
? getScopeDepartmentPathWhere(ctx.scopeDepartmentPath)
|
||||
: null
|
||||
const allowedTargetClauses = ctx.isSystemAdmin
|
||||
? []
|
||||
: [
|
||||
mergeOrClauses([
|
||||
currentEmployeeId ? { id: currentEmployeeId } : null,
|
||||
targetScopeWhere,
|
||||
]),
|
||||
]
|
||||
const employeeTargets = targetEmployeeIds.length > 0
|
||||
? await prisma.performanceSurveyEmployeeProfile.findMany({
|
||||
where: {
|
||||
AND: [
|
||||
await getPerformanceSurveyAccountProfileWhere(),
|
||||
{ id: { in: targetEmployeeIds } },
|
||||
...allowedTargetClauses,
|
||||
],
|
||||
},
|
||||
})
|
||||
: []
|
||||
|
||||
if (employeeTargets.length !== targetEmployeeIds.length) {
|
||||
throw new PerformanceSurveyApiError(
|
||||
ctx.isSystemAdmin
|
||||
? '部分被考核人不存在或已不可用'
|
||||
: '部分被考核人不在当前组织权限范围内',
|
||||
ctx.isSystemAdmin ? 400 : 403,
|
||||
)
|
||||
}
|
||||
|
||||
const targets = employeeTargets.map((employee) => ({
|
||||
targetType: 'employee',
|
||||
|
||||
@ -23,6 +23,8 @@ export type PerformanceSurveyScoreBand = {
|
||||
label?: string
|
||||
}
|
||||
|
||||
export type PerformanceSurveyAggregationStrategy = 'trim_extremes' | 'direct_average'
|
||||
|
||||
export type PerformanceSurveyTemplateShape = {
|
||||
code: string
|
||||
name: string
|
||||
@ -41,6 +43,7 @@ export type PerformanceSurveyTemplateShape = {
|
||||
dataSource?: string
|
||||
weight: number
|
||||
weightLabel?: string
|
||||
aggregationStrategy?: PerformanceSurveyAggregationStrategy
|
||||
maxTotal?: number
|
||||
questionMaxScore?: number
|
||||
requiredWorkItemCount?: number
|
||||
@ -74,6 +77,7 @@ export const DEFAULT_PERFORMANCE_SURVEY_TEMPLATES: PerformanceSurveyTemplateShap
|
||||
dataSource: '现场学员评',
|
||||
weight: 0.3,
|
||||
weightLabel: '30%',
|
||||
aggregationStrategy: 'trim_extremes',
|
||||
maxTotal: 100,
|
||||
achievementLabel: '满意度',
|
||||
achievementSuffix: '%',
|
||||
@ -112,6 +116,7 @@ export const DEFAULT_PERFORMANCE_SURVEY_TEMPLATES: PerformanceSurveyTemplateShap
|
||||
dataSource: '协作满意度问卷评分',
|
||||
weight: 0.2,
|
||||
weightLabel: '20%',
|
||||
aggregationStrategy: 'trim_extremes',
|
||||
maxTotal: 120,
|
||||
achievementLabel: '协作得分',
|
||||
achievementSuffix: '',
|
||||
@ -151,6 +156,7 @@ export const DEFAULT_PERFORMANCE_SURVEY_TEMPLATES: PerformanceSurveyTemplateShap
|
||||
dataSource: '上级主管评',
|
||||
weight: 0.2,
|
||||
weightLabel: '20%',
|
||||
aggregationStrategy: 'trim_extremes',
|
||||
maxTotal: 120,
|
||||
achievementLabel: '配合度得分',
|
||||
achievementSuffix: '',
|
||||
@ -190,6 +196,7 @@ export const DEFAULT_PERFORMANCE_SURVEY_TEMPLATES: PerformanceSurveyTemplateShap
|
||||
dataSource: '案例图片 + 评价人看图评分',
|
||||
weight: 1,
|
||||
weightLabel: '',
|
||||
aggregationStrategy: 'direct_average',
|
||||
maxTotal: 120,
|
||||
questionMaxScore: 8,
|
||||
requiredWorkItemCount: 3,
|
||||
@ -300,6 +307,7 @@ function withDefaultTemplateMeta(template: PerformanceSurveyTemplateShape): Perf
|
||||
respondentNameFallback: template.respondentNameFallback ?? matchedDefault?.respondentNameFallback,
|
||||
dataSource: template.dataSource ?? matchedDefault?.dataSource,
|
||||
weightLabel: matchedDefault?.weightLabel || `${Math.round(Number(template.weight || 0) * 100)}%`,
|
||||
aggregationStrategy: template.aggregationStrategy ?? matchedDefault?.aggregationStrategy ?? 'trim_extremes',
|
||||
maxTotal: template.maxTotal ?? matchedDefault?.maxTotal,
|
||||
questionMaxScore: template.questionMaxScore ?? matchedDefault?.questionMaxScore,
|
||||
requiredWorkItemCount: template.requiredWorkItemCount ?? matchedDefault?.requiredWorkItemCount,
|
||||
@ -371,7 +379,7 @@ export function calculateAggregateScore(
|
||||
}>,
|
||||
scoreBands: PerformanceSurveyScoreBand[],
|
||||
weight: number,
|
||||
template?: Pick<PerformanceSurveyTemplateShape, 'questions' | 'trimNote' | 'trimmedNote' | 'belowBand' | 'achievementLabel' | 'achievementSuffix' | 'maxTotal' | 'weightLabel'>,
|
||||
template?: Pick<PerformanceSurveyTemplateShape, 'code' | 'questions' | 'trimNote' | 'trimmedNote' | 'belowBand' | 'achievementLabel' | 'achievementSuffix' | 'maxTotal' | 'weightLabel' | 'aggregationStrategy'>,
|
||||
) {
|
||||
const sorted = [...responses].sort((left, right) => {
|
||||
const scoreDiff = Number(left.totalScore || 0) - Number(right.totalScore || 0)
|
||||
@ -383,7 +391,9 @@ export function calculateAggregateScore(
|
||||
sorted.length > 0
|
||||
? sorted.reduce((sum, response) => sum + Number(response.totalScore || 0), 0) / sorted.length
|
||||
: null
|
||||
const droppedHighestLowest = sorted.length >= 3
|
||||
const aggregationStrategy = template?.aggregationStrategy
|
||||
?? (template?.code === 'visual_brand_tone' ? 'direct_average' : 'trim_extremes')
|
||||
const droppedHighestLowest = aggregationStrategy === 'trim_extremes' && sorted.length >= 3
|
||||
const removedLow = droppedHighestLowest ? sorted[0] : null
|
||||
const removedHigh = droppedHighestLowest ? sorted[sorted.length - 1] : null
|
||||
const effective = droppedHighestLowest ? sorted.slice(1, -1) : sorted
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user