feat: 完善考核岗位与模板管理

This commit is contained in:
chenpei 2026-07-27 18:00:10 +08:00
parent acc93b5400
commit b2c3b20390
7 changed files with 627 additions and 405 deletions

View File

@ -10,7 +10,7 @@ const templateDefinition = {
description: '视觉案例评分',
surveyType: 'visual_case',
weight: 1,
maxTotal: 120,
maxTotal: 60,
questionMaxScore: 20,
requiredWorkItemCount: 3,
workItemImageRequired: true,
@ -201,7 +201,7 @@ describe('PerformanceSurveyAdminConfig', () => {
await waitFor(() => expect(screen.getByLabelText('岗位名称')).toHaveValue('AI 技术设计师'))
})
test('岗位页明确区分未发布草稿与当前生效方案', async () => {
test('岗位页以搜索方式维护草稿考核项,并只展示已选择内容', async () => {
const configuration = {
...config,
groups: config.groups.map((group: any) => group.id === 'group-1'
@ -219,9 +219,28 @@ describe('PerformanceSurveyAdminConfig', () => {
const request = createRequest(configuration)
render(<PerformanceSurveyAdminConfig mode="positions" request={request} />)
await waitFor(() => expect(screen.getByRole('heading', { name: '方案草稿中的考核项' })).toBeInTheDocument())
expect(screen.getByText('以下内容尚未生效;请前往“岗位考核方案”检查并发布。')).toBeInTheDocument()
expect(screen.queryByRole('heading', { name: '2026-07 当前生效的考核项' })).not.toBeInTheDocument()
await waitFor(() => expect(screen.getByRole('heading', { name: '岗位考核项' })).toBeInTheDocument())
expect(screen.getByText('课程分享')).toBeInTheDocument()
expect(screen.queryByText('视觉案例评分')).not.toBeInTheDocument()
fireEvent.change(screen.getByLabelText('添加考核项'), { target: { value: '视觉案例' } })
fireEvent.click(screen.getByRole('button', { name: /视觉案例评分/ }))
expect(screen.getByText('视觉案例评分')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: '保存修改' }))
await waitFor(() => {
const call = request.mock.calls.find(([path, options]) => (
path === '/admin/position-groups/group-1' && options?.method === 'PATCH'
))
expect(JSON.parse(String(call?.[1]?.body || '{}'))).toEqual({
name: '品牌设计师',
sortOrder: 10,
templateVersionIds: ['version-2', 'version-1'],
effectiveMonth: '2026-07',
})
})
expect(screen.queryByText('人员匹配规则')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: '复制岗位' })).not.toBeInTheDocument()
})
test('新增岗位使用确定的 collection POST 契约', async () => {
@ -240,28 +259,6 @@ describe('PerformanceSurveyAdminConfig', () => {
})))
})
test('复制岗位只要求管理人员填写名称和原因', async () => {
const request = createRequest()
const prompt = jest.spyOn(window, 'prompt')
.mockReturnValueOnce('品牌设计师(副本)')
.mockReturnValueOnce('复用现有配置')
render(<PerformanceSurveyAdminConfig mode="positions" request={request} />)
await waitFor(() => expect(screen.getByText('品牌设计师')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: '复制岗位' }))
await waitFor(() => expect(request).toHaveBeenCalledWith('/admin/position-groups/group-1/copy', expect.objectContaining({
method: 'POST',
body: JSON.stringify({
name: '品牌设计师(副本)',
month: '2026-07',
reason: '复用现有配置',
}),
})))
expect(prompt).toHaveBeenCalledTimes(2)
expect(prompt.mock.calls.flat().join(' ')).not.toContain('岗位代码')
})
test('人员批量分配提交最终 REST 请求体', async () => {
const request = createRequest()
render(<PerformanceSurveyAdminConfig mode="people" request={request} />)
@ -288,18 +285,19 @@ describe('PerformanceSurveyAdminConfig', () => {
})
})
test('模板发布前要求先保存 dirty 草稿,并提供复制与归档入口', async () => {
test('已发布模板通过修改按钮生成草稿,并使用统一的删除入口', async () => {
const request = createRequest()
render(<PerformanceSurveyAdminConfig mode="templates" request={request} />)
await waitFor(() => expect(screen.getByText(/v1 · 已发布/)).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: '复制为新草稿' }))
fireEvent.click(screen.getByRole('button', { name: '修改模板' }))
await waitFor(() => expect(request).toHaveBeenCalledWith('/admin/templates/version-1/clone', expect.objectContaining({ method: 'POST' })))
fireEvent.change(screen.getByLabelText('模板名称'), { target: { value: '新视觉评分' } })
fireEvent.click(screen.getByRole('button', { name: /发布至/ }))
expect(await screen.findByText('请先保存模板草稿,再执行发布')).toBeInTheDocument()
expect(screen.getByRole('button', { name: '归档模板' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: '删除模板' })).toBeInTheDocument()
expect(screen.queryByText('使用场景')).not.toBeInTheDocument()
})
test('模板编辑按基本信息、评分项、评审与计分分步展示', async () => {
@ -311,20 +309,56 @@ describe('PerformanceSurveyAdminConfig', () => {
fireEvent.click(screen.getByRole('button', { name: '2. 评分项' }))
expect(screen.getByRole('heading', { name: '评分项' })).toBeInTheDocument()
expect(screen.getByLabelText('评分项名称')).toHaveValue('作品质量')
expect(screen.getByLabelText('总分')).toHaveValue(60)
fireEvent.click(screen.getByRole('button', { name: '3. 评审与计分' }))
expect(screen.getByRole('heading', { name: '评审与计分' })).toBeInTheDocument()
expect(screen.getByLabelText('最终成绩规则')).toBeInTheDocument()
})
test('岗位考核方案可添加排序模板并经过影响确认后发布', async () => {
const request = createRequest()
test('模板草稿可自由增删评分项并显示总分分配状态', async () => {
const configuration = {
...config,
templates: config.templates.map((template: any) => template.id === 'template-1'
? {
...template,
versions: template.versions.map((version: any) => ({ ...version, status: 'draft', effectiveMonth: null })),
}
: template),
}
const request = createRequest(configuration)
render(<PerformanceSurveyAdminConfig mode="templates" request={request} />)
await waitFor(() => expect(screen.getByRole('button', { name: '2. 评分项' })).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: '2. 评分项' }))
fireEvent.click(screen.getByRole('button', { name: '删除评分项 1' }))
expect(screen.getByText('还没有评分项,请点击“添加评分项”')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: '添加评分项' }))
expect(screen.getByLabelText('评分项名称')).toHaveValue('评分项 1')
expect(screen.getByText('已分配 20 × 3 个作品 = 60 / 60 分')).toBeInTheDocument()
})
test('岗位考核方案只复核岗位页草稿,并经过影响确认后发布', async () => {
const configuration = {
...config,
groups: config.groups.map((group: any) => group.id === 'group-1'
? {
...group,
draftPlan: {
id: 'plan-1',
version: 2,
effectiveMonth: '2026-07',
templateVersionIds: ['version-1', 'version-2'],
},
}
: group),
}
const request = createRequest(configuration)
render(<PerformanceSurveyAdminConfig mode="plans" request={request} />)
await waitFor(() => expect(screen.getByRole('heading', { name: '岗位考核方案' })).toBeInTheDocument())
const courseLabel = screen.getByText('课程分享').closest('label')
expect(courseLabel).not.toBeNull()
fireEvent.click(courseLabel!.querySelector('input')!)
expect(screen.getByRole('heading', { name: '待发布的考核项' })).toBeInTheDocument()
expect(screen.queryByRole('heading', { name: '可用已发布模板' })).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: '发布前检查' }))
await waitFor(() => expect(screen.getByRole('region', { name: '发布影响确认' })).toBeInTheDocument())

View File

