feat: 配置考核主管与发起范围

This commit is contained in:
chenpei 2026-07-14 09:46:03 +08:00
parent 74486321f9
commit 14a7a65ce3
3 changed files with 262 additions and 24 deletions

View File

@ -588,9 +588,11 @@ export default function PerformanceSurveyPage() {
const isSurveySubmitPage = path[0] === 'survey' && Boolean(path[1])
const isResultsPage = path[0] === 'results' && Boolean(path[1])
let content = <Dashboard me={currentUser.data} />
const canCreateSurvey = Boolean(currentUser.data?.permissions?.canCreate)
const permissionsLoading = currentUser.loading || (!currentUser.data && !currentUser.error)
let content = <Dashboard me={currentUser.data} permissionsLoading={permissionsLoading} />
if (isSurveySubmitPage && path[1]) {
content = <SurveySubmit surveyId={path[1]} session={effectiveSession} />
content = <SurveySubmit surveyId={path[1]} session={effectiveSession} canCreateSurvey={canCreateSurvey} />
}
if (isResultsPage && path[1]) {
content = <SurveyResults surveyId={path[1]} />
@ -653,7 +655,7 @@ function PerformanceSurveyMobileHeader({ session }: { session: any }) {
)
}
function Dashboard({ me }: { me: any | null }) {
function Dashboard({ me, permissionsLoading }: { me: any | null; permissionsLoading: boolean }) {
const router = useRouter()
const searchParams = useSearchParams()
const requestedTabRaw = searchParams.get('tab') || 'personal'
@ -663,12 +665,23 @@ function Dashboard({ me }: { me: any | null }) {
const displayName = me?.employee?.flowerName || me?.employee?.displayName || me?.user?.name || '当前用户'
const avatar = me?.user?.avatar || me?.user?.image || ''
const canCreateSurvey = Boolean(me?.permissions?.canCreate)
const permissionsResolved = !permissionsLoading
const availableTabIds = useMemo(
() => canCreateSurvey ? ['personal', 'public', 'manage'] : ['personal', 'public'],
[canCreateSurvey],
)
useEffect(() => {
if (!permissionsResolved) return
if (requestedTab === 'manage' && !canCreateSurvey) {
setTab('personal')
const query = new URLSearchParams(searchParamsKey)
query.set('tab', 'personal')
query.delete('prefillMonth')
query.delete('prefillTemplate')
router.replace(`/performance-survey?${query.toString()}`, { scroll: false })
return
}
if (availableTabIds.includes(requestedTab) && tab !== requestedTab) {
setTab(requestedTab)
return
@ -676,7 +689,7 @@ function Dashboard({ me }: { me: any | null }) {
if (!availableTabIds.includes(tab)) {
setTab('personal')
}
}, [availableTabIds, requestedTab, tab])
}, [availableTabIds, canCreateSurvey, permissionsResolved, requestedTab, router, searchParamsKey, tab])
useEffect(() => {
if (requestedTabRaw === requestedTab) return
@ -724,7 +737,7 @@ function Dashboard({ me }: { me: any | null }) {
{tab === 'personal' && <PerformanceSurveyWorkspace canCreateSurvey={canCreateSurvey} />}
{tab === 'public' && <PerformanceDashboardBoard view="public" />}
{tab === 'manage' && (
{tab === 'manage' && permissionsResolved && canCreateSurvey && (
<ManagePanel currentEmployee={me?.employee || null} />
)}
</main>
@ -3823,7 +3836,7 @@ function NotificationList({
)
}
function SurveySubmit({ surveyId, session }: { surveyId: string; session: any }) {
function SurveySubmit({ surveyId, session, canCreateSurvey }: { surveyId: string; session: any; canCreateSurvey: boolean }) {
const router = useRouter()
const searchParams = useSearchParams()
const targetIdParam = searchParams.get('targetId')
@ -4088,13 +4101,15 @@ function SurveySubmit({ surveyId, session }: { surveyId: string; session: any })
>
公共看板
</button>
<button
type="button"
onClick={() => goToSurveyTab('manage')}
className="block w-full border-t border-[#edf2f7] px-4 py-3 text-left text-[14px] font-semibold text-[#101828] active:bg-[#f3f7fc]"
>
发起调研
</button>
{canCreateSurvey && (
<button
type="button"
onClick={() => goToSurveyTab('manage')}
className="block w-full border-t border-[#edf2f7] px-4 py-3 text-left text-[14px] font-semibold text-[#101828] active:bg-[#f3f7fc]"
>
发起调研
</button>
)}
</div>
)}
<button

View File

@ -718,6 +718,42 @@ describe('performance survey service policies', () => {
expect(prisma.performanceSurveyEmployeeProfile.findMany).toHaveBeenCalled()
})
test.each(['商品企划部', '空间视觉部'])(
'品牌中心%s不在普通人员发起范围内,canCreate 与创建接口保持一致',
async (departmentName) => {
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockResolvedValue({
...baseEmployee,
departmentName,
departmentPath: `集团A/品牌中心/${departmentName}`,
})
await expect(getPerformanceSurveyMe(session)).resolves.toEqual(expect.objectContaining({
permissions: expect.objectContaining({ canCreate: false }),
}))
await expect(createPerformanceSurvey(session, {
templateCode: 'course_share',
assessmentMonth: '2026-07',
targetEmployeeIds: ['employee-1'],
evaluatorEmployeeIds: ['employee-2'],
})).rejects.toEqual(new PerformanceSurveyApiError('只有系统管理员,或钉钉组织位于品牌中心、摄影中心、综合支持部的人员可以发起考核调研', 403))
expect(prisma.performanceSurveyEmployeeProfile.findMany).not.toHaveBeenCalled()
expect(prisma.$transaction).not.toHaveBeenCalled()
},
)
test('系统管理员属于品牌中心未开放部门时仍保留全局发起能力', async () => {
;(prisma.user.findUnique as jest.Mock).mockResolvedValue({ ...baseUser, role: 'ADMIN' })
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockResolvedValue({
...baseEmployee,
departmentName: '商品企划部',
departmentPath: '集团A/品牌中心/商品企划部',
})
await expect(getPerformanceSurveyMe(session)).resolves.toEqual(expect.objectContaining({
permissions: expect.objectContaining({ canCreate: true }),
}))
})
test('综合支持部普通人员可发起考核调研', async () => {
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockResolvedValue({
...baseEmployee,
@ -819,6 +855,163 @@ describe('performance survey service policies', () => {
]))
})
test.each([
['无邪', '09061817188066'],
['伯言', '09061617282237'],
['清云', '09053022115891'],
])('%s的视觉评分直属主管按钉钉唯一值固定为元泽', async (displayName, dingtalkUserId) => {
const target = {
...baseEmployee,
id: `employee-${displayName}`,
displayName,
flowerName: displayName,
dingtalkUserId,
managerDingtalkUserId: 'stale-manager',
}
const yuanzhe = {
...baseEmployee,
id: 'employee-yuanzhe',
displayName: '元泽',
flowerName: '元泽',
dingtalkUserId: '27102756692071120919',
}
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockResolvedValue(target)
;(getPerformanceSurveyTemplate as jest.Mock).mockResolvedValue({
code: 'visual_brand_tone',
name: '品牌调性视觉评分',
shortName: '视觉评分',
surveyType: 'visual_case',
weight: 1,
questions: [],
scoreBands: [],
})
;(prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock)
.mockResolvedValueOnce([target])
.mockResolvedValueOnce([yuanzhe])
;(prisma.performanceSurveyEmployeeProfile.findFirst as jest.Mock).mockResolvedValue(yuanzhe)
;(prisma.user.findMany as jest.Mock).mockResolvedValue([
{ id: 'user-target', dingtalkUserId },
{ id: 'user-yuanzhe', dingtalkUserId: '27102756692071120919' },
])
;(prisma.performanceSurvey.findUnique as jest.Mock).mockResolvedValue(buildSurvey({
templateCode: 'visual_brand_tone',
targets: [{
id: 'target-person',
employeeProfileId: target.id,
targetType: 'employee',
targetName: displayName,
targetSnapshot: {},
responses: [],
assignments: [],
workItems: [],
}],
}))
await createPerformanceSurvey(session, {
templateCode: 'visual_brand_tone',
assessmentMonth: '2026-07',
openNow: false,
})
expect(prisma.performanceSurveyEmployeeProfile.findFirst).toHaveBeenCalledWith({
where: {
AND: [
{ id: { not: '__hidden__' } },
{ dingtalkUserId: '27102756692071120919' },
],
},
})
const assignmentRows = transactionClient.performanceSurveyAssignment.createMany.mock.calls[0][0].data
expect(assignmentRows).toEqual(expect.arrayContaining([
expect.objectContaining({
evaluatorEmployeeId: 'employee-yuanzhe',
evaluatorSnapshot: expect.objectContaining({ performanceSurveyWorkflowRole: 'visual_final' }),
}),
]))
expect(assignmentRows.some((row: any) => row.evaluatorSnapshot?.performanceSurveyWorkflowRole === 'manager')).toBe(false)
})
test.each([
'集团A/摄影中心/摄影一部',
'摄影中心/摄影一部',
])('摄影中心人员的视觉评分直属主管按完整路径段固定为观世:%s', async (departmentPath) => {
const target = {
...baseEmployee,
id: 'employee-photographer',
displayName: '摄影师',
dingtalkUserId: 'ding-photographer',
departmentName: '摄影一部',
departmentPath,
managerDingtalkUserId: 'stale-manager',
}
const yuanzhe = {
...baseEmployee,
id: 'employee-yuanzhe',
displayName: '元泽',
dingtalkUserId: '27102756692071120919',
}
const guanshi = {
...baseEmployee,
id: 'employee-guanshi',
displayName: '观世',
dingtalkUserId: '17642061233583361',
}
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockResolvedValue(target)
;(getPerformanceSurveyTemplate as jest.Mock).mockResolvedValue({
code: 'visual_brand_tone',
name: '品牌调性视觉评分',
shortName: '视觉评分',
surveyType: 'visual_case',
weight: 1,
questions: [],
scoreBands: [],
})
;(prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock)
.mockResolvedValueOnce([target])
.mockResolvedValueOnce([yuanzhe])
;(prisma.performanceSurveyEmployeeProfile.findFirst as jest.Mock).mockResolvedValue(guanshi)
;(prisma.user.findMany as jest.Mock).mockResolvedValue([
{ id: 'user-target', dingtalkUserId: 'ding-photographer' },
{ id: 'user-yuanzhe', dingtalkUserId: '27102756692071120919' },
{ id: 'user-guanshi', dingtalkUserId: '17642061233583361' },
])
;(prisma.performanceSurvey.findUnique as jest.Mock).mockResolvedValue(buildSurvey({
templateCode: 'visual_brand_tone',
targets: [{
id: 'target-photographer',
employeeProfileId: target.id,
targetType: 'employee',
targetName: '摄影师',
targetSnapshot: {},
responses: [],
assignments: [],
workItems: [],
}],
}))
await createPerformanceSurvey(session, {
templateCode: 'visual_brand_tone',
assessmentMonth: '2026-07',
openNow: false,
})
expect(prisma.performanceSurveyEmployeeProfile.findFirst).toHaveBeenCalledWith({
where: {
AND: [
{ id: { not: '__hidden__' } },
{ dingtalkUserId: '17642061233583361' },
],
},
})
const assignmentRows = transactionClient.performanceSurveyAssignment.createMany.mock.calls[0][0].data
expect(assignmentRows).toEqual(expect.arrayContaining([
expect.objectContaining({
evaluatorEmployeeId: 'employee-guanshi',
evaluatorSnapshot: expect.objectContaining({ performanceSurveyWorkflowRole: 'manager' }),
}),
]))
})
test('修改月份命中另一条同人同月同模板调研时拒绝更新', async () => {
transactionClient.performanceSurveyTarget.findMany.mockResolvedValue([{
targetName: '测试人员',

View File

@ -539,9 +539,24 @@ function isVisualCaseTemplate(templateOrCode?: Pick<PerformanceSurveyTemplateSha
}
const VISUAL_CREATOR_ORGANIZATIONS = new Set(['品牌中心', '摄影中心', '综合支持部'])
const PERFORMANCE_SURVEY_EXCLUDED_CREATOR_DEPARTMENTS = new Set(['商品企划部', '空间视觉部'])
const VISUAL_FINAL_EVALUATOR_NAME = '元泽'
const VISUAL_FINAL_EVALUATOR_DINGTALK_USER_ID = '27102756692071120919'
const PHOTOGRAPHY_CENTER_MANAGER_DINGTALK_USER_ID = '17642061233583361'
const FIXED_MANAGER_DINGTALK_USER_ID_BY_EMPLOYEE = new Map([
['09061817188066', VISUAL_FINAL_EVALUATOR_DINGTALK_USER_ID], // 无邪 -> 元泽
['09061617282237', VISUAL_FINAL_EVALUATOR_DINGTALK_USER_ID], // 伯言 -> 元泽
['09053022115891', VISUAL_FINAL_EVALUATOR_DINGTALK_USER_ID], // 清云 -> 元泽
])
function isExcludedPerformanceSurveyCreatorOrganization(employee: any) {
const pathParts = parseDepartmentPathParts(employee?.departmentPath)
return pathParts.includes('品牌中心')
&& pathParts.some((part) => PERFORMANCE_SURVEY_EXCLUDED_CREATOR_DEPARTMENTS.has(part))
}
function isAllowedPerformanceSurveyCreator(employee: any) {
if (isExcludedPerformanceSurveyCreatorOrganization(employee)) return false
const pathParts = parseDepartmentPathParts(employee?.departmentPath)
const organizationParts = pathParts.length > 0
? pathParts
@ -549,6 +564,23 @@ function isAllowedPerformanceSurveyCreator(employee: any) {
return organizationParts.some((part) => VISUAL_CREATOR_ORGANIZATIONS.has(part))
}
function canCreatePerformanceSurvey(ctx: Pick<UserContext, 'isSystemAdmin' | 'employee'>) {
return Boolean(ctx.isSystemAdmin || (ctx.employee && isAllowedPerformanceSurveyCreator(ctx.employee)))
}
function getConfiguredVisualManagerDingtalkUserId(employee: any) {
const employeeDingtalkUserId = clean(employee?.dingtalkUserId)
const employeeOverride = employeeDingtalkUserId
? FIXED_MANAGER_DINGTALK_USER_ID_BY_EMPLOYEE.get(employeeDingtalkUserId)
: null
if (employeeOverride) return employeeOverride
const departmentParts = parseDepartmentPathParts(employee?.departmentPath)
return departmentParts.includes('摄影中心')
? PHOTOGRAPHY_CENTER_MANAGER_DINGTALK_USER_ID
: null
}
function readWorkflowRole(snapshot: unknown) {
if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) return null
return clean((snapshot as Record<string, unknown>).performanceSurveyWorkflowRole)
@ -864,7 +896,7 @@ export async function getPerformanceSurveyMe(session: Session | null) {
isLeadership: ctx.isLeadership,
scopeDepartment: ctx.scopeDepartment,
scopeDepartmentPath: ctx.scopeDepartmentPath,
canCreate: Boolean(ctx.isSystemAdmin || (ctx.employee && isAllowedPerformanceSurveyCreator(ctx.employee))),
canCreate: canCreatePerformanceSurvey(ctx),
},
}
}
@ -1319,7 +1351,7 @@ export async function listPerformanceSurveys(session: Session | null, params?: U
isLeadership: ctx.isLeadership,
scopeDepartment: ctx.scopeDepartment,
scopeDepartmentPath: ctx.scopeDepartmentPath,
canCreate: true,
canCreate: canCreatePerformanceSurvey(ctx),
},
}
}
@ -1988,7 +2020,7 @@ export async function getPerformanceSurveyDashboardDetail(session: Session | nul
export async function createPerformanceSurvey(session: Session | null, body: any) {
const ctx = await getPerformanceSurveyContext(session)
if (!ctx.isSystemAdmin && (!ctx.employee || !isAllowedPerformanceSurveyCreator(ctx.employee))) {
if (!canCreatePerformanceSurvey(ctx)) {
throw new PerformanceSurveyApiError('只有系统管理员,或钉钉组织位于品牌中心、摄影中心、综合支持部的人员可以发起考核调研', 403)
}
@ -3433,13 +3465,7 @@ async function resolveVisualSurveyEvaluators(targetEmployee: any) {
const accountWhere = await getPerformanceSurveyAccountProfileWhere()
const yuanzheCandidates = await prisma.performanceSurveyEmployeeProfile.findMany({
where: {
AND: [accountWhere, {
OR: [
{ displayName: VISUAL_FINAL_EVALUATOR_NAME },
{ flowerName: VISUAL_FINAL_EVALUATOR_NAME },
{ realName: VISUAL_FINAL_EVALUATOR_NAME },
],
}],
AND: [accountWhere, { dingtalkUserId: VISUAL_FINAL_EVALUATOR_DINGTALK_USER_ID }],
},
take: 2,
})
@ -3448,12 +3474,16 @@ async function resolveVisualSurveyEvaluators(targetEmployee: any) {
}
let manager: any | null = null
const managerDingtalkUserId = clean(targetEmployee.managerDingtalkUserId)
const configuredManagerDingtalkUserId = getConfiguredVisualManagerDingtalkUserId(targetEmployee)
const managerDingtalkUserId = configuredManagerDingtalkUserId || clean(targetEmployee.managerDingtalkUserId)
if (managerDingtalkUserId) {
manager = await prisma.performanceSurveyEmployeeProfile.findFirst({
where: { AND: [accountWhere, { dingtalkUserId: managerDingtalkUserId }] },
})
}
if (configuredManagerDingtalkUserId && !manager) {
throw new PerformanceSurveyApiError(`无法匹配${getEmployeeDisplayName(targetEmployee)}配置的直属主管档案`, 409)
}
if (!manager) {
const departmentPath = normalizeDepartmentPath(targetEmployee.departmentPath)
if (!departmentPath) {