@ -10,11 +10,6 @@ type RequestFn = PerformanceSurveyAdminRequest
export type PerformanceSurveyAdminMode = 'overview' | 'positions' | 'people' | 'templates' | 'plans'
type RuleDraft = {
departmentPathPrefix: string
positionTitle: string
}
type ReviewerSource = 'self' | 'direct_manager' | 'fixed_employee' | 'manual_selection'
type ReviewerDraft = {
@ -82,7 +77,13 @@ type PositionGroupRecord = {
isActive: boolean
status: 'ready' | 'pending' | 'disabled'
memberCount: number
rules: Array<RuleDraft & { id: string; isActive: boolean; sortOrder: number }>
rules: Array<{
id: string
departmentPathPrefix: string
positionTitle: string
isActive: boolean
sortOrder: number
}>
effectivePlan: null | {
id: string
version: number
@ -132,27 +133,17 @@ const adminConfigApi = {
body: JSON.stringify(input),
})
},
copyPositionGroup(
request: RequestFn,
groupId: string,
input: { name: string; month: string; reason: string },
) {
return request<{ id?: string; group?: { id?: string } }>(`/admin/position-groups/${groupId}/copy`, {
method: 'POST',
body: JSON.stringify(input),
})
},
previewPositionGroup(request: RequestFn, groupId: string, month: string) {
return request<any>(`/admin/position-groups/${groupId}/preview?month=${encodeURIComponent(month)}`)
},
archivePositionGroup(request: RequestFn, groupId: string, reason: string) {
return request(`/admin/position-groups/${groupId}`, {
removePositionGroup(request: RequestFn, groupId: string, reason: string) {
return request<{ id: string; action: 'deleted' | 'archived' }>(`/admin/position-groups/${groupId}`, {
method: 'DELETE',
body: JSON.stringify({ mode: 'auto', reason }),
})
},
deleteOrArchiveTemplate(request: RequestFn, templateId: string, reason: string) {
return request(`/admin/templates/${templateId}`, {
removeTemplate(request: RequestFn, templateId: string, reason: string) {
return request<{ id: string; action: 'deleted' | 'archived' }>(`/admin/templates/${templateId}`, {
method: 'DELETE',
body: JSON.stringify({ mode: 'auto', reason }),
})
@ -176,8 +167,8 @@ function newTemplateDefinition(): TemplateDefinition {
description: '',
surveyType: 'person_period',
weight: 1,
maxTotal: 120,
questions: [{ id: 'score_1', title: '评分项 1', description: '', maxScore: 20 }],
maxTotal: 100,
questions: [{ id: `score_${Date.now().toString(36)}`, title: '评分项 1', description: '', maxScore: 100 }],
scoreBands: [],
workflow: {
stages: [{
@ -202,9 +193,9 @@ function reviewerSourceLabel(source: ReviewerSource) {
function surveyTypeLabel(type: TemplateDefinition['surveyType']) {
return {
person_period: '人员周期评分',
visual_case: '视觉案例评分',
item_course: '事项 / 课程评分',
person_period: '按人员评分',
visual_case: '按作品评分',
item_course: '按课程或事项评分',
}[type]
}
@ -312,7 +303,7 @@ export function PerformanceSurveyAdminConfig({
: mode === 'templates'
? '已发布模板会长期使用;只有评分规则变化时才创建新版本'
: mode === 'positions'
? '岗位名称、人员匹配规则等修改会先保存为草稿,发布后生效'
? '岗位名称、排序和考核项修改会先保存为草稿,发布后生效'
: mode === 'plans'
? `正在查看 ${month} 的生效方案;已发布方案会持续沿用`
: `正在维护 ${month};已发布版本保持不变`}
@ -397,9 +388,6 @@ export function PerformanceSurveyAdminConfig({
request={request}
onError={setError}
onChanged={changed}
onDirtyChange={setDirtyState}
confirmDiscard={confirmDiscard}
dirty={dirty}
/>
)}
</div>
@ -423,7 +411,6 @@ function AdminOverviewWorkspace({
const [auditError, setAuditError] = useState<string | null>(null)
const [auditLoading, setAuditLoading] = useState(true)
const activeGroups = data.groups.filter((group) => group.status !== 'disabled')
const groupsWithMatchingRules = activeGroups.filter((group) => group.rules.some((rule) => rule.isActive)).length
const disabledGroups = data.groups.filter((group) => group.status === 'disabled').length
const draftTemplates = data.templates.flatMap((template) => template.versions).filter((version) => version.status === 'draft').length
const publishedTemplates = data.templates.flatMap((template) => template.versions).filter((version) => version.status === 'published').length
@ -439,7 +426,7 @@ function AdminOverviewWorkspace({
)).length
const draftPlanCount = activeGroups.filter((group) => group.draftPlan).length
const hasPeopleIssues = data.issues.unmatched.length > 0 || data.issues.conflicts.length > 0
const positionsReady = activeGroups.length > 0 && groupsWithMatchingRules === activeGroups.length
const positionsReady = activeGroups.length > 0
const templatesReady = availablePublishedTemplates > 0
const plansReady = activeGroups.length > 0 && effectivePlanCount === activeGroups.length
const launchReady = positionsReady && templatesReady && plansReady && data.issues.conflicts.length === 0
@ -462,7 +449,7 @@ function AdminOverviewWorkspace({
status: positionsReady ? 'done' : 'attention',
summary: activeGroups.length === 0
? '还没有可用岗位'
: `${groupsWithMatchingRules}/${activeGroups.length} 个在用岗位已完成匹配规则${disabledGroups > 0 ? `,另有 ${disabledGroups} 个已归档` : ''}`,
: `${activeGroups.length} 个岗位可用;人员归属请在“人员分配”中维护${disabledGroups > 0 ? `,另有 ${disabledGroups} 个已删除` : ''}`,
action: '管理岗位',
target: 'positions' as const,
},
@ -641,13 +628,10 @@ function PositionConfigWorkspace({
const selected = data.groups.find((group) => group.id === selectedId) || data.groups[0]
const [name, setName] = useState(selected?.name || '')
const [sortOrder, setSortOrder] = useState(selected?.sortOrder || 0)
const [rules, setRules] = useState<RuleDraft[]>(selected?.rules.map((rule) => ({
departmentPathPrefix: rule.departmentPathPrefix || '',
positionTitle: rule.positionTitle || '',
})) || [])
const [templateVersionIds, setTemplateVersionIds] = useState<string[]>(
selected?.draftPlan?.templateVersionIds || selected?.effectivePlan?.templateVersionIds || [],
)
const [templateSearch, setTemplateSearch] = useState('')
const [saving, setSaving] = useState(false)
const [creating, setCreating] = useState(false)
const [newName, setNewName] = useState('')
@ -657,11 +641,8 @@ function PositionConfigWorkspace({
if (!selected) return
setName(selected.name)
setSortOrder(selected.sortOrder)
setRules(selected.rules.map((rule) => ({
departmentPathPrefix: rule.departmentPathPrefix || '',
positionTitle: rule.positionTitle || '',
})))
setTemplateVersionIds(selected.draftPlan?.templateVersionIds || selected.effectivePlan?.templateVersionIds || [])
setTemplateSearch('')
onDirtyChange(false)
}, [onDirtyChange, selected])
@ -669,9 +650,30 @@ function PositionConfigWorkspace({
const publishedVersions = useMemo(() => data.templates.flatMap((template) => (
template.versions
.filter((version) => version.status === 'published')
.filter((version) => (
version.status === 'published'
&& (!version.effectiveMonth || version.effectiveMonth <= month)
))
.map((version) => ({ template, version }))
)), [data.templates])
)), [data.templates, month])
const versionById = useMemo(
() => new Map(publishedVersions.map((item) => [item.version.id, item])),
[publishedVersions],
)
const searchResults = useMemo(() => {
const keyword = templateSearch.trim().toLocaleLowerCase('zh-CN')
if (!keyword) return []
const selectedTemplateIds = new Set(
templateVersionIds
.map((id) => versionById.get(id)?.template.id)
.filter(Boolean),
)
return publishedVersions.filter(({ template, version }) => (
!templateVersionIds.includes(version.id)
&& !selectedTemplateIds.has(template.id)
&& `${version.definition.name} ${template.name}`.toLocaleLowerCase('zh-CN').includes(keyword)
)).slice(0, 8)
}, [publishedVersions, templateSearch, templateVersionIds, versionById])
if (!selected) return <div className="px-5 py-12 text-center text-sm text-[#727687]">暂无岗位组</div>
@ -681,9 +683,9 @@ function PositionConfigWorkspace({
try {
await request(`/admin/position-groups/${selected.id}`, {
method: 'PATCH',
body: JSON.stringify({ name, sortOrder, rules, templateVersionIds, effectiveMonth: month }),
body: JSON.stringify({ name, sortOrder, templateVersionIds, effectiveMonth: month }),
})
await onChanged('岗位方案草稿已保存')
await onChanged('岗位和考核项修改已保存,发布后生效')
} catch (actionError) {
onError(actionError instanceof Error ? actionError.message : '岗位方案保存失败')
} finally {
@ -715,46 +717,52 @@ function PositionConfigWorkspace({
}
}
const copyGroup = async () => {
const removeGroup = async () => {
if (!selected || !confirmDiscard()) return
const copyName = window.prompt('请输入复制后的岗位名称', `${selected.name}(副本)`)?.trim()
if (!copyName) return
const reason = window.prompt('请输入复制原因', `基于“${selected.name}”创建新岗位`)?.trim()
const memberWarning = selected.memberCount > 0
? `当前仍有 ${selected.memberCount} 人属于该岗位,删除后这些人员会变为待分配。`
: '该岗位当前没有人员。'
if (!window.confirm(`确认删除岗位“${selected.name}”吗?${memberWarning}历史调研记录不会删除。`)) return
const reason = window.prompt('请输入删除原因(用于操作记录)')?.trim()
if (!reason) return
setSaving(true)
onError(null)
try {
const copied = await adminConfigApi.copyPositionGroup(request, selected.id, {
name: copyName,
month,
reason,
})
const next = await onChanged(`已复制“${selected.name}”`)
if (copied.id || copied.group?.id) setSelectedId(copied.id || copied.group?.id || '')
else if (next?.groups.length) setSelectedId(next.groups[next.groups.length - 1].id)
const result = await adminConfigApi.removePositionGroup(request, selected.id, reason)
const next = await onChanged(
result.action === 'deleted'
? `岗位“${selected.name}”已删除`
: `岗位“${selected.name}”已从管理列表删除,历史记录已保留`,
)
setSelectedId(next?.groups[0]?.id || '')
} catch (actionError) {
onError(actionError instanceof Error ? actionError.message : '岗位复制失败')
onError(actionError instanceof Error ? actionError.message : '岗位删除失败')
} finally {
setSaving(false)
}
}
const archiveGroup = async () => {
if (!selected || !confirmDiscard()) return
if (!window.confirm(`确认归档“${selected.name}”吗?归档前请确认相关人员已完成转岗。`)) return
const reason = window.prompt('请输入删除或归档原因')?.trim()
if (!reason) return
setSaving(true)
onError(null)
try {
await adminConfigApi.archivePositionGroup(request, selected.id, reason)
const next = await onChanged(`“${selected.name}”已归档`)
setSelectedId(next?.groups.find((group) => group.status !== 'disabled')?.id || next?.groups[0]?.id || '')
} catch (actionError) {
onError(actionError instanceof Error ? actionError.message : '岗位归档失败')
} finally {
setSaving(false)
}
const addTemplateVersion = (versionId: string) => {
setTemplateVersionIds((current) => current.includes(versionId) ? current : [...current, versionId])
setTemplateSearch('')
markDirty()
}
const removeTemplateVersion = (versionId: string) => {
setTemplateVersionIds((current) => current.filter((id) => id !== versionId))
markDirty()
}
const moveTemplateVersion = (index: number, direction: -1 | 1) => {
const targetIndex = index + direction
if (targetIndex < 0 || targetIndex >= templateVersionIds.length) return
setTemplateVersionIds((current) => {
const next = [...current]
const [moved] = next.splice(index, 1)
next.splice(targetIndex, 0, moved)
return next
})
markDirty()
}
const selectGroup = (groupId: string) => {
@ -816,147 +824,86 @@ function PositionConfigWorkspace({
<div className="mb-4 flex flex-wrap items-center justify-between gap-3 border-b border-[#e2e2e2] pb-3">
<div>
<div className="text-[12px] font-bold text-[#0050cb]">正在编辑:{selected.name}</div>
<p className="mt-1 text-[11px] leading-5 text-[#5f5e5e]">岗位名称、排序和人员匹配规则保存后进入草稿,需要发布岗位考核方案后才会生效。</p>
</div>
<div className="flex flex-wrap gap-2">
<button type="button" disabled={saving} onClick={() => void copyGroup()} className="min-h-10 rounded border border-[#c2c6d8] px-3 text-[12px] font-bold text-[#1a1c1c] hover:bg-[#f4f3f3]">复制岗位</button>
{selected.status !== 'disabled' && (
<button type="button" disabled={saving} onClick={() => void archiveGroup()} className="min-h-10 rounded border border-[#f0b8b8] px-3 text-[12px] font-bold text-[#b42318] hover:bg-[#fff5f5]">归档岗位</button>
)}
<p className="mt-1 text-[11px] leading-5 text-[#5f5e5e]">岗位名称、排序和考核项保存后进入草稿,需要发布岗位考核方案后才会生效。</p>
</div>
<button type="button" disabled={saving} onClick={() => void removeGroup()} className="min-h-10 rounded border border-[#f0b8b8] px-3 text-[12px] font-bold text-[#b42318] hover:bg-[#fff5f5]">
删除岗位
</button>
</div>
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_120px]">
<div className="grid min-w-0 gap-4 lg:grid-cols-[minmax(0,1fr)_140px]">
<AdminField label="岗位名称" value={name} onChange={(value) => { setName(value); markDirty() }} />
<AdminField label="排序" value={String(sortOrder)} onChange={(value) => { setSortOrder(Number(value) || 0); markDirty() }} type="number" />
</div>
<div className="mt-6 border-t border-[#eeeeee] pt-5">
<div className="flex items-center justify-between gap-3">
<div>
<h3 className="text-[14px] font-bold text-[#1a1c1c]">人员匹配规则</h3>
<p className="mt-1 text-[12px] text-[#727687]">每行内条件同时满足,多行之间满足任意一行即可</p>
</div>
<button
type="button"
onClick={() => {
setRules((current) => [...current, { departmentPathPrefix: '', positionTitle: '' }])
markDirty()
}}
className="min-h-11 rounded border border-[#c2c6d8] px-3 text-[12px] font-bold text-[#1a1c1c] hover:bg-[#f4f3f3]"
>
添加规则
</button>
</div>
<div className="mt-3 grid gap-2">
{rules.map((rule, index) => (
<div key={index} className="grid gap-2 sm:grid-cols-[minmax(0,1fr)_minmax(180px,0.7fr)_36px]">
<input
value={rule.departmentPathPrefix}
onChange={(event) => {
setRules((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, departmentPathPrefix: event.target.value } : item))
markDirty()
}}
placeholder="部门路径前缀,例如 品牌中心/品牌创意A部"
aria-label={`规则 ${index + 1} 部门路径前缀`}
className="h-11 rounded border border-[#c2c6d8] px-3 text-[13px] outline-none focus:border-[#0050cb]"
/>
<input
value={rule.positionTitle}
onChange={(event) => {
setRules((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, positionTitle: event.target.value } : item))
markDirty()
}}
placeholder="职位名称(精确匹配)"
aria-label={`规则 ${index + 1} 职位名称`}
className="h-11 rounded border border-[#c2c6d8] px-3 text-[13px] outline-none focus:border-[#0050cb]"
/>
<button
type="button"
aria-label="删除规则"
title="删除规则"
onClick={() => {
setRules((current) => current.filter((_, itemIndex) => itemIndex !== index))
markDirty()
}}
className="min-h-11 min-w-11 rounded border border-[#e2e2e2] text-[18px] text-[#8c1d18] hover:bg-[#fff6f4]"
>
×
</button>
</div>
))}
{rules.length === 0 && <div className="border border-dashed border-[#d0d0d0] px-4 py-6 text-center text-[12px] text-[#727687]">未配置规则,岗位不能发布</div>}
</div>
</div>
<div className="mt-6 border-t border-[#eeeeee] pt-5">
<h3 className="text-[14px] font-bold text-[#1a1c1c]">
{selected.draftPlan ? '方案草稿中的考核项' : `${month} 当前生效的考核项`}
</h3>
<p className="mt-1 text-[12px] text-[#5f5e5e]">
{selected.draftPlan
? '以下内容尚未生效;请前往“岗位考核方案”检查并发布。'
: '这里只读展示;添加、移除和排序请前往“岗位考核方案”。'}
<h3 className="text-[14px] font-bold text-[#1a1c1c]">岗位考核项</h3>
<p className="mt-1 text-[12px] leading-5 text-[#5f5e5e]">
在这里选择该岗位需要参加的考核。保存后会形成草稿,再到“岗位考核方案”检查并发布。
</p>
<div className="mt-3 grid gap-2">
{publishedVersions.map(({ template, version }) => {
const checked = templateVersionIds.includes(version.id)
<div className="relative mt-4 max-w-xl">
<label className="grid gap-1 text-[12px] font-semibold text-[#5f5e5e]">
添加考核项
<input
value={templateSearch}
onChange={(event) => setTemplateSearch(event.target.value)}
placeholder="输入模板名称搜索"
className="h-11 w-full rounded border border-[#c2c6d8] px-3 text-[13px] outline-none focus:border-[#0050cb]"
/>
</label>
{templateSearch.trim() && (
<div className="absolute z-30 mt-1 max-h-64 w-full overflow-y-auto border border-[#c2c6d8] bg-white shadow-[0_4px_8px_rgba(0,0,0,0.12)]">
{searchResults.map(({ template, version }) => (
<button
key={version.id}
type="button"
onClick={() => addTemplateVersion(version.id)}
className="flex min-h-11 w-full items-center justify-between gap-3 border-b border-[#eeeeee] px-3 py-2 text-left last:border-b-0 hover:bg-[#f4f6ff]"
>
<span className="min-w-0">
<span className="block truncate text-[13px] font-bold text-[#1a1c1c]">{version.definition.name}</span>
</span>
<span className="shrink-0 text-[11px] text-[#5f5e5e]">v{version.version}</span>
</button>
))}
{searchResults.length === 0 && (
<div className="px-3 py-4 text-center text-[12px] text-[#727687]">没有可添加的匹配模板</div>
)}
</div>
)}
</div>
<div className="mt-4 grid gap-2">
{templateVersionIds.map((id, index) => {
const item = versionById.get(id)
return (
<label key={version.id} className={`grid grid-cols-[20px_minmax(0,1fr)_auto] items-center gap-3 border px-3 py-3 ${checked ? 'border-[#b3c5ff] bg-[#f8faff]' : 'border-[#eeeeee]'}`}>
<input
type="checkbox"
checked={checked}
disabled
/>
<span className="min-w-0 truncate text-[13px] font-semibold text-[#1a1c1c]">{version.definition.shortName || template.name}</span>
<span className="text-[11px] text-[#727687]">v{version.version}</span>
</label>
<div key={id} className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-3 border border-[#c2c6d8] px-3 py-3">
<div className="min-w-0">
<div className="truncate text-[13px] font-bold text-[#1a1c1c]">{item?.version.definition.name || item?.template.name || '历史模板'}</div>
<div className="mt-0.5 text-[11px] text-[#727687]">
第 {index + 1} 项{item ? ` · v${item.version.version}` : ''}
</div>
</div>
<div className="flex flex-wrap justify-end gap-1">
<button type="button" disabled={index === 0} onClick={() => moveTemplateVersion(index, -1)} className="min-h-10 rounded px-3 text-[12px] font-bold text-[#0050cb] disabled:text-[#aaaaaa]">上移</button>
<button type="button" disabled={index === templateVersionIds.length - 1} onClick={() => moveTemplateVersion(index, 1)} className="min-h-10 rounded px-3 text-[12px] font-bold text-[#0050cb] disabled:text-[#aaaaaa]">下移</button>
<button type="button" onClick={() => removeTemplateVersion(id)} className="min-h-10 rounded px-3 text-[12px] font-bold text-[#b42318] hover:bg-[#fff5f5]">移除</button>
</div>
</div>
)
})}
{templateVersionIds.length === 0 && (
<div className="border border-dashed border-[#c2c6d8] px-4 py-7 text-center text-[12px] text-[#727687]">
尚未选择考核项,请通过上方搜索框添加
</div>
)}
</div>
</div>
<div className="sticky bottom-[68px] z-20 -mx-4 mt-6 flex flex-wrap items-center justify-between gap-2 border-t border-[#c2c6d8] bg-white/95 px-4 py-3 shadow-[0_-4px_10px_rgba(0,0,0,0.06)] backdrop-blur sm:bottom-0 sm:mx-0 sm:justify-end sm:shadow-none">
<span className="text-[12px] font-semibold text-[#5f5e5e] sm:mr-auto">考核模板组合与顺序请在“岗位考核方案”中维护</span>
<span className="text-[12px] font-semibold text-[#5f5e5e] sm:mr-auto">保存后请前往“岗位考核方案”发布生效</span>
<button type="button" disabled={saving || selected.status === 'disabled'} onClick={() => void save()} className="min-h-11 rounded bg-[#0050cb] px-5 text-[13px] font-bold text-white disabled:opacity-50">
{saving ? '保存中...' : '保存修改'}
</button>
</div>
{(data.issues.conflicts.length > 0 || data.issues.unmatched.length > 0) && (
<div className="mt-6 border-t border-[#eeeeee] pt-5">
<h3 className="text-[14px] font-bold text-[#1a1c1c]">配置问题</h3>
<div className="mt-2 text-[12px] text-[#727687]">
未匹配 {data.issues.unmatched.length} 人 · 重复匹配 {data.issues.conflicts.length} 人
</div>
<div className="mt-3 grid max-h-64 gap-4 overflow-y-auto pr-1 sm:grid-cols-2">
{data.issues.unmatched.length > 0 && (
<div>
<div className="mb-2 text-[12px] font-bold text-[#8a5700]">未匹配人员</div>
<div className="grid gap-2">
{data.issues.unmatched.map((item) => (
<div key={item.id} className="border-l-2 border-[#c78512] pl-3 text-[12px] text-[#5f5e5e]">
<strong className="text-[#1a1c1c]">{item.displayName}</strong>
<span className="block text-[11px] text-[#727687]">{item.departmentPath || item.departmentName || '未填写部门'} · {item.positionTitle || '未填写职位'}</span>
</div>
))}
</div>
</div>
)}
{data.issues.conflicts.length > 0 && (
<div>
<div className="mb-2 text-[12px] font-bold text-[#b42318]">重复匹配人员</div>
<div className="grid gap-2">
{data.issues.conflicts.map((item) => (
<div key={item.id} className="border-l-2 border-[#b42318] pl-3 text-[12px] text-[#5f5e5e]">
<strong className="text-[#1a1c1c]">{item.displayName}</strong>:{item.groupNames.join('、')}
</div>
))}
</div>
</div>
)}
</div>
</div>
)}
</div>
</div>
)
@ -1005,6 +952,15 @@ function TemplateConfigWorkspace({
const version = selectedTemplate?.versions.find((item) => item.id === versionId) || null
const editable = !version || version.status === 'draft'
const questionTotal = definition.questions.reduce(
(sum, question) => sum + Number(question.maxScore || definition.questionMaxScore || 20),
0,
)
const calculatedTemplateTotal = questionTotal * (
definition.surveyType === 'visual_case' ? Math.max(1, Number(definition.requiredWorkItemCount || 1)) : 1
)
const templateDefinitionReady = definition.questions.length > 0
&& Math.round(calculatedTemplateTotal * 100) === Math.round(Number(definition.maxTotal || 0) * 100)
const updateDefinition = (next: TemplateDefinition | ((current: TemplateDefinition) => TemplateDefinition)) => {
setDefinition(next)
onDirtyChange(true)
@ -1074,21 +1030,24 @@ function TemplateConfigWorkspace({
}
}
const deleteOrArchiveTemplate = async () => {
const removeTemplate = async () => {
if (!selectedTemplate || !confirmDiscard()) return
const onlyDrafts = selectedTemplate.versions.every((item) => item.status === 'draft')
const actionLabel = onlyDrafts ? '删除' : '归档'
if (!window.confirm(`确认${actionLabel}模板“${selectedTemplate.name}”吗?已被历史调研引用的数据不会删除。`)) return
const reason = window.prompt(`请输入${actionLabel}原因`)?.trim()
const displayName = version?.definition.name || selectedTemplate.versions[0]?.definition.name || selectedTemplate.name
if (!window.confirm(`确认删除模板“${displayName}”吗?已被历史调研引用的数据会保留;正在被岗位使用的模板需要先从岗位考核项中移除。`)) return
const reason = window.prompt('请输入删除原因(用于操作记录)')?.trim()
if (!reason) return
setSaving(true)
onError(null)
try {
await adminConfigApi.deleteOrArchiveTemplate(request, selectedTemplate.id, reason)
const next = await onChanged(`模板“${selectedTemplate.name}”已${actionLabel}`)
const result = await adminConfigApi.removeTemplate(request, selectedTemplate.id, reason)
const next = await onChanged(
result.action === 'deleted'
? `模板“${displayName}”已删除`
: `模板“${displayName}”已从模板列表删除,历史记录已保留`,
)
setSelectedTemplateId(next?.templates[0]?.id || 'new')
} catch (actionError) {
onError(actionError instanceof Error ? actionError.message : `模板${actionLabel}失败`)
onError(actionError instanceof Error ? actionError.message : '模板删除失败')
} finally {
setSaving(false)
}
@ -1107,13 +1066,15 @@ function TemplateConfigWorkspace({
return (
<div className="grid min-h-[680px] md:grid-cols-[260px_minmax(0,1fr)]">
<aside className="border-b border-[#e2e2e2] md:border-b-0 md:border-r">
<button
type="button"
onClick={() => selectTemplate('new')}
className={`w-full border-b border-[#eeeeee] px-4 py-3 text-left text-[13px] font-bold ${selectedTemplateId === 'new' ? 'bg-[#f1f4ff] text-[#0050cb]' : 'text-[#1a1c1c] hover:bg-[#fafafa]'}`}
>
新建模板
</button>
<div className="border-b border-[#c2c6d8] p-3">
<button
type="button"
onClick={() => selectTemplate('new')}
className="min-h-11 w-full rounded bg-[#1a1c1c] px-4 text-center text-[13px] font-bold text-white hover:bg-black"
>
新建模板
</button>
</div>
{data.templates.map((template) => (
<button
key={template.id}
@ -1121,14 +1082,14 @@ function TemplateConfigWorkspace({
onClick={() => selectTemplate(template.id)}
className={`w-full border-b border-[#eeeeee] px-4 py-3 text-left ${selectedTemplateId === template.id ? 'bg-[#f1f4ff]' : 'hover:bg-[#fafafa]'}`}
>
<span className="block truncate text-[13px] font-bold text-[#1a1c1c]">{template.name}</span>
<span className="block truncate text-[13px] font-bold text-[#1a1c1c]">{template.versions[0]?.definition.name || template.name}</span>
<span className="mt-0.5 block text-[11px] text-[#727687]">{template.versions.length} 个版本</span>
</button>
))}
</aside>
<div ref={editorRef} className="min-w-0 scroll-mt-4 p-4 sm:p-5">
<div className="mb-4 text-[12px] font-bold text-[#0050cb] md:hidden">正在编辑:{selectedTemplate?.name || '新建模板'}</div>
<div className="mb-4 text-[12px] font-bold text-[#0050cb] md:hidden">正在编辑:{definition.name || '新建模板'}</div>
{selectedTemplate && (
<div className="mb-4 flex flex-wrap items-center gap-2 border-b border-[#eeeeee] pb-3">
{selectedTemplate.versions.map((item) => (
@ -1152,10 +1113,10 @@ function TemplateConfigWorkspace({
<button
type="button"
disabled={saving}
onClick={() => void deleteOrArchiveTemplate()}
onClick={() => void removeTemplate()}
className="ml-auto min-h-10 rounded border border-[#f0b8b8] px-3 text-[12px] font-bold text-[#b42318] hover:bg-[#fff5f5] disabled:opacity-50"
>
{selectedTemplate.versions.every((item) => item.status === 'draft') ? '安全删除模板' : '归档模板'}
删除模板
</button>
</div>
)}
@ -1172,9 +1133,9 @@ function TemplateConfigWorkspace({
<div className="flex gap-5 text-right">
<div>
<div className="text-[18px] font-bold text-[#1a1c1c]">
{definition.questions.reduce((sum, question) => sum + Number(question.maxScore || definition.questionMaxScore || 20), 0)}
{Number(definition.maxTotal || 0)}
</div>
<div className="text-[11px] font-semibold text-[#727687]">评分项合计</div>
<div className="text-[11px] font-semibold text-[#727687]">模板总分</div>
</div>
<div>
<div className="text-[18px] font-bold text-[#1a1c1c]">{version ? `v${version.version}` : '新建'}</div>
@ -1211,19 +1172,23 @@ function TemplateConfigWorkspace({
<p className="mt-1 text-[12px] leading-5 text-[#727687]">管理员和员工都会看到这些名称与说明。</p>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<AdminField label="模板名称" value={definition.name} onChange={(value) => updateDefinition((current) => ({ ...current, name: value }))} disabled={!editable} />
<AdminField label="看板简称" value={definition.shortName || ''} onChange={(value) => updateDefinition((current) => ({ ...current, shortName: value }))} disabled={!editable} />
<AdminField
label="模板名称"
value={definition.name}
onChange={(value) => updateDefinition((current) => ({ ...current, name: value, shortName: value }))}
disabled={!editable}
/>
<label className="grid gap-1 text-[12px] font-semibold text-[#5f5e5e]">
使用场景
评分对象
<select
value={definition.surveyType}
disabled={!editable}
onChange={(event) => updateDefinition((current) => ({ ...current, surveyType: event.target.value as TemplateDefinition['surveyType'] }))}
className="h-11 rounded border border-[#c2c6d8] bg-white px-3 text-[13px] font-semibold text-[#1a1c1c] outline-none focus:border-[#0050cb] disabled:bg-[#f4f4f4]"
>
<option value="person_period">人员周期评分</option>
<option value="visual_case">视觉案例评分</option>
<option value="item_course">事项 / 课程评分</option>
<option value="person_period">员工表现(评价一段时间内的工作表现)</option>
<option value="visual_case">作品或案例(需要提交图片或案例)</option>
<option value="item_course">课程或事项(评价一次活动或任务)</option>
</select>
</label>
{definition.surveyType === 'visual_case' && (
@ -1245,13 +1210,6 @@ function TemplateConfigWorkspace({
/>
</label>
</div>
<details className="mt-5 border-t border-[#eeeeee] pt-4">
<summary className="min-h-11 cursor-pointer py-3 text-[12px] font-bold text-[#5f5e5e]">高级设置(一般无需修改)</summary>
<div className="mt-2 max-w-md">
<AdminField label="系统内部模板代码" value={definition.code} onChange={(value) => updateDefinition((current) => ({ ...current, code: value }))} disabled={Boolean(selectedTemplate) || !editable} />
<p className="mt-2 text-[11px] leading-5 text-[#727687]">新建时已自动生成;创建后不可修改,仅用于系统识别。</p>
</div>
</details>
</section>
)}
@ -1263,9 +1221,19 @@ function TemplateConfigWorkspace({
)}
<div className="sticky bottom-[68px] z-20 -mx-4 mt-6 flex flex-wrap justify-end gap-2 border-t border-[#c2c6d8] bg-white/95 px-4 py-3 shadow-[0_-4px_10px_rgba(0,0,0,0.06)] backdrop-blur sm:bottom-0 sm:mx-0 sm:shadow-none">
{!editable && <button type="button" disabled={saving} onClick={() => void cloneVersion()} className="min-h-11 rounded border border-[#1a1c1c] px-4 text-[13px] font-bold text-[#1a1c1c]">复制为新草稿</button>}
{!editable && <button type="button" disabled={saving} onClick={() => void cloneVersion()} className="min-h-11 rounded bg-[#0050cb] px-4 text-[13px] font-bold text-white disabled:opacity-50">修改模板</button>}
{editable && <button type="button" disabled={saving} onClick={() => void save()} className="min-h-11 rounded border border-[#1a1c1c] px-4 text-[13px] font-bold text-[#1a1c1c] disabled:opacity-50">保存草稿</button>}
{editable && versionId && <button type="button" disabled={saving} onClick={() => void publish()} className="min-h-11 rounded bg-[#0050cb] px-4 text-[13px] font-bold text-white disabled:opacity-50">发布至 {month}</button>}
{editable && versionId && (
<button
type="button"
disabled={saving || !templateDefinitionReady}
onClick={() => void publish()}
className="min-h-11 rounded bg-[#0050cb] px-4 text-[13px] font-bold text-white disabled:opacity-50"
title={templateDefinitionReady ? undefined : '请先添加评分项,并确保评分项合计与模板总分一致'}
>
发布至 {month}
</button>
)}
</div>
</div>
</div>
@ -1278,18 +1246,12 @@ function MonthlyPlanWorkspace({
request,
onError,
onChanged,
onDirtyChange,
confirmDiscard,
dirty,
}: {
data: AdminConfig
month: string
request: RequestFn
onError: (message: string | null) => void
onChanged: (message: string) => Promise<AdminConfig | null>
onDirtyChange: (dirty: boolean) => void
confirmDiscard: (message?: string) => boolean
dirty: boolean
}) {
const [selectedGroupId, setSelectedGroupId] = useState(data.groups.find((group) => group.status !== 'disabled')?.id || data.groups[0]?.id || '')
const group = data.groups.find((item) => item.id === selectedGroupId) || data.groups[0]
@ -1309,65 +1271,23 @@ function MonthlyPlanWorkspace({
if (!group) return
setTemplateVersionIds(group.draftPlan?.templateVersionIds || group.effectivePlan?.templateVersionIds || [])
setPreview(null)
onDirtyChange(false)
}, [group, onDirtyChange])
}, [group])
const changeGroup = (groupId: string) => {
if (groupId === selectedGroupId) return
if (!confirmDiscard('切换岗位会放弃当前岗位考核方案修改,确定继续吗?')) return
onDirtyChange(false)
setSelectedGroupId(groupId)
}
const moveVersion = (index: number, direction: -1 | 1) => {
const target = index + direction
if (target < 0 || target >= templateVersionIds.length) return
setTemplateVersionIds((current) => {
const next = [...current]
const [moved] = next.splice(index, 1)
next.splice(target, 0, moved)
return next
})
setPreview(null)
onDirtyChange(true)
}
const toggleVersion = (versionId: string, checked: boolean) => {
setTemplateVersionIds((current) => checked ? [...current, versionId] : current.filter((id) => id !== versionId))
setPreview(null)
onDirtyChange(true)
}
const saveDraft = async (showSuccess = true) => {
if (!group) return false
setSaving(true)
onError(null)
try {
await request(`/admin/position-groups/${group.id}`, {
method: 'PATCH',
body: JSON.stringify({ templateVersionIds, effectiveMonth: month }),
})
if (showSuccess) await onChanged(`${group.name} 的岗位考核方案草稿已保存,计划从 ${month} 起生效`)
else onDirtyChange(false)
return true
} catch (actionError) {
onError(actionError instanceof Error ? actionError.message : '岗位考核方案保存失败')
return false
} finally {
setSaving(false)
}
}
const openPublishPreview = async () => {
if (!group) return
if (!group.draftPlan) {
onError('当前没有待发布的岗位修改,请先到“岗位”页面调整考核项并保存')
return
}
if (templateVersionIds.length === 0) {
onError('岗位考核方案至少需要 1 个已发布模板')
return
}
if (dirty) {
const saved = await saveDraft(false)
if (!saved) return
}
setSaving(true)
onError(null)
try {
@ -1389,11 +1309,6 @@ function MonthlyPlanWorkspace({
const publishPlan = async () => {
if (!group) return
if (dirty) {
onError('岗位考核方案在预览后又发生了修改,请重新执行发布前检查')
setPreview(null)
return
}
const draftPlanId = String(preview?.draftPlanId || '').trim()
const draftVersion = Number(preview?.draftVersion)
const draftUpdatedAt = String(preview?.draftUpdatedAt || '').trim()
@ -1454,11 +1369,13 @@ function MonthlyPlanWorkspace({
</div>
<p className="mt-4 max-w-3xl text-[12px] leading-5 text-[#5f5e5e]">
已发布方案会从生效月份起持续沿用,后续月份无需重复发布。只有岗位名称、排序、人员匹配规则、考核模板或排列顺序发生变化时,才需要发布新方案。
已发布方案会从生效月份起持续沿用,后续月份无需重复发布。请先在“岗位”页面调整考核项并保存,再到这里检查影响并发布。
</p>
<div className="mt-5">
<h3 className="text-[14px] font-bold text-[#1a1c1c]">模板顺序</h3>
<h3 className="text-[14px] font-bold text-[#1a1c1c]">
{group.draftPlan ? '待发布的考核项' : '当前生效的考核项'}
</h3>
<div className="mt-2 overflow-x-auto border border-[#c2c6d8]">
<table className="w-full min-w-[620px] border-collapse text-left">
<thead>
@ -1466,7 +1383,6 @@ function MonthlyPlanWorkspace({
<th scope="col" className="w-16 px-3 py-3">顺序</th>
<th scope="col" className="px-3 py-3">模板</th>
<th scope="col" className="w-32 px-3 py-3">版本</th>
<th scope="col" className="w-44 px-3 py-3 text-right">调整</th>
</tr>
</thead>
<tbody className="divide-y divide-[#e2e2e2]">
@ -1475,38 +1391,17 @@ function MonthlyPlanWorkspace({
return (
<tr key={id}>
<td className="px-3 py-3 text-[13px] font-bold text-[#1a1c1c]">{index + 1}</td>
<td className="px-3 py-3 text-[13px] font-bold text-[#1a1c1c]">{item?.version.definition.shortName || item?.template.name || '历史模板版本'}</td>
<td className="px-3 py-3 text-[13px] font-bold text-[#1a1c1c]">{item?.version.definition.name || item?.template.name || '历史模板版本'}</td>
<td className="px-3 py-3 text-[12px] text-[#5f5e5e]">{item ? `v${item.version.version}` : id}</td>
<td className="px-3 py-2 text-right">
<button type="button" disabled={index === 0} onClick={() => moveVersion(index, -1)} aria-label={`上移模板 ${index + 1}`} className="min-h-10 rounded px-3 text-[12px] font-bold text-[#0050cb] disabled:text-[#a0a0a0]">上移</button>
<button type="button" disabled={index === templateVersionIds.length - 1} onClick={() => moveVersion(index, 1)} aria-label={`下移模板 ${index + 1}`} className="min-h-10 rounded px-3 text-[12px] font-bold text-[#0050cb] disabled:text-[#a0a0a0]">下移</button>
<button type="button" onClick={() => toggleVersion(id, false)} className="min-h-10 rounded px-3 text-[12px] font-bold text-[#b42318]">移除</button>
</td>
</tr>
)
})}
{templateVersionIds.length === 0 && <tr><td colSpan={4} className="px-4 py-8 text-center text-[13px] text-[#8a5700]">尚未选择模板</td></tr>}
{templateVersionIds.length === 0 && <tr><td colSpan={3} className="px-4 py-8 text-center text-[13px] text-[#8a5700]">尚未选择考核项,请先到“岗位”页面添加</td></tr>}
</tbody>
</table>
</div>
</div>
<div className="mt-5">
<h3 className="text-[14px] font-bold text-[#1a1c1c]">可用已发布模板</h3>
<div className="mt-2 grid gap-2 sm:grid-cols-2">
{publishedVersions.map(({ template, version }) => {
const checked = templateVersionIds.includes(version.id)
return (
<label key={version.id} className={`flex min-h-11 items-center gap-3 border px-3 py-2 ${checked ? 'border-[#b3c5ff] bg-[#f8faff]' : 'border-[#e2e2e2]'}`}>
<input type="checkbox" checked={checked} onChange={(event) => toggleVersion(version.id, event.target.checked)} />
<span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-[#1a1c1c]">{version.definition.shortName || template.name}</span>
<span className="text-[11px] text-[#5f5e5e]">v{version.version}</span>
</label>
)
})}
</div>
</div>
{preview && (
<div className="mt-5 border border-[#b3c5ff] bg-[#f8faff] px-4 py-4" role="region" aria-label="发布影响确认">
<h3 className="text-[14px] font-bold text-[#1a1c1c]">发布影响确认</h3>
@ -1530,8 +1425,10 @@ function MonthlyPlanWorkspace({
)}
<div className="sticky bottom-[68px] z-20 -mx-4 mt-6 flex flex-wrap justify-end gap-2 border-t border-[#c2c6d8] bg-white/95 px-4 py-3 shadow-[0_-4px_10px_rgba(0,0,0,0.06)] backdrop-blur sm:bottom-0 sm:mx-0 sm:shadow-none">
<button type="button" disabled={saving || !dirty} onClick={() => void saveDraft()} className="min-h-11 rounded border border-[#1a1c1c] px-4 text-[13px] font-bold text-[#1a1c1c] disabled:opacity-50">保存草稿</button>
<button type="button" disabled={saving || group.status === 'disabled'} onClick={() => void openPublishPreview()} className="min-h-11 rounded bg-[#0050cb] px-4 text-[13px] font-bold text-white disabled:opacity-50">发布前检查</button>
<span className="mr-auto text-[12px] font-semibold text-[#5f5e5e]">
{group.draftPlan ? '当前有待发布修改' : '当前没有待发布修改'}
</span>
<button type="button" disabled={saving || group.status === 'disabled' || !group.draftPlan} onClick={() => void openPublishPreview()} className="min-h-11 rounded bg-[#0050cb] px-4 text-[13px] font-bold text-white disabled:opacity-50">发布前检查</button>
</div>
</section>
)
@ -1546,12 +1443,23 @@ function QuestionEditor({
editable: boolean
onChange: (definition: TemplateDefinition) => void
}) {
const perItemTotal = definition.questions.reduce(
(sum, question) => sum + Number(question.maxScore || definition.questionMaxScore || 20),
0,
)
const workItemCount = definition.surveyType === 'visual_case'
? Math.max(1, Number(definition.requiredWorkItemCount || 1))
: 1
const allocatedTotal = perItemTotal * workItemCount
const configuredTotal = Number(definition.maxTotal || 0)
const totalMatches = Math.round(allocatedTotal * 100) === Math.round(configuredTotal * 100)
return (
<section aria-labelledby="template-questions-heading">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 id="template-questions-heading" className="text-[15px] font-bold text-[#1a1c1c]">评分项</h3>
<p className="mt-1 text-[12px] leading-5 text-[#727687]">评分人将逐项打分,右侧满分会决定该项可填写的最高分。</p>
<p className="mt-1 text-[12px] leading-5 text-[#727687]">评分人将逐项打分;所有评分项满分之和必须等于总分。</p>
</div>
{editable && (
<button
@ -1559,7 +1467,7 @@ function QuestionEditor({
onClick={() => onChange({
...definition,
questions: [...definition.questions, {
id: `score_${definition.questions.length + 1}`,
id: `score_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
title: `评分项 ${definition.questions.length + 1}`,
description: '',
maxScore: definition.questionMaxScore || 20,
@ -1571,7 +1479,31 @@ function QuestionEditor({
</button>
)}
</div>
<div className={`mt-4 grid gap-3 border px-4 py-4 sm:grid-cols-[minmax(0,240px)_1fr] sm:items-end ${totalMatches ? 'border-[#c2c6d8] bg-[#fafafa]' : 'border-[#e7b64a] bg-[#fff9ec]'}`}>
<label className="grid min-w-0 gap-1 text-[12px] font-semibold text-[#5f5e5e]">
总分
<input
type="number"
min="1"
value={configuredTotal || ''}
disabled={!editable}
onChange={(event) => onChange({ ...definition, maxTotal: Math.max(1, Number(event.target.value) || 1) })}
className="h-11 min-w-0 w-full rounded border border-[#c2c6d8] px-3 text-[13px] font-bold text-[#1a1c1c] outline-none focus:border-[#0050cb] disabled:bg-[#f4f4f4]"
/>
</label>
<div className={`text-[12px] leading-5 ${totalMatches ? 'text-[#5f5e5e]' : 'font-bold text-[#8a5700]'}`}>
{definition.surveyType === 'visual_case'
? `已分配 ${perItemTotal} × ${workItemCount} 个作品 = ${allocatedTotal} / ${configuredTotal || 0} 分`
: `已分配 ${allocatedTotal} / ${configuredTotal || 0} 分`}
{!totalMatches && <span className="block">请调整评分项满分或总分,二者一致后才能发布。</span>}
</div>
</div>
<div className="mt-4 grid gap-3">
{definition.questions.length === 0 && (
<div className="border border-dashed border-[#c2c6d8] px-4 py-8 text-center text-[12px] text-[#727687]">
还没有评分项,请点击“添加评分项”
</div>
)}
{definition.questions.map((question, index) => (
<div key={`${question.id}-${index}`} className="border border-[#e2e2e2] p-4">
<div className="flex items-center justify-between gap-3 border-b border-[#eeeeee] pb-3">
@ -1579,26 +1511,25 @@ function QuestionEditor({
{editable && (
<button
type="button"
disabled={definition.questions.length <= 1}
aria-label={`删除评分项 ${index + 1}`}
onClick={() => onChange({ ...definition, questions: definition.questions.filter((_, itemIndex) => itemIndex !== index) })}
className="min-h-11 rounded px-3 text-[12px] font-bold text-[#b42318] hover:bg-[#fff5f5] disabled:cursor-not-allowed disabled:text-[#aaaaaa]"
className="min-h-11 rounded px-3 text-[12px] font-bold text-[#b42318] hover:bg-[#fff5f5]"
>
删除
</button>
)}
</div>
<div className="mt-3 grid gap-3 sm:grid-cols-[minmax(0,1fr)_120px]">
<label className="grid gap-1 text-[12px] font-semibold text-[#5f5e5e]">
<label className="grid min-w-0 gap-1 text-[12px] font-semibold text-[#5f5e5e]">
评分项名称
<input
value={question.title}
disabled={!editable}
onChange={(event) => onChange({ ...definition, questions: definition.questions.map((item, itemIndex) => itemIndex === index ? { ...item, title: event.target.value } : item) })}
className="h-11 rounded border border-[#e2e2e2] px-3 text-[13px] outline-none focus:border-[#0050cb] disabled:bg-[#f4f4f4]"
className="h-11 min-w-0 w-full rounded border border-[#e2e2e2] px-3 text-[13px] outline-none focus:border-[#0050cb] disabled:bg-[#f4f4f4]"
/>
</label>
<label className="grid gap-1 text-[12px] font-semibold text-[#5f5e5e]">
<label className="grid min-w-0 gap-1 text-[12px] font-semibold text-[#5f5e5e]">
满分
<input
type="number"
@ -1606,7 +1537,7 @@ function QuestionEditor({
value={question.maxScore || 20}
disabled={!editable}
onChange={(event) => onChange({ ...definition, questions: definition.questions.map((item, itemIndex) => itemIndex === index ? { ...item, maxScore: Number(event.target.value) || 1 } : item) })}
className="h-11 rounded border border-[#e2e2e2] px-3 text-[13px] outline-none focus:border-[#0050cb] disabled:bg-[#f4f4f4]"
className="h-11 min-w-0 w-full rounded border border-[#e2e2e2] px-3 text-[13px] outline-none focus:border-[#0050cb] disabled:bg-[#f4f4f4]"
/>
</label>
<label className="grid gap-1 text-[12px] font-semibold text-[#5f5e5e] sm:col-span-2">
@ -1620,18 +1551,6 @@ function QuestionEditor({
/>
</label>
</div>
<details className="mt-3">
<summary className="min-h-11 cursor-pointer py-3 text-[11px] font-bold text-[#727687]">高级设置</summary>
<label className="grid max-w-sm gap-1 text-[11px] font-semibold text-[#727687]">
系统内部评分项代码
<input
value={question.id}
disabled={!editable}
onChange={(event) => onChange({ ...definition, questions: definition.questions.map((item, itemIndex) => itemIndex === index ? { ...item, id: event.target.value } : item) })}
className="h-11 rounded border border-[#e2e2e2] px-3 text-[12px] outline-none focus:border-[#0050cb] disabled:bg-[#f4f4f4]"
/>
</label>
</details>
</div>
))}
</div>
@ -1901,14 +1820,14 @@ function AdminField({
disabled?: boolean
}) {
return (
<label className="grid gap-1 text-[12px] font-semibold text-[#5f5e5e]">
<label className="grid min-w-0 gap-1 text-[12px] font-semibold text-[#5f5e5e]">
{label}
<input
type={type}
value={value}
disabled={disabled}
onChange={(event) => onChange(event.target.value)}
className="h-11 rounded border border-[#e2e2e2] px-3 text-[13px] font-semibold text-[#1a1c1c] outline-none focus:border-[#0050cb] disabled:bg-[#f4f4f4] disabled:text-[#8a8a8a]"
className="h-11 min-w-0 w-full rounded border border-[#e2e2e2] px-3 text-[13px] font-semibold text-[#1a1c1c] outline-none focus:border-[#0050cb] disabled:bg-[#f4f4f4] disabled:text-[#8a8a8a]"
/>
</label>
)

View File

@ -3348,7 +3348,7 @@ function CreateSurveyForm({
{selectedTemplateInfo?.templateVariant && (
<div className="border border-[#dce5f3] bg-[#f8faff] px-3 py-3">
<div className="text-[12px] font-bold text-[#1a1c1c]">
{selectedTemplateInfo.questions.length} 个评分项 · 每项 {selectedTemplateInfo.questionMaxScore || selectedTemplateInfo.questions[0]?.maxScore || 0} 分 · 合计 40 分
{selectedTemplateInfo.questions.length} 个评分项 · 模板总分 {selectedTemplateInfo.maxTotal || 0} 分
</div>
<div className="mt-1 text-[12px] leading-5 text-[#5f5e5e]">
{selectedTemplateInfo.questions.map((question) => question.title).join(' / ')}

View File

@ -4,13 +4,17 @@ import { prisma } from '@/lib/prisma'
import {
assertPerformanceSurveyPositionPlanPreviewMatches,
createPerformanceSurveyManualPositionAssignments,
listPerformanceSurveyPositionGroups,
removePerformanceSurveyTemplate,
savePerformanceSurveyPositionGroupDraft,
} from '@/lib/performance-survey-position-config'
import { DEFAULT_PERFORMANCE_SURVEY_TEMPLATES } from '@/lib/performance-survey-templates'
jest.mock('@/lib/prisma', () => ({
prisma: {
performanceSurveyPositionGroup: {
findUnique: jest.fn(),
findMany: jest.fn(),
update: jest.fn(),
},
performanceSurveyPositionRule: {
@ -21,6 +25,15 @@ jest.mock('@/lib/prisma', () => ({
performanceSurveyTemplateVersion: {
findMany: jest.fn(),
},
performanceSurveyTemplate: {
findUnique: jest.fn(),
},
performanceSurveyPositionPlanItem: {
count: jest.fn(),
},
performanceSurvey: {
count: jest.fn(),
},
performanceSurveyEmployeeProfile: {
findMany: jest.fn(),
},
@ -200,4 +213,135 @@ describe('performance survey position admin', () => {
data: expect.objectContaining({ reason: '' }),
})
})
test('当前或未来岗位方案仍在使用模板时拒绝删除', async () => {
;(prisma.performanceSurveyTemplate.findUnique as jest.Mock).mockResolvedValue({
id: 'template-1',
code: 'visual_review',
versions: [{ id: 'version-1', status: 'published' }],
})
;(prisma.performanceSurveyPositionPlanItem.count as jest.Mock).mockResolvedValue(1)
;(prisma.performanceSurvey.count as jest.Mock).mockResolvedValue(2)
;(prisma.performanceSurveyPositionGroup.findMany as jest.Mock).mockResolvedValue([{
name: '品牌设计师',
plans: [{
id: 'plan-1',
status: 'published',
effectiveMonth: '2026-07',
version: 1,
items: [{ id: 'item-1' }],
}],
}])
await expect(removePerformanceSurveyTemplate({
templateId: 'template-1',
actorUserId: 'admin-1',
actorName: '管理员',
reason: '不再使用',
})).rejects.toThrow('请先从岗位考核项中移除并发布新方案')
expect(prisma.$transaction).not.toHaveBeenCalled()
})
test('历史查询保留已删除岗位和模板,常规查询默认排除已删除岗位', async () => {
const definition = structuredClone(DEFAULT_PERFORMANCE_SURVEY_TEMPLATES[0])
;(prisma.performanceSurveyPositionGroup.findMany as jest.Mock).mockResolvedValueOnce([{
id: 'group-archived',
code: 'archived-group',
name: '已删除岗位',
sortOrder: 10,
isActive: true,
isSystem: false,
archivedAt: new Date('2026-07-01T00:00:00.000Z'),
plans: [{
id: 'plan-history',
status: 'published',
effectiveMonth: '2026-06',
version: 1,
groupConfig: {
name: '已删除岗位',
sortOrder: 10,
isActive: true,
},
matchRules: [],
items: [{
id: 'item-history',
isEnabled: true,
sortOrder: 10,
templateVersion: {
id: 'version-history',
version: 1,
status: 'published',
effectiveMonth: '2026-01',
definition,
template: {
archivedAt: new Date('2026-07-01T00:00:00.000Z'),
},
},
}],
}],
}])
await expect(listPerformanceSurveyPositionGroups('2026-06', {
includeArchived: true,
})).resolves.toMatchObject([{
id: 'group-archived',
status: 'ready',
templates: [{
templateVersionId: 'version-history',
templateArchivedAt: new Date('2026-07-01T00:00:00.000Z'),
}],
}])
expect(prisma.performanceSurveyPositionGroup.findMany).toHaveBeenNthCalledWith(
1,
expect.objectContaining({ where: undefined }),
)
;(prisma.performanceSurveyPositionGroup.findMany as jest.Mock).mockResolvedValueOnce([])
await expect(listPerformanceSurveyPositionGroups('2026-07')).resolves.toEqual([])
expect(prisma.performanceSurveyPositionGroup.findMany).toHaveBeenNthCalledWith(
2,
expect.objectContaining({ where: { archivedAt: null } }),
)
})
test('包含历史岗位时,已删除岗位不会在删除月份及之后重新激活', async () => {
const archivedGroup = {
id: 'group-archived',
code: 'archived-group',
name: '旧岗位',
sortOrder: 10,
isActive: true,
isSystem: false,
// 北京时间 7 月 1 日 00:30,UTC 仍是 6 月;业务月份必须按北京时间判断。
archivedAt: new Date('2026-06-30T16:30:00.000Z'),
plans: [],
}
const activeGroup = {
id: 'group-active',
code: 'active-group',
name: '新岗位',
sortOrder: 20,
isActive: true,
isSystem: false,
archivedAt: null,
plans: [],
}
;(prisma.performanceSurveyPositionGroup.findMany as jest.Mock)
.mockResolvedValue([archivedGroup, activeGroup])
await expect(listPerformanceSurveyPositionGroups('2026-07', {
includeArchived: true,
})).resolves.toMatchObject([
{
id: 'group-archived',
isActive: false,
status: 'disabled',
},
{
id: 'group-active',
isActive: true,
},
])
})
})

View File

@ -3,6 +3,7 @@
import {
PERFORMANCE_SURVEY_POSITION_GROUP_SEEDS,
createPerformanceSurveyPositionGroupIdentity,
getAvailablePerformanceSurveyPositionTemplates,
matchesPerformanceSurveyPositionRule,
paginatePerformanceSurveyTemplates,
performanceSurveyMonthRangesOverlap,
@ -41,6 +42,28 @@ describe('performance survey position configuration', () => {
expect(new Set(PERFORMANCE_SURVEY_POSITION_GROUP_SEEDS.map((item) => item.code)).size).toBe(8)
})
test('已删除模板保留在历史岗位方案中,但不能用于新发起', () => {
const activeTemplate = {
...structuredClone(DEFAULT_PERFORMANCE_SURVEY_TEMPLATES[0]),
templateVersionId: 'version-active',
templateArchivedAt: null,
}
const archivedTemplate = {
...structuredClone(DEFAULT_PERFORMANCE_SURVEY_TEMPLATES[1]),
templateVersionId: 'version-archived',
templateArchivedAt: new Date('2026-07-01T00:00:00.000Z'),
}
const positionGroup = group({
id: 'history-group',
code: 'history-group',
name: '历史岗位',
templates: [activeTemplate, archivedTemplate],
})
expect(positionGroup.templates).toHaveLength(2)
expect(getAvailablePerformanceSurveyPositionTemplates(positionGroup)).toEqual([activeTemplate])
})
test('单条规则内部门和职位按 AND 匹配,部门路径支持子部门', () => {
const rule = { departmentPathPrefix: '集团/品牌中心', positionTitle: 'AI策划' }
expect(matchesPerformanceSurveyPositionRule({
@ -229,9 +252,16 @@ describe('performance survey position configuration', () => {
test('一个完整考核项也允许发布,不要求凑满四项', () => {
const template = structuredClone(DEFAULT_PERFORMANCE_SURVEY_TEMPLATES[0])
template.questions = [template.questions[0]]
template.maxTotal = Number(template.questions[0].maxScore || template.questionMaxScore || 20)
expect(() => validatePerformanceSurveyTemplateDefinition(template)).not.toThrow()
})
test('模板总分必须与评分项满分合计一致', () => {
const template = structuredClone(DEFAULT_PERFORMANCE_SURVEY_TEMPLATES[0])
template.maxTotal = Number(template.maxTotal || 0) + 1
expect(() => validatePerformanceSurveyTemplateDefinition(template)).toThrow('与模板总分')
})
test('拒绝空题目、重复阶段顺序和不唯一的终审计分人', () => {
const empty = structuredClone(DEFAULT_PERFORMANCE_SURVEY_TEMPLATES[0])
empty.questions = []

View File

@ -82,7 +82,15 @@ export type PositionGroupRuntime = {
planVersion: number | null
effectiveMonth: string | null
rules: PerformanceSurveyPositionRuleInput[]
templates: PerformanceSurveyTemplateShape[]
templates: Array<PerformanceSurveyTemplateShape & {
templateArchivedAt?: Date | null
}>
}
export function getAvailablePerformanceSurveyPositionTemplates(
group: Pick<PositionGroupRuntime, 'templates'>,
) {
return group.templates.filter((template) => !template.templateArchivedAt)
}
type PositionGroupPlanConfiguration = {
@ -203,6 +211,17 @@ function getCurrentAssessmentMonth() {
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
}
function getPerformanceSurveyBusinessMonth(date: Date) {
const parts = new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
}).formatToParts(date)
const year = parts.find((part) => part.type === 'year')?.value
const month = parts.find((part) => part.type === 'month')?.value
return year && month ? `${year}-${month.padStart(2, '0')}` : date.toISOString().slice(0, 7)
}
export function matchesPerformanceSurveyPositionRule(
employee: PerformanceSurveyPositionEmployeeInput,
rule: PerformanceSurveyPositionRuleInput,
@ -341,6 +360,7 @@ export function validatePerformanceSurveyTemplateDefinition(definition: Performa
throw new PerformanceSurveyPositionConfigError('模板至少需要 1 个评分项')
}
const questionIds = new Set<string>()
let allocatedTotal = 0
for (const question of definition.questions) {
const id = clean(question.id)
if (!id || !clean(question.title)) throw new PerformanceSurveyPositionConfigError('评分项缺少名称或标识')
@ -348,12 +368,24 @@ export function validatePerformanceSurveyTemplateDefinition(definition: Performa
questionIds.add(id)
const maxScore = Number(question.maxScore ?? definition.questionMaxScore ?? 20)
if (!Number.isFinite(maxScore) || maxScore <= 0) throw new PerformanceSurveyPositionConfigError(`评分项「${question.title}」满分无效`)
allocatedTotal += maxScore
}
if (definition.surveyType === 'visual_case') {
const requiredCount = Number(definition.requiredWorkItemCount || 0)
if (!Number.isInteger(requiredCount) || requiredCount < 1) {
throw new PerformanceSurveyPositionConfigError('视觉案例模板必须配置作品数量')
}
const requiredWorkItemCount = definition.surveyType === 'visual_case'
? Number(definition.requiredWorkItemCount || 0)
: 1
if (definition.surveyType === 'visual_case' && (!Number.isInteger(requiredWorkItemCount) || requiredWorkItemCount < 1)) {
throw new PerformanceSurveyPositionConfigError('视觉案例模板必须配置作品数量')
}
const calculatedTotal = allocatedTotal * requiredWorkItemCount
const maxTotal = Number(definition.maxTotal)
if (!Number.isFinite(maxTotal) || maxTotal <= 0) {
throw new PerformanceSurveyPositionConfigError('模板总分必须大于 0')
}
if (Math.round(calculatedTotal * 100) !== Math.round(maxTotal * 100)) {
const calculationLabel = definition.surveyType === 'visual_case'
? `每个作品 ${allocatedTotal} 分 × ${requiredWorkItemCount} 个作品 = ${calculatedTotal} 分`
: `评分项合计 ${allocatedTotal} 分`
throw new PerformanceSurveyPositionConfigError(`${calculationLabel},与模板总分 ${maxTotal} 分不一致`)
}
validateWorkflow(definition.workflow)
}
@ -613,16 +645,23 @@ export async function listPerformanceSurveyPositionGroups(
return groups.map((group) => {
const plan = chooseEffectivePlan(group.plans, month)
const configuration = readPositionGroupPlanConfiguration(plan?.groupConfig, group)
const templates = (plan?.items || []).map((item) => ({
const templates = (plan?.items || [])
.filter((item) => item.templateVersion.status === 'published')
.map((item) => ({
...readTemplateDefinition(item.templateVersion.definition),
templateArchivedAt: item.templateVersion.template.archivedAt,
templateVersionId: item.templateVersion.id,
templateVersion: item.templateVersion.version,
templateVersionStatus: item.templateVersion.status as 'draft' | 'published' | 'archived',
effectiveMonth: item.templateVersion.effectiveMonth,
}))
const rules = readRules(plan?.matchRules)
const isActive = Boolean(configuration.isActive && !group.archivedAt)
const ready = Boolean(plan && rules.length > 0 && templates.length > 0)
const archivedMonth = group.archivedAt
? getPerformanceSurveyBusinessMonth(group.archivedAt)
: null
const wasActiveInRequestedMonth = !archivedMonth || month < archivedMonth
const isActive = Boolean(configuration.isActive && wasActiveInRequestedMonth)
const ready = Boolean(plan && templates.length > 0)
return {
id: group.id,
code: group.code,
@ -674,10 +713,11 @@ function mapEffectiveManualPositionAssignments<T extends {
export async function getPerformanceSurveyPositionGroupForEmployee(
employee: PerformanceSurveyPositionEmployeeInput,
month?: string | null,
options?: { includeArchived?: boolean },
) {
const normalizedMonth = normalizePerformanceSurveyAssessmentMonth(month) || getCurrentAssessmentMonth()
const [groups, assignments, departmentMemberships] = await Promise.all([
listPerformanceSurveyPositionGroups(normalizedMonth),
listPerformanceSurveyPositionGroups(normalizedMonth, { includeArchived: options?.includeArchived }),
employee.id
? listEffectiveManualPositionAssignments(normalizedMonth, [employee.id])
: Promise.resolve([]),
@ -777,8 +817,12 @@ export async function getPerformanceSurveyPositionMembershipsForEmployees<
]))
}
export async function getPerformanceSurveyPositionGroupByCode(code: string, month?: string | null) {
const groups = await listPerformanceSurveyPositionGroups(month)
export async function getPerformanceSurveyPositionGroupByCode(
code: string,
month?: string | null,
options?: { includeArchived?: boolean },
) {
const groups = await listPerformanceSurveyPositionGroups(month, { includeArchived: options?.includeArchived })
const group = groups.find((item) => item.code === code)
if (!group) throw new PerformanceSurveyPositionConfigError('考核岗位组不存在', 404)
return group
@ -789,6 +833,7 @@ export async function getPerformanceSurveyPositionAdminConfig(monthInput?: strin
const [runtimeGroups, groups, templates, employees] = await Promise.all([
listPerformanceSurveyPositionGroups(month, { includeArchived: true }),
prisma.performanceSurveyPositionGroup.findMany({
where: { archivedAt: null },
orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }],
include: {
rules: { orderBy: { sortOrder: 'asc' } },
@ -805,6 +850,7 @@ export async function getPerformanceSurveyPositionAdminConfig(monthInput?: strin
},
}),
prisma.performanceSurveyTemplate.findMany({
where: { archivedAt: null },
orderBy: [{ createdAt: 'asc' }],
include: { versions: { orderBy: { version: 'desc' } } },
}),
@ -835,7 +881,7 @@ export async function getPerformanceSurveyPositionAdminConfig(monthInput?: strin
const configuration = readPositionGroupPlanConfiguration(draft.groupConfig, runtime)
const rules = readRules(draft.matchRules)
const draftTemplates = draft.items
.filter((item) => item.isEnabled)
.filter((item) => item.isEnabled && !item.templateVersion.template.archivedAt && item.templateVersion.status === 'published')
.map((item) => ({
...readTemplateDefinition(item.templateVersion.definition),
templateVersionId: item.templateVersion.id,
@ -849,7 +895,7 @@ export async function getPerformanceSurveyPositionAdminConfig(monthInput?: strin
name: configuration.name,
sortOrder: configuration.sortOrder,
isActive,
status: !isActive ? 'disabled' : rules.length > 0 && draftTemplates.length > 0 ? 'ready' : 'pending',
status: !isActive ? 'disabled' : draftTemplates.length > 0 ? 'ready' : 'pending',
planId: draft.id,
planVersion: draft.version,
effectiveMonth: draft.effectiveMonth,
@ -1339,9 +1385,6 @@ export async function publishPerformanceSurveyPositionPlan(input: {
}
const rules = readRules(draft.matchRules)
const configuration = readPositionGroupPlanConfiguration(draft.groupConfig, draft.positionGroup)
if (configuration.isActive && rules.length === 0) {
throw new PerformanceSurveyPositionConfigError('请先配置至少 1 条岗位匹配规则')
}
if (configuration.isActive && draft.items.length === 0) {
throw new PerformanceSurveyPositionConfigError('岗位方案至少需要 1 个考核项')
}
@ -1443,6 +1486,7 @@ function normalizeTemplateDefinitionInput(value: unknown): PerformanceSurveyTemp
description: String(definition.description || '').trim(),
surveyType: String(definition.surveyType || 'person_period').trim(),
weight: Number(definition.weight || 1),
maxTotal: Number(definition.maxTotal || 0),
questions: Array.isArray(definition.questions) ? definition.questions : [],
scoreBands: Array.isArray(definition.scoreBands) ? definition.scoreBands : [],
}
@ -1456,7 +1500,7 @@ export async function savePerformanceSurveyTemplateDraft(input: {
reason?: string | null
}) {
const definition = normalizeTemplateDefinitionInput(input.definition)
if (!definition.code || !definition.name) throw new PerformanceSurveyPositionConfigError('模板代码和名称不能为空')
if (!definition.code || !definition.name) throw new PerformanceSurveyPositionConfigError('模板名称不能为空')
const existingVersion = input.versionId
? await prisma.performanceSurveyTemplateVersion.findUnique({
where: { id: input.versionId },
@ -1906,7 +1950,8 @@ export async function removePerformanceSurveyTemplate(input: {
})
if (!template) throw new PerformanceSurveyPositionConfigError('模板不存在', 404)
const versionIds = template.versions.map((version) => version.id)
const [planReferenceCount, surveyReferenceCount] = await Promise.all([
const currentMonth = getCurrentAssessmentMonth()
const [planReferenceCount, surveyReferenceCount, activeGroups] = await Promise.all([
versionIds.length > 0
? prisma.performanceSurveyPositionPlanItem.count({ where: { templateVersionId: { in: versionIds } } })
: 0,
@ -1918,11 +1963,50 @@ export async function removePerformanceSurveyTemplate(input: {
],
},
}),
versionIds.length > 0
? prisma.performanceSurveyPositionGroup.findMany({
where: { archivedAt: null },
select: {
name: true,
plans: {
where: { status: { in: ['draft', 'published'] } },
select: {
id: true,
status: true,
effectiveMonth: true,
version: true,
items: {
where: { isEnabled: true, templateVersionId: { in: versionIds } },
select: { id: true },
},
},
},
},
})
: [],
])
const activePositionNames = activeGroups.flatMap((group) => {
const currentPlan = chooseEffectivePlan(group.plans, currentMonth)
const referenced = group.plans.some((plan) => (
plan.items.length > 0
&& (
plan.status === 'draft'
|| plan.id === currentPlan?.id
|| (plan.status === 'published' && Boolean(plan.effectiveMonth && plan.effectiveMonth > currentMonth))
)
))
return referenced ? [group.name] : []
})
const canHardDelete = template.versions.every((version) => version.status === 'draft')
&& planReferenceCount === 0
&& surveyReferenceCount === 0
const shouldDelete = input.mode !== 'archive' && canHardDelete
if (!shouldDelete && activePositionNames.length > 0) {
throw new PerformanceSurveyPositionConfigError(
`模板仍被以下岗位使用:${activePositionNames.join('、')}。请先从岗位考核项中移除并发布新方案,再删除模板。`,
409,
)
}
return prisma.$transaction(async (tx) => {
if (shouldDelete) {
@ -2328,7 +2412,6 @@ export async function previewPerformanceSurveyPositionPlanImpact(input: {
const rules = readRules(draft.matchRules)
const configuration = readPositionGroupPlanConfiguration(draft.groupConfig, draft.positionGroup)
const blockingIssues: string[] = []
if (configuration.isActive && rules.length === 0) blockingIssues.push('缺少岗位匹配规则')
if (configuration.isActive && draft.items.length === 0) blockingIssues.push('缺少考核模板')
try {
validatePerformanceSurveyPositionPlanTemplateVersions(
@ -2375,7 +2458,7 @@ export async function previewPerformanceSurveyPositionPlanImpact(input: {
isActive: configuration.isActive,
status: !configuration.isActive
? 'disabled'
: rules.length > 0 && draft.items.length > 0 ? 'ready' : 'pending',
: draft.items.length > 0 ? 'ready' : 'pending',
rules,
templates: draft.items.map((item) => ({
...readTemplateDefinition(item.templateVersion.definition),

View File

@ -29,6 +29,7 @@ import {
createPerformanceSurveyManualPositionAssignments,
createPerformanceSurveyPositionGroup,
createPerformanceSurveyTemplateDraftFromVersion,
getAvailablePerformanceSurveyPositionTemplates,
getManualReviewerStages,
getPerformanceSurveyPositionAdminConfig,
getPerformanceSurveyPositionGroupByCode,
@ -1131,7 +1132,7 @@ export async function getPerformanceSurveyPositionGroups(session: Session | null
name: group.name,
status: group.status,
isActive: group.isActive,
templateCount: group.templates.length,
templateCount: getAvailablePerformanceSurveyPositionTemplates(group).length,
effectiveMonth: group.effectiveMonth,
})),
membership: {
@ -1151,14 +1152,16 @@ export async function getPerformanceSurveyTemplates(session: Session | null, par
try {
const group = await getPerformanceSurveyPositionGroupByCode(requestedGroupCode, month)
if (group.status !== 'ready') throw new PerformanceSurveyApiError('该岗位组尚未完成配置', 409)
return group.templates
return getAvailablePerformanceSurveyPositionTemplates(group)
} catch (error) {
return rethrowPositionConfigError(error)
}
}
if (!ctx.employee) return []
const membership = await getPerformanceSurveyPositionGroupForEmployee(ctx.employee, month)
return membership.group?.status === 'ready' ? membership.group.templates : []
return membership.group?.status === 'ready'
? getAvailablePerformanceSurveyPositionTemplates(membership.group)
: []
}
export async function getPerformanceSurveyAdminConfiguration(session: Session | null, params?: URLSearchParams) {
@ -2367,9 +2370,9 @@ export async function getPerformanceSurveyDashboard(session: Session | null, par
const currentMonth = getCurrentMonthRange()
const monthRange = getMonthRange(params?.get('month')) || currentMonth
const monthValue = clean(params?.get('month')) || currentMonth.value
const positionGroups = await listPerformanceSurveyPositionGroups(monthValue)
const positionGroups = await listPerformanceSurveyPositionGroups(monthValue, { includeArchived: true })
const personalMembership = ctx.employee
? await getPerformanceSurveyPositionGroupForEmployee(ctx.employee, monthValue)
? await getPerformanceSurveyPositionGroupForEmployee(ctx.employee, monthValue, { includeArchived: true })
: { status: 'unmatched' as const, group: null, matches: [], source: 'automatic' as const, manualAssignmentId: null }
const requestedGroupCode = clean(params?.get('positionGroupCode'))
let selectedGroup = dashboardView === 'personal'
@ -2380,7 +2383,7 @@ export async function getPerformanceSurveyDashboard(session: Session | null, par
if (requestedGroupCode && dashboardView !== 'personal' && !selectedGroup) {
throw new PerformanceSurveyApiError('考核岗位组不存在', 404)
}
if (selectedGroup?.status !== 'ready') selectedGroup = selectedGroup || null
if (selectedGroup?.status !== 'ready') selectedGroup = null
const allTemplates = selectedGroup?.templates || []
const templatePageResult = paginatePerformanceSurveyTemplates(allTemplates, params?.get('itemPage'))
const templates = templatePageResult.items
@ -2530,10 +2533,18 @@ export async function getPerformanceSurveyDashboardDetail(session: Session | nul
}
}
const membership = await getPerformanceSurveyPositionGroupForEmployee(employee, monthValue)
const membership = await getPerformanceSurveyPositionGroupForEmployee(
employee,
monthValue,
{ includeArchived: true },
)
const effectivePositionGroupCode = positionGroupCode || membership.group?.code
if (!effectivePositionGroupCode) throw new PerformanceSurveyApiError('该人员尚未匹配唯一的考核岗位组', 409)
const positionGroup = await getPerformanceSurveyPositionGroupByCode(effectivePositionGroupCode, monthValue)
const positionGroup = await getPerformanceSurveyPositionGroupByCode(
effectivePositionGroupCode,
monthValue,
{ includeArchived: true },
)
const template = positionGroup.templates.find((item) => item.code === templateCode)
if (!template) throw new PerformanceSurveyApiError('该考核项不属于当前岗位组', 404)
const targets = await prisma.performanceSurveyTarget.findMany({
@ -2789,7 +2800,8 @@ export async function createPerformanceSurvey(session: Session | null, body: any
const templateVersionId = clean(body?.templateVersionId)
const templateCode = clean(body?.templateCode)
const template = positionGroup.templates.find((item) => (
templateVersionId ? item.templateVersionId === templateVersionId : item.code === templateCode
!item.templateArchivedAt
&& (templateVersionId ? item.templateVersionId === templateVersionId : item.code === templateCode)
))
if (!template) throw new PerformanceSurveyApiError('所选考核项不属于当前岗位组或版本已失效', 409)