feat: 优化考核调研管理后台

This commit is contained in:
chenpei 2026-07-27 10:28:18 +08:00
parent 9b442574fa
commit 063bbca0ef
11 changed files with 1901 additions and 232 deletions

View File

@ -30,6 +30,7 @@ import {
submitPerformanceSurveyWorkItemScores,
submitPerformanceSurveyWorkItemScore,
submitPerformanceSurveyResponse,
previewPerformanceSurveyEmployeeProfiles,
syncPerformanceSurveyEmployeeProfiles,
updatePerformanceSurvey,
savePerformanceSurveyAdminPositionGroup,
@ -248,7 +249,16 @@ export async function POST(request: Request, context: RouteContext) {
return ok(await submitPerformanceSurveyWorkItemScore(session, path[1], path[3], body))
}
if (path[0] === 'admin' && path[1] === 'sync-employees') {
if (
path[0] === 'admin'
&& path[1] === 'sync-employees'
&& path[2] === 'preview'
&& path.length === 3
) {
return ok(await previewPerformanceSurveyEmployeeProfiles(session, body))
}
if (path[0] === 'admin' && path[1] === 'sync-employees' && path.length === 2) {
return ok(await syncPerformanceSurveyEmployeeProfiles(session, body))
}

View File

@ -153,15 +153,35 @@ describe('PerformanceSurveyAdminConfig', () => {
test('概览展示岗位、人员、模板和月度方案状态', async () => {
const request = createRequest()
render(<PerformanceSurveyAdminConfig mode="overview" request={request} />)
const onNavigate = jest.fn()
render(<PerformanceSurveyAdminConfig mode="overview" request={request} onNavigate={onNavigate} />)
expect(screen.getByText('配置加载中...')).toBeInTheDocument()
await waitFor(() => expect(screen.getByRole('heading', { name: '2026-07 配置概览' })).toBeInTheDocument())
expect(screen.getByRole('rowheader', { name: '岗位' })).toBeInTheDocument()
expect(screen.getByText('未匹配 1 人')).toBeInTheDocument()
expect(screen.getByRole('heading', { name: '本月上线准备' })).toBeInTheDocument()
expect(screen.getByText(/1 人待确认/)).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: '处理人员' }))
expect(onNavigate).toHaveBeenCalledWith('people')
expect(request).toHaveBeenCalledWith(expect.stringContaining('/admin/config-audit-logs'))
})
test('受控月份切换通过外层更新,保持管理工作区月份一致', async () => {
const request = createRequest()
const onMonthChange = jest.fn()
render(
<PerformanceSurveyAdminConfig
mode="overview"
request={request}
month="2026-08"
onMonthChange={onMonthChange}
/>,
)
await waitFor(() => expect(screen.getByRole('heading', { name: '2026-08 配置概览' })).toBeInTheDocument())
fireEvent.change(screen.getByLabelText('查看月份'), { target: { value: '2026-09' } })
expect(onMonthChange).toHaveBeenCalledWith('2026-09')
})
test('岗位编辑产生 dirty 状态并保护岗位切换', async () => {
const request = createRequest()
const onDirtyChange = jest.fn()
@ -200,7 +220,7 @@ describe('PerformanceSurveyAdminConfig', () => {
const request = createRequest()
render(<PerformanceSurveyAdminConfig mode="people" request={request} />)
await waitFor(() => expect(screen.getByText('张三')).toBeInTheDocument())
await waitFor(() => expect(screen.getAllByText('张三').length).toBeGreaterThan(0))
fireEvent.click(screen.getByLabelText('选择 张三'))
fireEvent.change(screen.getByLabelText('批量分配操作'), { target: { value: 'group-1' } })
fireEvent.change(screen.getByLabelText('本次调整原因'), { target: { value: '部门异动' } })
@ -236,6 +256,21 @@ describe('PerformanceSurveyAdminConfig', () => {
expect(screen.getByRole('button', { name: '归档模板' })).toBeInTheDocument()
})
test('模板编辑按基本信息、评分项、评审与计分分步展示', async () => {
const request = createRequest()
render(<PerformanceSurveyAdminConfig mode="templates" request={request} />)
await waitFor(() => expect(screen.getByRole('navigation', { name: '模板编辑步骤' })).toBeInTheDocument())
expect(screen.getByRole('heading', { name: '基本信息' })).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: '2. 评分项' }))
expect(screen.getByRole('heading', { name: '评分项' })).toBeInTheDocument()
expect(screen.getByLabelText('评分项名称')).toHaveValue('作品质量')
fireEvent.click(screen.getByRole('button', { name: '3. 评审与计分' }))
expect(screen.getByRole('heading', { name: '评审与计分' })).toBeInTheDocument()
expect(screen.getByLabelText('最终成绩规则')).toBeInTheDocument()
})
test('月度方案可添加排序模板并经过影响确认后发布', async () => {
const request = createRequest()
render(<PerformanceSurveyAdminConfig mode="plans" request={request} />)

View File

@ -170,7 +170,7 @@ function clone<T>(value: T): T {
function newTemplateDefinition(): TemplateDefinition {
return {
code: '',
code: `template_${Date.now().toString(36)}`,
name: '',
shortName: '',
description: '',
@ -200,16 +200,31 @@ function reviewerSourceLabel(source: ReviewerSource) {
}[source]
}
function surveyTypeLabel(type: TemplateDefinition['surveyType']) {
return {
person_period: '人员周期评分',
visual_case: '视觉案例评分',
item_course: '事项 / 课程评分',
}[type]
}
export function PerformanceSurveyAdminConfig({
mode,
request,
onDirtyChange,
month: controlledMonth,
onMonthChange,
onNavigate,
}: {
mode: PerformanceSurveyAdminMode
request: RequestFn
onDirtyChange?: (dirty: boolean) => void
month?: string
onMonthChange?: (month: string) => void
onNavigate?: (mode: PerformanceSurveyAdminMode | 'launch') => void
}) {
const [month, setMonth] = useState(currentMonth())
const [internalMonth, setInternalMonth] = useState(controlledMonth || currentMonth())
const month = controlledMonth || internalMonth
const [data, setData] = useState<AdminConfig | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
@ -267,7 +282,8 @@ export function PerformanceSurveyAdminConfig({
if (!confirmDiscard('切换月份会放弃当前未保存修改,确定继续吗?')) return
setDirtyState(false)
setNotice(null)
setMonth(nextMonth)
if (onMonthChange) onMonthChange(nextMonth)
else setInternalMonth(nextMonth)
}
const changed = useCallback(async (message: string) => {
@ -291,7 +307,7 @@ export function PerformanceSurveyAdminConfig({
}[mode]}
</h2>
<p className="mt-0.5 text-[12px] text-[#5f5e5e]">
{dirty ? '有未保存修改' : '配置按月份查看;已发布版本保持不变'}
{dirty ? `${month} 有未保存修改` : `正在维护 ${month};已发布版本保持不变`}
</p>
</div>
<label className="flex items-center gap-2 text-[12px] font-semibold text-[#5f5e5e]">
@ -304,14 +320,23 @@ export function PerformanceSurveyAdminConfig({
/>
</label>
</div>
{notice && <div role="status" className="border-b border-[#b3c5ff] bg-[#f8faff] px-4 py-3 text-[13px] font-semibold text-[#0050cb]">{notice}</div>}
{notice && (
<>
<div role="status" aria-live="polite" className="border-b border-[#b3c5ff] bg-[#f8faff] px-4 py-3 text-[13px] font-semibold text-[#0050cb]">
{notice}
</div>
<div className="fixed bottom-[76px] right-4 z-50 max-w-[calc(100vw-2rem)] border border-[#b3c5ff] bg-white px-4 py-3 text-[13px] font-semibold text-[#0050cb] shadow-[0_12px_30px_rgba(0,0,0,0.14)] sm:bottom-5">
{notice}
</div>
</>
)}
{error && (
<div role="alert" className="flex flex-wrap items-center justify-between gap-3 border-b border-[#ffdad6] bg-[#fff6f4] px-4 py-3 text-[13px] font-semibold text-[#93000a]">
<span>{error}</span>
{!data && <button type="button" onClick={() => void load(month)} className="min-h-9 px-2 underline">重新加载</button>}
</div>
)}
{loading && !data && <div className="px-5 py-12 text-center text-[13px] font-semibold text-[#5f5e5e]">配置加载中...</div>}
{loading && !data && <div role="status" aria-live="polite" className="px-5 py-12 text-center text-[13px] font-semibold text-[#5f5e5e]">配置加载中...</div>}
{data && (
<div className={`p-4 sm:p-5 ${loading ? 'pointer-events-none opacity-60' : ''}`} aria-busy={loading}>
{mode === 'overview' && (
@ -319,6 +344,7 @@ export function PerformanceSurveyAdminConfig({
data={data}
month={month}
request={request}
onNavigate={onNavigate}
/>
)}
{mode === 'positions' && (
@ -378,18 +404,84 @@ function AdminOverviewWorkspace({
data,
month,
request,
onNavigate,
}: {
data: AdminConfig
month: string
request: RequestFn
onNavigate?: (mode: PerformanceSurveyAdminMode | 'launch') => void
}) {
const [audits, setAudits] = useState<ConfigAudit[]>([])
const [auditError, setAuditError] = useState<string | null>(null)
const [auditLoading, setAuditLoading] = useState(true)
const readyGroups = data.groups.filter((group) => group.status === 'ready').length
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
const availablePublishedTemplates = data.templates
.flatMap((template) => template.versions)
.filter((version) => (
version.status === 'published'
&& (!version.effectiveMonth || version.effectiveMonth <= month)
)).length
const effectivePlanCount = activeGroups.filter((group) => group.effectivePlan?.effectiveMonth === month).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 templatesReady = availablePublishedTemplates > 0
const plansReady = activeGroups.length > 0 && effectivePlanCount === activeGroups.length
const launchReady = positionsReady && templatesReady && plansReady && data.issues.conflicts.length === 0
const steps = [
{
id: 'people',
label: '确认人员资料',
status: data.issues.conflicts.length > 0 ? 'blocked' : hasPeopleIssues ? 'attention' : 'done',
summary: data.issues.conflicts.length > 0
? `${data.issues.conflicts.length} 人同时匹配多个岗位,必须先处理`
: data.issues.unmatched.length > 0
? `${data.issues.unmatched.length} 人待确认:分配岗位,或明确标记为不参与`
: '人员岗位归属没有待处理异常',
action: '处理人员',
target: 'people' as const,
},
{
id: 'positions',
label: '确认岗位',
status: positionsReady ? 'done' : 'attention',
summary: activeGroups.length === 0
? '还没有可用岗位'
: `${groupsWithMatchingRules}/${activeGroups.length} 个在用岗位已完成匹配规则${disabledGroups > 0 ? `,另有 ${disabledGroups} 个已归档` : ''}`,
action: '管理岗位',
target: 'positions' as const,
},
{
id: 'templates',
label: '准备考核模板',
status: templatesReady ? (draftTemplates > 0 ? 'attention' : 'done') : 'blocked',
summary: templatesReady
? `${availablePublishedTemplates} 个版本可用于 ${month}${draftTemplates > 0 ? `,${draftTemplates} 个草稿待确认` : ''}`
: `还没有可用于 ${month} 的已发布模板,月度方案无法完成${publishedTemplates > 0 ? `(另有 ${publishedTemplates} 个其它月份版本)` : ''}`,
action: '管理模板',
target: 'templates' as const,
},
{
id: 'plans',
label: '发布月度方案',
status: plansReady ? 'done' : draftPlanCount > 0 ? 'attention' : 'blocked',
summary: `${effectivePlanCount}/${activeGroups.length} 个在用岗位已有 ${month} 方案${draftPlanCount > 0 ? `,${draftPlanCount} 个草稿待发布` : ''}`,
action: '配置方案',
target: 'plans' as const,
},
{
id: 'launch',
label: '发起调研',
status: launchReady ? 'ready' : 'blocked',
summary: launchReady ? `${month} 的岗位、模板和方案已可用于发起调研` : '完成上面的必要配置后再发起,避免人员或模板选错',
action: '去发起调研',
target: 'launch' as const,
},
]
const loadAudits = useCallback(async () => {
setAuditLoading(true)
@ -420,49 +512,53 @@ function AdminOverviewWorkspace({
</p>
</div>
<div className="mt-4 overflow-x-auto border border-[#c2c6d8]">
<table className="w-full min-w-[640px] border-collapse text-left">
<thead>
<tr className="border-b border-[#c2c6d8] bg-[#f4f3f3] text-[12px] font-bold text-[#5f5e5e]">
<th scope="col" className="px-4 py-3">维护项</th>
<th scope="col" className="px-4 py-3">当前状态</th>
<th scope="col" className="px-4 py-3">需要处理</th>
</tr>
</thead>
<tbody className="divide-y divide-[#e2e2e2] text-[13px]">
<tr>
<th scope="row" className="px-4 py-3 font-bold text-[#1a1c1c]">岗位</th>
<td className="px-4 py-3 text-[#5f5e5e]">{readyGroups}/{data.groups.length} 个岗位已就绪</td>
<td className="px-4 py-3 text-[#5f5e5e]">{disabledGroups > 0 ? `${disabledGroups} 个已归档` : '无归档岗位'}</td>
</tr>
<tr>
<th scope="row" className="px-4 py-3 font-bold text-[#1a1c1c]">人员</th>
<td className="px-4 py-3 text-[#5f5e5e]">未匹配 {data.issues.unmatched.length} 人</td>
<td className={`px-4 py-3 font-semibold ${data.issues.conflicts.length > 0 ? 'text-[#b42318]' : 'text-[#16794b]'}`}>
{data.issues.conflicts.length > 0 ? `重复匹配 ${data.issues.conflicts.length} 人` : '无重复匹配'}
</td>
</tr>
<tr>
<th scope="row" className="px-4 py-3 font-bold text-[#1a1c1c]">模板</th>
<td className="px-4 py-3 text-[#5f5e5e]">{publishedTemplates} 个已发布版本</td>
<td className="px-4 py-3 text-[#5f5e5e]">{draftTemplates > 0 ? `${draftTemplates} 个草稿待处理` : '无待发布草稿'}</td>
</tr>
<tr>
<th scope="row" className="px-4 py-3 font-bold text-[#1a1c1c]">月度方案</th>
<td className="px-4 py-3 text-[#5f5e5e]">
{data.groups.filter((group) => group.effectivePlan?.effectiveMonth === month).length} 个岗位本月已有方案
</td>
<td className="px-4 py-3 text-[#5f5e5e]">
{data.groups.filter((group) => group.draftPlan).length} 个岗位有未发布草稿
</td>
</tr>
</tbody>
</table>
<div className="mt-4 border border-[#c2c6d8]">
<div className="border-b border-[#e2e2e2] bg-[#f7f7f7] px-4 py-3">
<h3 className="text-[14px] font-bold text-[#1a1c1c]">本月上线准备</h3>
<p className="mt-1 text-[12px] leading-5 text-[#5f5e5e]">按顺序完成;每一步都可以直接进入对应管理页面。</p>
</div>
<ol className="divide-y divide-[#e2e2e2]">
{steps.map((step, index) => {
const statusLabel = {
done: '已完成',
attention: '待确认',
blocked: '未完成',
ready: '可发起',
}[step.status]
const statusClass = {
done: 'bg-[#eaf7ef] text-[#16794b]',
attention: 'bg-[#fff4da] text-[#7a4b00]',
blocked: 'bg-[#f3f3f3] text-[#5f5e5e]',
ready: 'bg-[#e9efff] text-[#0050cb]',
}[step.status]
return (
<li key={step.id} className="grid gap-3 px-4 py-4 sm:grid-cols-[40px_minmax(0,1fr)_auto] sm:items-center">
<div className="flex h-8 w-8 items-center justify-center rounded-full border border-[#c2c6d8] text-[13px] font-bold text-[#1a1c1c]" aria-hidden="true">
{index + 1}
</div>
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<h4 className="text-[14px] font-bold text-[#1a1c1c]">{step.label}</h4>
<span className={`rounded-full px-2 py-1 text-[11px] font-bold ${statusClass}`}>{statusLabel}</span>
</div>
<p className="mt-1 text-[12px] leading-5 text-[#5f5e5e]">{step.summary}</p>
</div>
<button
type="button"
onClick={() => onNavigate?.(step.target)}
className="min-h-11 w-full rounded border border-[#1a1c1c] px-4 text-[12px] font-bold text-[#1a1c1c] hover:bg-[#1a1c1c] hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0050cb] focus-visible:ring-offset-2 sm:w-auto"
>
{step.action}
</button>
</li>
)
})}
</ol>
</div>
{(data.issues.unmatched.length > 0 || data.issues.conflicts.length > 0) && (
<div className="mt-4 border border-[#e4b86a] bg-[#fffaf0] px-4 py-3 text-[13px] leading-5 text-[#6f4700]">
发布前请先处理人员分配:未匹配 {data.issues.unmatched.length} 人,重复匹配 {data.issues.conflicts.length} 人。
“未匹配”不等于必须参与考核。请逐一确认:需要参与的人分配岗位,不参与的人明确标记为“不参与”;重复匹配人员必须先消除冲突。
</div>
)}
@ -473,7 +569,7 @@ function AdminOverviewWorkspace({
刷新
</button>
</div>
{auditLoading && <div className="py-6 text-[13px] font-semibold text-[#5f5e5e]">记录加载中...</div>}
{auditLoading && <div role="status" aria-live="polite" className="py-6 text-[13px] font-semibold text-[#5f5e5e]">记录加载中...</div>}
{auditError && (
<div role="note" className="py-4 text-[13px] text-[#8a5700]">
配置记录暂不可用:{auditError}
@ -886,6 +982,7 @@ function TemplateConfigWorkspace({
|| null
const [versionId, setVersionId] = useState<string | null>(selectedVersion?.id || null)
const [definition, setDefinition] = useState<TemplateDefinition>(() => clone(selectedVersion?.definition || newTemplateDefinition()))
const [editorStep, setEditorStep] = useState<'basics' | 'questions' | 'workflow'>('basics')
const [saving, setSaving] = useState(false)
const editorRef = useRef<HTMLDivElement>(null)
@ -895,6 +992,7 @@ function TemplateConfigWorkspace({
|| null
setVersionId(nextVersion?.id || null)
setDefinition(clone(nextVersion?.definition || newTemplateDefinition()))
setEditorStep('basics')
onDirtyChange(false)
}, [onDirtyChange, selectedTemplate])
@ -1036,6 +1134,7 @@ function TemplateConfigWorkspace({
onDirtyChange(false)
setVersionId(item.id)
setDefinition(clone(item.definition))
setEditorStep('basics')
}}
className={`min-h-10 rounded border px-3 text-left text-[12px] font-bold ${versionId === item.id ? 'border-[#0050cb] bg-[#f1f4ff] text-[#0050cb]' : 'border-[#e2e2e2] text-[#5f5e5e]'}`}
>
@ -1054,48 +1153,107 @@ function TemplateConfigWorkspace({
</div>
)}
<div className="grid gap-4 sm:grid-cols-2">
<AdminField label="模板代码" value={definition.code} onChange={(value) => updateDefinition((current) => ({ ...current, code: value }))} disabled={Boolean(selectedTemplate)} />
<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} />
<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>
</select>
</label>
<label className="grid gap-1 sm:col-span-2 text-[12px] font-semibold text-[#5f5e5e]">
说明
<textarea
value={definition.description}
disabled={!editable}
onChange={(event) => updateDefinition((current) => ({ ...current, description: event.target.value }))}
className="min-h-20 rounded border border-[#e2e2e2] px-3 py-2 text-[13px] font-normal text-[#1a1c1c] outline-none focus:border-[#0050cb] disabled:bg-[#f4f4f4]"
/>
</label>
</div>
{definition.surveyType === 'visual_case' && (
<div className="mt-5 grid gap-4 border-t border-[#eeeeee] pt-5 sm:grid-cols-2">
<AdminField
label="要求作品数量"
value={String(definition.requiredWorkItemCount || 3)}
type="number"
disabled={!editable}
onChange={(value) => updateDefinition((current) => ({ ...current, requiredWorkItemCount: Math.max(1, Number(value) || 1), workItemImageRequired: true }))}
/>
<section aria-label="模板摘要" className="mb-5 border border-[#c2c6d8] bg-[#fafafa] px-4 py-3">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0">
<div className="text-[11px] font-bold text-[#727687]">当前模板</div>
<div className="mt-1 truncate text-[16px] font-bold text-[#1a1c1c]">{definition.name || '未命名模板'}</div>
<div className="mt-1 text-[12px] leading-5 text-[#5f5e5e]">
{surveyTypeLabel(definition.surveyType)} · {definition.questions.length} 个评分项 · {definition.workflow.stages.length} 个评审阶段
</div>
</div>
<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)}
</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>
<div className="text-[11px] font-semibold text-[#727687]">{editable ? '草稿可编辑' : '已发布只读'}</div>
</div>
</div>
</div>
</section>
<nav aria-label="模板编辑步骤" className="mb-5 grid grid-cols-3 border border-[#c2c6d8]">
{([
['basics', '1. 基本信息'],
['questions', '2. 评分项'],
['workflow', '3. 评审与计分'],
] as const).map(([step, label]) => (
<button
key={step}
type="button"
aria-current={editorStep === step ? 'step' : undefined}
onClick={() => setEditorStep(step)}
className={`min-h-11 border-r border-[#c2c6d8] px-2 text-[12px] font-bold last:border-r-0 ${
editorStep === step ? 'bg-[#1a1c1c] text-white' : 'bg-white text-[#5f5e5e] hover:bg-[#f4f4f4]'
}`}
>
{label}
</button>
))}
</nav>
{editorStep === 'basics' && (
<section aria-labelledby="template-basics-heading">
<div className="mb-4">
<h3 id="template-basics-heading" className="text-[15px] font-bold text-[#1a1c1c]">基本信息</h3>
<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} />
<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>
</select>
</label>
{definition.surveyType === 'visual_case' && (
<AdminField
label="每人需要提交的作品数量"
value={String(definition.requiredWorkItemCount || 3)}
type="number"
disabled={!editable}
onChange={(value) => updateDefinition((current) => ({ ...current, requiredWorkItemCount: Math.max(1, Number(value) || 1), workItemImageRequired: true }))}
/>
)}
<label className="grid gap-1 sm:col-span-2 text-[12px] font-semibold text-[#5f5e5e]">
给发起人和评分人的说明
<textarea
value={definition.description}
disabled={!editable}
onChange={(event) => updateDefinition((current) => ({ ...current, description: event.target.value }))}
className="min-h-24 rounded border border-[#e2e2e2] px-3 py-2 text-[13px] font-normal text-[#1a1c1c] outline-none focus:border-[#0050cb] disabled:bg-[#f4f4f4]"
/>
</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>
)}
<QuestionEditor definition={definition} editable={editable} onChange={updateDefinition} />
<WorkflowEditor definition={definition} editable={editable} request={request} onChange={updateDefinition} />
{editorStep === 'questions' && (
<QuestionEditor definition={definition} editable={editable} onChange={updateDefinition} />
)}
{editorStep === 'workflow' && (
<WorkflowEditor definition={definition} editable={editable} request={request} onChange={updateDefinition} />
)}
<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>}
@ -1376,9 +1534,12 @@ function QuestionEditor({
onChange: (definition: TemplateDefinition) => void
}) {
return (
<div className="mt-6 border-t border-[#eeeeee] pt-5">
<div className="flex items-center justify-between gap-3">
<h3 className="text-[14px] font-bold text-[#1a1c1c]">评分项</h3>
<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>
</div>
{editable && (
<button
type="button"
@ -1391,24 +1552,77 @@ function QuestionEditor({
maxScore: definition.questionMaxScore || 20,
}],
})}
className="h-9 border border-[#e2e2e2] px-3 text-[12px] font-bold text-[#1a1c1c]"
className="min-h-11 rounded border border-[#1a1c1c] px-4 text-[12px] font-bold text-[#1a1c1c] hover:bg-[#1a1c1c] hover:text-white"
>
添加评分项
</button>
)}
</div>
<div className="mt-3 grid gap-2">
<div className="mt-4 grid gap-3">
{definition.questions.map((question, index) => (
<div key={`${question.id}-${index}`} className="grid gap-2 border border-[#eeeeee] p-3 lg:grid-cols-[140px_minmax(160px,0.8fr)_minmax(220px,1fr)_90px_36px]">
<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-9 rounded border border-[#e2e2e2] px-2 text-[12px] outline-none disabled:bg-[#f4f4f4]" />
<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-9 rounded border border-[#e2e2e2] px-2 text-[12px] outline-none disabled:bg-[#f4f4f4]" />
<input value={question.description || ''} disabled={!editable} placeholder="评分说明" onChange={(event) => onChange({ ...definition, questions: definition.questions.map((item, itemIndex) => itemIndex === index ? { ...item, description: event.target.value } : item) })} className="h-9 rounded border border-[#e2e2e2] px-2 text-[12px] outline-none disabled:bg-[#f4f4f4]" />
<input type="number" min="1" value={question.maxScore || 20} disabled={!editable} aria-label={`${question.title}满分`} onChange={(event) => onChange({ ...definition, questions: definition.questions.map((item, itemIndex) => itemIndex === index ? { ...item, maxScore: Number(event.target.value) || 1 } : item) })} className="h-9 rounded border border-[#e2e2e2] px-2 text-[12px] outline-none disabled:bg-[#f4f4f4]" />
{editable && <button type="button" aria-label="删除评分项" title="删除评分项" onClick={() => onChange({ ...definition, questions: definition.questions.filter((_, itemIndex) => itemIndex !== index) })} className="h-9 border border-[#e2e2e2] text-[18px] text-[#8c1d18]">×</button>}
<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">
<div className="text-[13px] font-bold text-[#1a1c1c]">评分项 {index + 1}</div>
{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]"
>
删除
</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]">
评分项名称
<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]"
/>
</label>
<label className="grid gap-1 text-[12px] font-semibold text-[#5f5e5e]">
满分
<input
type="number"
min="1"
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]"
/>
</label>
<label className="grid gap-1 text-[12px] font-semibold text-[#5f5e5e] sm:col-span-2">
评分说明(可选)
<textarea
value={question.description || ''}
disabled={!editable}
placeholder="告诉评分人这一项应该看什么"
onChange={(event) => onChange({ ...definition, questions: definition.questions.map((item, itemIndex) => itemIndex === index ? { ...item, description: event.target.value } : item) })}
className="min-h-20 rounded border border-[#e2e2e2] px-3 py-2 text-[13px] outline-none focus:border-[#0050cb] disabled:bg-[#f4f4f4]"
/>
</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>
</div>
</section>
)
}
@ -1423,33 +1637,67 @@ function WorkflowEditor({
request: RequestFn
onChange: (definition: TemplateDefinition) => void
}) {
const updateStages = (stages: StageDraft[]) => onChange({
...definition,
workflow: { ...definition.workflow, stages: stages.map((stage, index) => ({ ...stage, order: index })) },
})
const updateStages = (nextStages: StageDraft[]) => {
const stages = nextStages.map((stage, index) => ({ ...stage, order: index }))
const currentScoring = definition.workflow.scoring
const scoring = currentScoring.mode === 'average_reviewers'
? { mode: 'average_reviewers' as const, stageKeys: stages.map((stage) => stage.key) }
: (() => {
const selectedStage = stages.find((stage) => stage.key === currentScoring.stageKey) || stages[stages.length - 1]
const selectedReviewer = selectedStage?.reviewers.find((reviewer) => reviewer.source === currentScoring.reviewerSource)
|| selectedStage?.reviewers[0]
return {
mode: 'final_reviewer' as const,
stageKey: selectedStage?.key || '',
reviewerSource: selectedReviewer?.source || 'manual_selection' as ReviewerSource,
}
})()
onChange({
...definition,
workflow: { ...definition.workflow, stages, scoring },
})
}
const stages = definition.workflow.stages
return (
<div className="mt-6 border-t border-[#eeeeee] pt-5">
<div className="flex items-center justify-between gap-3">
<section aria-labelledby="template-workflow-heading">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 className="text-[14px] font-bold text-[#1a1c1c]">评审流程</h3>
<h3 id="template-workflow-heading" className="text-[15px] font-bold text-[#1a1c1c]">评审与计分</h3>
<p className="mt-1 text-[12px] text-[#727687]">同阶段并行,上一阶段全部提交后开放下一阶段</p>
</div>
{editable && <button type="button" onClick={() => updateStages([...stages, { key: `stage_${stages.length + 1}`, label: `阶段 ${stages.length + 1}`, order: stages.length, reviewers: [{ source: 'manual_selection', label: '评价人' }] }])} className="h-9 border border-[#e2e2e2] px-3 text-[12px] font-bold text-[#1a1c1c]">添加阶段</button>}
{editable && <button type="button" onClick={() => updateStages([...stages, { key: `stage_${stages.length + 1}`, label: `阶段 ${stages.length + 1}`, order: stages.length, reviewers: [{ source: 'manual_selection', label: '评价人' }] }])} className="min-h-11 rounded border border-[#1a1c1c] px-4 text-[12px] font-bold text-[#1a1c1c] hover:bg-[#1a1c1c] hover:text-white">添加阶段</button>}
</div>
<div className="mt-3 grid gap-3">
{stages.map((stage, stageIndex) => (
<div key={`${stage.key}-${stageIndex}`} className="border border-[#eeeeee] p-3">
<div className="grid gap-2 sm:grid-cols-[130px_minmax(180px,1fr)_auto]">
<input value={stage.key} disabled={!editable} onChange={(event) => updateStages(stages.map((item, index) => index === stageIndex ? { ...item, key: event.target.value } : item))} className="h-9 rounded border border-[#e2e2e2] px-2 text-[12px] outline-none disabled:bg-[#f4f4f4]" />
<input value={stage.label} disabled={!editable} onChange={(event) => updateStages(stages.map((item, index) => index === stageIndex ? { ...item, label: event.target.value } : item))} className="h-9 rounded border border-[#e2e2e2] px-2 text-[12px] outline-none disabled:bg-[#f4f4f4]" />
{editable && <button type="button" onClick={() => updateStages(stages.filter((_, index) => index !== stageIndex))} className="h-9 border border-[#e2e2e2] px-3 text-[12px] font-bold text-[#8c1d18]">删除阶段</button>}
<div key={`${stage.key}-${stageIndex}`} className="border border-[#e2e2e2] p-4">
<div className="flex items-end gap-3">
<label className="grid min-w-0 flex-1 gap-1 text-[12px] font-semibold text-[#5f5e5e]">
阶段 {stageIndex + 1} 名称
<input
value={stage.label}
disabled={!editable}
onChange={(event) => updateStages(stages.map((item, index) => index === stageIndex ? { ...item, label: event.target.value } : item))}
className="h-11 rounded border border-[#e2e2e2] px-3 text-[13px] outline-none focus:border-[#0050cb] disabled:bg-[#f4f4f4]"
/>
</label>
{editable && (
<button
type="button"
disabled={stages.length <= 1}
onClick={() => updateStages(stages.filter((_, index) => index !== stageIndex))}
className="min-h-11 rounded px-3 text-[12px] font-bold text-[#b42318] hover:bg-[#fff5f5] disabled:cursor-not-allowed disabled:text-[#aaaaaa]"
>
删除阶段
</button>
)}
</div>
<p className="mt-3 text-[11px] font-bold text-[#727687]">本阶段评分人</p>
<div className="mt-3 grid gap-2">
{stage.reviewers.map((reviewer, reviewerIndex) => (
<div key={`${stage.key}-${reviewerIndex}`} className="grid gap-2 sm:grid-cols-[180px_minmax(180px,1fr)_36px]">
<div key={`${stage.key}-${reviewerIndex}`} className="grid gap-2 sm:grid-cols-[180px_minmax(180px,1fr)_72px]">
<select
aria-label={`阶段 ${stageIndex + 1} 评分人类型 ${reviewerIndex + 1}`}
value={reviewer.source}
disabled={!editable}
onChange={(event) => updateStages(stages.map((item, index) => index === stageIndex ? {
@ -1459,7 +1707,7 @@ function WorkflowEditor({
label: reviewerSourceLabel(event.target.value as ReviewerSource),
} : entry),
} : item))}
className="h-9 rounded border border-[#e2e2e2] bg-white px-2 text-[12px] font-semibold outline-none disabled:bg-[#f4f4f4]"
className="h-11 rounded border border-[#e2e2e2] bg-white px-3 text-[12px] font-semibold outline-none focus:border-[#0050cb] disabled:bg-[#f4f4f4]"
>
<option value="self">本人</option>
<option value="direct_manager">直属主管</option>
@ -1477,20 +1725,52 @@ function WorkflowEditor({
} : item))}
/>
) : (
<input value={reviewer.label} disabled={!editable} onChange={(event) => updateStages(stages.map((item, index) => index === stageIndex ? { ...item, reviewers: item.reviewers.map((entry, entryIndex) => entryIndex === reviewerIndex ? { ...entry, label: event.target.value } : entry) } : item))} className="h-9 rounded border border-[#e2e2e2] px-2 text-[12px] outline-none disabled:bg-[#f4f4f4]" />
<input
aria-label={`阶段 ${stageIndex + 1} 评分人显示名称 ${reviewerIndex + 1}`}
value={reviewer.label}
disabled={!editable}
onChange={(event) => updateStages(stages.map((item, index) => index === stageIndex ? { ...item, reviewers: item.reviewers.map((entry, entryIndex) => entryIndex === reviewerIndex ? { ...entry, label: event.target.value } : entry) } : item))}
className="h-11 rounded border border-[#e2e2e2] px-3 text-[12px] outline-none focus:border-[#0050cb] disabled:bg-[#f4f4f4]"
/>
)}
{editable && (
<button
type="button"
disabled={stage.reviewers.length <= 1}
aria-label={`删除阶段 ${stageIndex + 1} 的第 ${reviewerIndex + 1} 类评分人`}
onClick={() => updateStages(stages.map((item, index) => index === stageIndex ? { ...item, reviewers: item.reviewers.filter((_, entryIndex) => entryIndex !== reviewerIndex) } : item))}
className="min-h-11 rounded text-[12px] font-bold text-[#b42318] hover:bg-[#fff5f5] disabled:cursor-not-allowed disabled:text-[#aaaaaa]"
>
删除
</button>
)}
{editable && <button type="button" aria-label="删除评分人来源" title="删除" onClick={() => updateStages(stages.map((item, index) => index === stageIndex ? { ...item, reviewers: item.reviewers.filter((_, entryIndex) => entryIndex !== reviewerIndex) } : item))} className="h-9 border border-[#e2e2e2] text-[18px] text-[#8c1d18]">×</button>}
</div>
))}
{editable && <button type="button" onClick={() => updateStages(stages.map((item, index) => index === stageIndex ? { ...item, reviewers: [...item.reviewers, { source: 'manual_selection', label: '评价人' }] } : item))} className="h-8 w-fit border border-[#e2e2e2] px-3 text-[11px] font-bold text-[#1a1c1c]">添加评分人来源</button>}
{editable && <button type="button" onClick={() => updateStages(stages.map((item, index) => index === stageIndex ? { ...item, reviewers: [...item.reviewers, { source: 'manual_selection', label: '评价人' }] } : item))} className="min-h-11 w-fit rounded border border-[#e2e2e2] px-3 text-[11px] font-bold text-[#1a1c1c] hover:border-[#1a1c1c]">添加一类评分人</button>}
</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={stage.key}
disabled={!editable}
onChange={(event) => updateStages(stages.map((item, index) => index === stageIndex ? { ...item, key: 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>
<div className="mt-4 grid gap-3 sm:grid-cols-3">
<div className="mt-5 border-t border-[#eeeeee] pt-5">
<h4 className="text-[14px] font-bold text-[#1a1c1c]">最终成绩采用哪一组评分</h4>
<p className="mt-1 text-[12px] leading-5 text-[#727687]">这里只决定最终展示的分数;各评分人的原始分仍会保留。</p>
</div>
<div className="mt-3 grid gap-3 sm:grid-cols-3">
<label className="grid gap-1 text-[12px] font-semibold text-[#5f5e5e]">
计分方式
最终成绩规则
<select
value={definition.workflow.scoring.mode}
disabled={!editable}
@ -1503,30 +1783,30 @@ function WorkflowEditor({
: { mode: 'average_reviewers', stageKeys: stages.map((stage) => stage.key) },
},
})}
className="h-9 rounded border border-[#e2e2e2] bg-white px-2 text-[12px] font-semibold disabled:bg-[#f4f4f4]"
className="h-11 rounded border border-[#e2e2e2] bg-white px-3 text-[12px] font-semibold disabled:bg-[#f4f4f4]"
>
<option value="average_reviewers">指定阶段平均分</option>
<option value="final_reviewer">指定终审人得分</option>
<option value="average_reviewers">所有指定阶段评分取平均</option>
<option value="final_reviewer">以指定终审人评分为准</option>
</select>
</label>
{definition.workflow.scoring.mode === 'final_reviewer' && (
<>
<label className="grid gap-1 text-[12px] font-semibold text-[#5f5e5e]">
终审阶段
<select value={definition.workflow.scoring.stageKey || ''} disabled={!editable} onChange={(event) => onChange({ ...definition, workflow: { ...definition.workflow, scoring: { ...definition.workflow.scoring, mode: 'final_reviewer', stageKey: event.target.value } } })} className="h-9 rounded border border-[#e2e2e2] bg-white px-2 text-[12px] font-semibold disabled:bg-[#f4f4f4]">
<select value={definition.workflow.scoring.stageKey || ''} disabled={!editable} onChange={(event) => onChange({ ...definition, workflow: { ...definition.workflow, scoring: { ...definition.workflow.scoring, mode: 'final_reviewer', stageKey: event.target.value } } })} className="h-11 rounded border border-[#e2e2e2] bg-white px-3 text-[12px] font-semibold disabled:bg-[#f4f4f4]">
{stages.map((stage) => <option key={stage.key} value={stage.key}>{stage.label}</option>)}
</select>
</label>
<label className="grid gap-1 text-[12px] font-semibold text-[#5f5e5e]">
终审人来源
<select value={definition.workflow.scoring.reviewerSource || ''} disabled={!editable} onChange={(event) => onChange({ ...definition, workflow: { ...definition.workflow, scoring: { ...definition.workflow.scoring, mode: 'final_reviewer', reviewerSource: event.target.value as ReviewerSource } } })} className="h-9 rounded border border-[#e2e2e2] bg-white px-2 text-[12px] font-semibold disabled:bg-[#f4f4f4]">
<select value={definition.workflow.scoring.reviewerSource || ''} disabled={!editable} onChange={(event) => onChange({ ...definition, workflow: { ...definition.workflow, scoring: { ...definition.workflow.scoring, mode: 'final_reviewer', reviewerSource: event.target.value as ReviewerSource } } })} className="h-11 rounded border border-[#e2e2e2] bg-white px-3 text-[12px] font-semibold disabled:bg-[#f4f4f4]">
{(stages.find((stage) => stage.key === definition.workflow.scoring.stageKey)?.reviewers || []).map((reviewer) => <option key={reviewer.source} value={reviewer.source}>{reviewer.employeeName || reviewer.label}</option>)}
</select>
</label>
</>
)}
</div>
</div>
</section>
)
}
@ -1562,6 +1842,7 @@ function FixedReviewerPicker({
return (
<div className="relative min-w-0">
<input
aria-label="搜索固定评分人"
value={search || value.employeeName || ''}
disabled={disabled}
onChange={(event) => {
@ -1569,10 +1850,10 @@ function FixedReviewerPicker({
onChange({ source: 'fixed_employee', label: '固定员工' })
}}
placeholder="搜索固定评分人"
className="h-9 w-full rounded border border-[#e2e2e2] px-2 text-[12px] outline-none disabled:bg-[#f4f4f4]"
className="h-11 w-full rounded border border-[#e2e2e2] px-3 text-[12px] outline-none focus:border-[#0050cb] disabled:bg-[#f4f4f4]"
/>
{items.length > 0 && (
<div className="absolute inset-x-0 top-10 z-30 max-h-48 overflow-y-auto border border-[#e2e2e2] bg-white shadow-[0_10px_24px_rgba(0,0,0,0.1)]">
<div className="absolute inset-x-0 top-12 z-30 max-h-48 overflow-y-auto border border-[#e2e2e2] bg-white shadow-[0_10px_24px_rgba(0,0,0,0.1)]">
{items.map((item) => (
<button
key={item.id}
@ -1582,7 +1863,7 @@ function FixedReviewerPicker({
setSearch('')
setItems([])
}}
className="block w-full border-b border-[#eeeeee] px-3 py-2 text-left text-[12px] hover:bg-[#f7f7f7]"
className="block min-h-11 w-full border-b border-[#eeeeee] px-3 py-2 text-left text-[12px] hover:bg-[#f7f7f7]"
>
<strong>{item.displayName}</strong>{item.departmentName ? ` · ${item.departmentName}` : ''}
</button>
@ -1614,7 +1895,7 @@ function AdminField({
value={value}
disabled={disabled}
onChange={(event) => onChange(event.target.value)}
className="h-10 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 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

@ -0,0 +1,123 @@
/** @jest-environment jsdom */
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import {
PerformanceSurveyAdminPeople,
type PerformanceSurveyAdminRequest,
} from './PerformanceSurveyAdminPeople'
const groups = [{
id: 'group-1',
name: '品牌设计师',
status: 'ready' as const,
memberCount: 10,
}]
function renderPeople(request: PerformanceSurveyAdminRequest) {
const onError = jest.fn()
const onSuccess = jest.fn()
render(
<PerformanceSurveyAdminPeople
month="2026-07"
groups={groups}
request={request}
onError={onError}
onSuccess={onSuccess}
/>,
)
return { onError, onSuccess }
}
describe('PerformanceSurveyAdminPeople', () => {
test('使用每页 50 人,并同时提供桌面表格和移动端卡片', async () => {
const request = jest.fn(async () => ({
items: [{
id: 'employee-1',
employeeId: 'employee-1',
displayName: '张三',
departmentPath: '集团/品牌中心',
positionTitle: '设计师',
participation: 'unassigned',
}],
total: 1,
})) as unknown as jest.MockedFunction<PerformanceSurveyAdminRequest>
renderPeople(request)
expect(screen.getByRole('status')).toHaveTextContent('正在加载人员列表')
await waitFor(() => expect(within(screen.getByTestId('people-mobile-cards')).getByText('张三')).toBeInTheDocument())
expect(screen.getByTestId('people-desktop-table')).toBeInTheDocument()
expect(screen.getByTestId('people-mobile-cards')).toBeInTheDocument()
expect(request).toHaveBeenCalledWith(expect.stringContaining('pageSize=50'))
expect(screen.getByRole('status')).toHaveTextContent('人员列表已更新,共 1 人')
})
test('选择跨页保留,并在固定批量栏一次提交全部人员', async () => {
const request = jest.fn(async (path: string, _options?: RequestInit) => {
if (path.startsWith('/admin/position-assignments?')) {
const page = new URL(path, 'https://example.test').searchParams.get('page')
return {
items: page === '2'
? [{
id: 'employee-2',
employeeId: 'employee-2',
displayName: '李四',
departmentName: '摄影中心',
positionTitle: '摄影师',
participation: 'unassigned',
}]
: [{
id: 'employee-1',
employeeId: 'employee-1',
displayName: '张三',
departmentName: '品牌中心',
positionTitle: '设计师',
participation: 'unassigned',
}],
total: 51,
}
}
return {}
}) as unknown as jest.MockedFunction<PerformanceSurveyAdminRequest>
const { onSuccess } = renderPeople(request)
await waitFor(() => expect(screen.getByLabelText('选择 张三')).toBeInTheDocument())
fireEvent.click(screen.getByLabelText('选择 张三'))
expect(screen.getByRole('region', { name: '批量分配所选人员' })).toHaveTextContent('已选择 1 人')
fireEvent.click(screen.getByRole('button', { name: '下一页' }))
await waitFor(() => expect(screen.getByLabelText('选择 李四')).toBeInTheDocument())
fireEvent.click(screen.getByLabelText('选择 李四'))
expect(screen.getByRole('region', { name: '批量分配所选人员' })).toHaveTextContent('已选择 2 人')
fireEvent.change(screen.getByLabelText('批量分配操作'), { target: { value: 'group-1' } })
fireEvent.change(screen.getByLabelText('本次调整原因'), { target: { value: '组织调整' } })
fireEvent.click(screen.getByRole('button', { name: '应用分配' }))
await waitFor(() => {
const call = request.mock.calls.find(([path, options]) => (
path === '/admin/position-assignments' && options?.method === 'POST'
))
expect(call).toBeDefined()
expect(JSON.parse(String(call?.[1]?.body))).toEqual(expect.objectContaining({
employeeIds: ['employee-1', 'employee-2'],
positionGroupId: 'group-1',
reason: '组织调整',
}))
})
expect(onSuccess).toHaveBeenCalledWith('已为 2 人分配岗位')
})
test('网络失败显示中文可恢复提示', async () => {
const request = jest.fn()
.mockRejectedValueOnce(new Error('Failed to fetch'))
.mockResolvedValueOnce({ items: [], total: 0 }) as unknown as jest.MockedFunction<PerformanceSurveyAdminRequest>
renderPeople(request)
expect(await screen.findByRole('alert')).toHaveTextContent('暂时无法加载人员,请检查网络后重试。')
expect(screen.queryByText('Failed to fetch')).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: '重新加载' }))
await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('人员列表已更新,共 0 人'))
})
})

View File

@ -100,6 +100,12 @@ function participationLabel(row: AssignmentRow) {
return '待分配'
}
function readTechnicalError(error: unknown) {
if (!(error instanceof Error)) return null
const detail = error.message.trim()
return detail && detail !== 'Failed to fetch' ? detail : null
}
export function PerformanceSurveyAdminPeople({
month,
groups,
@ -117,15 +123,16 @@ export function PerformanceSurveyAdminPeople({
const [statusFilter, setStatusFilter] = useState<'all' | 'assigned' | 'unassigned' | 'excluded'>('all')
const [rows, setRows] = useState<AssignmentRow[]>([])
const [loading, setLoading] = useState(true)
const [loadError, setLoadError] = useState<string | null>(null)
const [loadError, setLoadError] = useState<{ message: string; technicalDetail: string | null } | null>(null)
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
const selectedRowsRef = useRef<Map<string, AssignmentRow>>(new Map())
const [assignmentValue, setAssignmentValue] = useState('')
const [reason, setReason] = useState('')
const [saving, setSaving] = useState(false)
const [page, setPage] = useState(1)
const [total, setTotal] = useState(0)
const requestSequence = useRef(0)
const pageSize = 200
const pageSize = 50
const load = useCallback(async () => {
const sequence = requestSequence.current + 1
@ -144,11 +151,13 @@ export function PerformanceSurveyAdminPeople({
const nextRows = normalizeAssignmentRows(payload)
setRows(nextRows)
setTotal(readAssignmentTotal(payload, nextRows))
setSelectedIds(new Set())
} catch (error) {
if (requestSequence.current !== sequence) return
setRows([])
setLoadError(error instanceof Error ? error.message : '人员分配加载失败')
setLoadError({
message: '暂时无法加载人员,请检查网络后重试。',
technicalDetail: readTechnicalError(error),
})
} finally {
if (requestSequence.current === sequence) setLoading(false)
}
@ -156,6 +165,8 @@ export function PerformanceSurveyAdminPeople({
useEffect(() => {
setPage(1)
setSelectedIds(new Set())
selectedRowsRef.current.clear()
}, [keyword, month, statusFilter])
useEffect(() => {
@ -170,20 +181,41 @@ export function PerformanceSurveyAdminPeople({
const toggleAll = () => {
setSelectedIds((current) => {
if (allVisibleSelected) return new Set()
return new Set(Array.from(current).concat(visibleIds))
const next = new Set(current)
if (allVisibleSelected) {
visibleIds.forEach((id) => {
next.delete(id)
selectedRowsRef.current.delete(id)
})
return next
}
rows.forEach((row) => {
next.add(row.id)
selectedRowsRef.current.set(row.id, row)
})
return next
})
}
const toggleRow = (id: string) => {
const toggleRow = (row: AssignmentRow) => {
setSelectedIds((current) => {
const next = new Set(current)
if (next.has(id)) next.delete(id)
else next.add(id)
if (next.has(row.id)) {
next.delete(row.id)
selectedRowsRef.current.delete(row.id)
} else {
next.add(row.id)
selectedRowsRef.current.set(row.id, row)
}
return next
})
}
const clearSelection = () => {
selectedRowsRef.current.clear()
setSelectedIds(new Set())
}
const applyAssignment = async () => {
if (selectedIds.size === 0) {
onError('请先选择人员')
@ -201,7 +233,7 @@ export function PerformanceSurveyAdminPeople({
setSaving(true)
onError(null)
try {
const selectedRows = rows.filter((row) => selectedIds.has(row.id))
const selectedRows = Array.from(selectedRowsRef.current.values())
const employeeIds = selectedRows.map((row) => row.employeeId || row.id)
if (assignmentValue === '__automatic__') {
const manualRows = selectedRows.filter((row) => row.manualAssignmentId)
@ -214,6 +246,7 @@ export function PerformanceSurveyAdminPeople({
)))
onSuccess(`已将 ${manualRows.length} 人恢复为按岗位规则自动匹配`)
setReason('')
clearSelection()
await load()
return
}
@ -242,9 +275,15 @@ export function PerformanceSurveyAdminPeople({
: `已为 ${employeeIds.length} 人分配岗位`,
)
setReason('')
clearSelection()
await load()
} catch (error) {
onError(error instanceof Error ? error.message : '批量分配失败')
const technicalDetail = readTechnicalError(error)
onError(
technicalDetail
? `人员分配未能保存,请稍后重试。技术信息:${technicalDetail}`
: '人员分配未能保存,请检查网络后重试。',
)
} finally {
setSaving(false)
}
@ -296,22 +335,49 @@ export function PerformanceSurveyAdminPeople({
{loadError && (
<div role="alert" className="my-4 flex flex-wrap items-center justify-between gap-3 border border-[#f0b8b8] bg-[#fff8f7] px-4 py-3 text-[13px] text-[#93000a]">
<span>{loadError}</span>
<button type="button" onClick={() => void load()} className="min-h-9 px-2 font-bold underline">重试</button>
<div>
<p className="font-semibold">{loadError.message}</p>
{loadError.technicalDetail && (
<details className="mt-1 text-[12px] text-[#5f5e5e]">
<summary className="cursor-pointer">查看技术信息</summary>
<p className="mt-1 break-all">{loadError.technicalDetail}</p>
</details>
)}
</div>
<button type="button" onClick={() => void load()} className="min-h-11 px-3 font-bold underline">重新加载</button>
</div>
)}
<div className="mt-4 overflow-x-auto border border-[#c2c6d8]">
<div role="status" aria-live="polite" className="sr-only">
{loading ? '正在加载人员列表' : `人员列表已更新,共 ${total} 人`}
</div>
<div className="mt-4 flex min-h-11 items-center justify-between gap-3 border border-[#c2c6d8] bg-[#f8f8f8] px-3 py-2 text-[12px] font-semibold text-[#5f5e5e]">
<span>本页 {rows.length} 人{selectedIds.size > 0 ? ` · 已跨页选择 ${selectedIds.size} 人` : ''}</span>
<button
type="button"
disabled={rows.length === 0 || loading}
onClick={toggleAll}
className="min-h-11 rounded px-3 font-bold text-[#0050cb] hover:bg-[#eef5ff] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0050cb] disabled:opacity-40"
>
{allVisibleSelected ? '取消选择本页' : '选择本页全部'}
</button>
</div>
<div className="hidden overflow-x-auto border-x border-b border-[#c2c6d8] md:block" data-testid="people-desktop-table">
<table className="w-full min-w-[760px] border-collapse text-left">
<thead>
<tr className="border-b border-[#c2c6d8] bg-[#f4f3f3] text-[12px] font-bold text-[#5f5e5e]">
<th scope="col" className="w-12 px-3 py-3">
<input
type="checkbox"
checked={allVisibleSelected}
onChange={toggleAll}
aria-label="选择当前列表全部人员"
/>
<label className="inline-flex min-h-11 min-w-11 cursor-pointer items-center justify-center" title="选择当前列表全部人员">
<input
type="checkbox"
className="h-5 w-5"
checked={allVisibleSelected}
onChange={toggleAll}
aria-label="选择当前列表全部人员"
/>
</label>
</th>
<th scope="col" className="px-3 py-3">人员</th>
<th scope="col" className="px-3 py-3">部门</th>
@ -327,13 +393,16 @@ export function PerformanceSurveyAdminPeople({
)}
{!loading && rows.map((row) => (
<tr key={row.id} className={selectedIds.has(row.id) ? 'bg-[#f4f7ff]' : 'bg-white hover:bg-[#fcfcfc]'}>
<td className="px-3 py-3">
<input
type="checkbox"
checked={selectedIds.has(row.id)}
onChange={() => toggleRow(row.id)}
aria-label={`选择 ${row.displayName}`}
/>
<td className="px-3 py-1">
<label className="inline-flex min-h-11 min-w-11 cursor-pointer items-center justify-center" title={`选择 ${row.displayName}`}>
<input
type="checkbox"
className="h-5 w-5"
checked={selectedIds.has(row.id)}
onChange={() => toggleRow(row)}
aria-label={`在表格中选择 ${row.displayName}`}
/>
</label>
</td>
<td className="px-3 py-3 text-[13px] font-bold text-[#1a1c1c]">{row.displayName}</td>
<td className="px-3 py-3 text-[13px] text-[#5f5e5e]">{row.departmentPath || row.departmentName || '-'}</td>
@ -362,6 +431,56 @@ export function PerformanceSurveyAdminPeople({
</table>
</div>
<div className="divide-y divide-[#e2e2e2] border-x border-b border-[#c2c6d8] bg-white md:hidden" data-testid="people-mobile-cards">
{loading && (
<div className="px-4 py-10 text-center text-[13px] font-semibold text-[#5f5e5e]">
人员加载中...
</div>
)}
{!loading && rows.map((row) => (
<label
key={row.id}
className={`flex min-h-20 cursor-pointer gap-3 p-3 ${
selectedIds.has(row.id) ? 'bg-[#f4f7ff]' : 'bg-white active:bg-[#f4f3f3]'
}`}
>
<span className="inline-flex min-h-11 min-w-11 items-start justify-center pt-1">
<input
type="checkbox"
className="h-5 w-5"
checked={selectedIds.has(row.id)}
onChange={() => toggleRow(row)}
aria-label={`选择 ${row.displayName}`}
/>
</span>
<span className="min-w-0 flex-1">
<span className="flex flex-wrap items-start justify-between gap-2">
<span className="text-[14px] font-bold text-[#1a1c1c]">{row.displayName}</span>
<span className={`inline-flex rounded px-2 py-1 text-[12px] font-semibold ${
row.participation === 'excluded'
? 'bg-[#f4f3f3] text-[#5f5e5e]'
: row.positionGroupName
? 'bg-[#eef5ff] text-[#0050cb]'
: 'bg-[#fff4df] text-[#8a5700]'
}`}>
{participationLabel(row)}
</span>
</span>
<span className="mt-1 block break-words text-[12px] leading-5 text-[#5f5e5e]">
{row.departmentPath || row.departmentName || '部门未填写'}
<span aria-hidden="true"> · </span>
{row.positionTitle || '职位未填写'}
</span>
</span>
</label>
))}
{!loading && rows.length === 0 && !loadError && (
<div className="px-4 py-10 text-center text-[13px] font-semibold text-[#5f5e5e]">
当前条件下没有人员
</div>
)}
</div>
<div className="flex flex-wrap items-center justify-between gap-3 border-x border-b border-[#c2c6d8] px-3 py-3 text-[12px] font-semibold text-[#5f5e5e]">
<span>
共 {total} 人
@ -372,7 +491,7 @@ export function PerformanceSurveyAdminPeople({
type="button"
disabled={page <= 1 || loading}
onClick={() => setPage((current) => Math.max(1, current - 1))}
className="min-h-9 rounded border border-[#c2c6d8] px-3 font-bold text-[#1a1c1c] disabled:opacity-40"
className="min-h-11 rounded border border-[#c2c6d8] px-3 font-bold text-[#1a1c1c] disabled:opacity-40"
>
上一页
</button>
@ -381,50 +500,66 @@ export function PerformanceSurveyAdminPeople({
type="button"
disabled={page * pageSize >= total || loading}
onClick={() => setPage((current) => current + 1)}
className="min-h-9 rounded border border-[#c2c6d8] px-3 font-bold text-[#1a1c1c] disabled:opacity-40"
className="min-h-11 rounded border border-[#c2c6d8] px-3 font-bold text-[#1a1c1c] disabled:opacity-40"
>
下一页
</button>
</div>
</div>
<div className="sticky bottom-[68px] z-20 -mx-4 mt-4 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:flex sm:items-center sm:justify-between sm:shadow-none">
<div className="mb-2 text-[12px] font-semibold text-[#5f5e5e] sm:mb-0">
已选择 {selectedIds.size} 人
</div>
<div className="grid grid-cols-[minmax(0,1fr)_auto] gap-2 sm:flex">
<div className="grid min-w-0 gap-2 sm:grid-cols-[220px_240px]">
<select
aria-label="批量分配操作"
value={assignmentValue}
onChange={(event) => setAssignmentValue(event.target.value)}
className="h-11 min-w-0 rounded border border-[#c2c6d8] bg-white px-3 text-[13px] font-semibold text-[#1a1c1c] outline-none focus:border-[#0050cb]"
>
<option value="">选择分配结果</option>
{groups.filter((group) => group.status !== 'disabled').map((group) => (
<option key={group.id} value={group.id}>{group.name}</option>
))}
<option value="__excluded__">不参与考核</option>
<option value="__automatic__">恢复自动匹配</option>
</select>
<input
aria-label="本次调整原因"
value={reason}
onChange={(event) => setReason(event.target.value)}
placeholder="本次调整原因(必填)"
className="h-11 min-w-0 rounded border border-[#c2c6d8] px-3 text-[13px] text-[#1a1c1c] outline-none focus:border-[#0050cb]"
/>
</div>
<button
type="button"
disabled={saving || selectedIds.size === 0}
onClick={() => void applyAssignment()}
className="min-h-11 rounded bg-[#0050cb] px-4 text-[13px] font-bold text-white hover:bg-[#003fa4] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0050cb] focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
{selectedIds.size > 0 && (
<>
<div aria-hidden="true" className="h-[220px] sm:h-24" />
<div
role="region"
aria-label="批量分配所选人员"
className="fixed bottom-[72px] left-3 right-3 z-40 border border-[#c2c6d8] bg-white/95 p-3 shadow-[0_-6px_20px_rgba(0,0,0,0.14)] backdrop-blur sm:bottom-4 sm:left-1/2 sm:right-auto sm:w-[min(960px,calc(100vw-2rem))] sm:-translate-x-1/2 sm:flex sm:items-end sm:justify-between sm:gap-3"
>
{saving ? '处理中...' : '应用分配'}
</button>
</div>
</div>
<div className="mb-2 flex min-h-11 items-center justify-between gap-3 text-[12px] font-semibold text-[#5f5e5e] sm:mb-0 sm:min-w-[128px]">
<span>已选择 {selectedIds.size} 人</span>
<button
type="button"
onClick={clearSelection}
className="min-h-11 rounded px-3 font-bold text-[#0050cb] hover:bg-[#eef5ff] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0050cb]"
>
清空选择
</button>
</div>
<div className="grid gap-2 sm:flex sm:min-w-0 sm:flex-1">
<div className="grid min-w-0 gap-2 sm:flex sm:flex-1">
<select
aria-label="批量分配操作"
value={assignmentValue}
onChange={(event) => setAssignmentValue(event.target.value)}
className="h-11 min-w-0 rounded border border-[#c2c6d8] bg-white px-3 text-[13px] font-semibold text-[#1a1c1c] outline-none focus:border-[#0050cb] sm:w-[220px]"
>
<option value="">选择分配结果</option>
{groups.filter((group) => group.status !== 'disabled').map((group) => (
<option key={group.id} value={group.id}>{group.name}</option>
))}
<option value="__excluded__">不参与考核</option>
<option value="__automatic__">恢复自动匹配</option>
</select>
<input
aria-label="本次调整原因"
value={reason}
onChange={(event) => setReason(event.target.value)}
placeholder="本次调整原因(必填)"
className="h-11 min-w-0 rounded border border-[#c2c6d8] px-3 text-[13px] text-[#1a1c1c] outline-none focus:border-[#0050cb] sm:flex-1"
/>
</div>
<button
type="button"
disabled={saving || selectedIds.size === 0}
onClick={() => void applyAssignment()}
className="min-h-11 rounded bg-[#0050cb] px-4 text-[13px] font-bold text-white hover:bg-[#003fa4] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0050cb] focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 sm:shrink-0"
>
{saving ? '处理中...' : '应用分配'}
</button>
</div>
</div>
</>
)}
</section>
)
}

View File

@ -469,19 +469,25 @@ function mergeEmployeesById(...groups: Employee[][]) {
async function apiRequest<T>(path: string, options?: RequestInit): Promise<T> {
const dingtalkToken = getStoredDingtalkPerformanceToken()
const response = await fetch(`${API_BASE}${path}`, {
...options,
headers: {
...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),
...(dingtalkToken
? {
Authorization: `Bearer ${dingtalkToken}`,
[DINGTALK_PERFORMANCE_SESSION_HEADER]: dingtalkToken,
}
: {}),
...(options?.headers || {}),
},
})
let response: Response
try {
response = await fetch(`${API_BASE}${path}`, {
...options,
headers: {
...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),
...(dingtalkToken
? {
Authorization: `Bearer ${dingtalkToken}`,
[DINGTALK_PERFORMANCE_SESSION_HEADER]: dingtalkToken,
}
: {}),
...(options?.headers || {}),
},
})
} catch (error) {
if (error instanceof DOMException && error.name === 'AbortError') throw error
throw new Error('网络连接失败,请检查网络后重试')
}
const contentType = response.headers.get('content-type') || ''
const payload = contentType.includes('application/json') ? await response.json() : await response.text()
@ -2788,6 +2794,8 @@ function ManagePanel({
const surveys = useApi<any>('/surveys', [])
const [message, setMessage] = useState<string | null>(null)
const requestedWorkspace = String(searchParams.get('adminWorkspace') || '').trim() as PerformanceSurveyAdminWorkspace
const requestedAdminMonth = String(searchParams.get('adminMonth') || '').trim()
const adminMonth = /^\d{4}-\d{2}$/.test(requestedAdminMonth) ? requestedAdminMonth : getCurrentMonthValue()
const initialWorkspace = isSystemAdmin && PERFORMANCE_SURVEY_ADMIN_WORKSPACES.includes(requestedWorkspace)
? requestedWorkspace
: isSystemAdmin ? 'overview' : 'launch'
@ -2842,6 +2850,15 @@ function ManagePanel({
router.replace(`/performance-survey?${query.toString()}`, { scroll: false })
}
const selectAdminMonth = (nextMonth: string) => {
if (!/^\d{4}-\d{2}$/.test(nextMonth) || nextMonth === adminMonth) return
const query = new URLSearchParams(searchParams.toString())
query.set('tab', 'manage')
query.set('adminMonth', nextMonth)
query.delete('prefillMonth')
router.replace(`/performance-survey?${query.toString()}`, { scroll: false })
}
return (
<div className="grid gap-4">
{isSystemAdmin && (
@ -2851,11 +2868,11 @@ function ManagePanel({
>
{([
['overview', '管理概览'],
['launch', '发起调研'],
['positions', '岗位'],
['people', '人员分配'],
['templates', '模板'],
['plans', '月度方案'],
['launch', '发起调研'],
['operations', '运行维护'],
] as const).map(([id, label]) => (
<button
@ -2863,7 +2880,7 @@ function ManagePanel({
type="button"
onClick={() => selectWorkspace(id)}
aria-current={workspace === id ? 'page' : undefined}
className={`h-9 shrink-0 rounded px-3 text-[12px] font-bold transition-colors ${
className={`min-h-11 shrink-0 rounded px-3 text-[12px] font-bold transition-colors ${
workspace === id
? 'bg-[#1a1c1c] text-white'
: 'text-[#5f5e5e] hover:bg-[#f4f4f4] hover:text-[#1a1c1c]'
@ -2879,6 +2896,9 @@ function ManagePanel({
departments={departments.data || []}
currentEmployee={currentEmployee}
canSelectAnyPosition={canSelectAnyPosition}
defaultMonth={adminMonth}
onMonthChange={selectAdminMonth}
onAdminNavigate={isSystemAdmin ? selectWorkspace : undefined}
onCreated={async () => {
setMessage('已发布调研')
await surveys.refresh()
@ -2899,6 +2919,9 @@ function ManagePanel({
<PerformanceSurveyAdminConfig
mode={workspace}
request={apiRequest}
month={adminMonth}
onMonthChange={selectAdminMonth}
onNavigate={(nextWorkspace) => selectWorkspace(nextWorkspace)}
onDirtyChange={setConfigurationDirty}
/>
)}
@ -2967,11 +2990,17 @@ function CreateSurveyForm({
departments,
currentEmployee,
canSelectAnyPosition,
defaultMonth,
onMonthChange,
onAdminNavigate,
onCreated,
}: {
departments: DepartmentOption[]
currentEmployee: Employee | null
canSelectAnyPosition: boolean
defaultMonth?: string
onMonthChange?: (month: string) => void
onAdminNavigate?: (workspace: PerformanceSurveyAdminWorkspace) => void
onCreated: () => Promise<void>
}) {
const router = useRouter()
@ -2982,7 +3011,7 @@ function CreateSurveyForm({
const [title, setTitle] = useState('')
const [description, setDescription] = useState('')
const [templateOptionKey, setTemplateOptionKey] = useState(prefillTemplate)
const [assessmentMonth, setAssessmentMonth] = useState(prefillMonth || getCurrentMonthValue())
const [assessmentMonth, setAssessmentMonth] = useState(prefillMonth || defaultMonth || getCurrentMonthValue())
const [positionGroupCode, setPositionGroupCode] = useState(prefillPositionGroup)
const [deadlineAt, setDeadlineAt] = useState('')
const openNow = true
@ -3013,13 +3042,14 @@ function CreateSurveyForm({
useEffect(() => {
if (prefillMonth && /^\d{4}-\d{2}$/.test(prefillMonth)) setAssessmentMonth(prefillMonth)
else if (defaultMonth && /^\d{4}-\d{2}$/.test(defaultMonth)) setAssessmentMonth(defaultMonth)
if (prefillPositionGroup) setPositionGroupCode(prefillPositionGroup)
if (prefillTemplate) {
const matched = templates.find((template) => template.templateOptionKey === prefillTemplate)
|| templates.find((template) => template.code === prefillTemplate)
if (matched) setTemplateOptionKey(matched.templateOptionKey || matched.code)
}
}, [prefillMonth, prefillPositionGroup, prefillTemplate, templates])
}, [defaultMonth, prefillMonth, prefillPositionGroup, prefillTemplate, templates])
const selectedTemplate = templateOptionKey || templates[0]?.templateOptionKey || templates[0]?.code || ''
const selectedTemplateInfo = templates.find((template) => (template.templateOptionKey || template.code) === selectedTemplate)
@ -3231,7 +3261,15 @@ function CreateSurveyForm({
<div>
<div className="border border-[#eeeeee] bg-white p-4 sm:p-6">
<div className="space-y-6">
<TextInput label="考核月份" value={assessmentMonth} onChange={setAssessmentMonth} type="month" />
<TextInput
label="考核月份"
value={assessmentMonth}
onChange={(value) => {
setAssessmentMonth(value)
onMonthChange?.(value)
}}
type="month"
/>
<label className="grid gap-2 text-sm">
<span className="text-[12px] font-semibold tracking-[0.05em] text-[#5f5e5e]">考核岗位</span>
<select
@ -3241,7 +3279,7 @@ function CreateSurveyForm({
setTemplateOptionKey('')
setTargetEmployees([])
}}
className="h-10 rounded border border-[#eeeeee] bg-white px-3 text-[14px] font-semibold text-[#1a1c1c] outline-none transition-colors focus:border-[#0050cb]"
className="h-11 rounded border border-[#eeeeee] bg-white px-3 text-[14px] font-semibold text-[#1a1c1c] outline-none transition-colors focus:border-[#0050cb]"
>
<option value="">选择考核岗位</option>
{availablePositionGroups.map((group: any) => (
@ -3261,6 +3299,36 @@ function CreateSurveyForm({
</div>
)}
</label>
{onAdminNavigate && positionGroupsState.data && (
availablePositionGroups.every((group: any) => group.status !== 'ready')
|| (selectedPositionGroupCode && !templatesState.loading && templates.length === 0)
) && (
<div className="border border-[#e4b86a] bg-[#fffaf0] px-3 py-3 text-[12px] leading-5 text-[#6f4700]">
<div className="font-bold">
{availablePositionGroups.every((group: any) => group.status !== 'ready')
? `${assessmentMonth} 暂无可发起的岗位`
: '所选岗位还没有可用考核模板'}
</div>
<p className="mt-1">请先补齐岗位匹配、人员归属、模板和月度方案,再回来发起调研。</p>
<div className="mt-3 flex flex-wrap gap-2">
{([
['positions', '检查岗位'],
['people', '检查人员'],
['templates', '检查模板'],
['plans', '检查月度方案'],
] as const).map(([target, label]) => (
<button
key={target}
type="button"
onClick={() => onAdminNavigate(target)}
className="min-h-11 rounded border border-[#6f4700] px-3 text-[11px] font-bold hover:bg-[#6f4700] hover:text-white"
>
{label}
</button>
))}
</div>
</div>
)}
<TextInput label="截止时间(可选)" value={deadlineAt} onChange={setDeadlineAt} type="datetime-local" />
<label className="grid gap-2 text-sm">
<span className="text-[12px] font-semibold tracking-[0.05em] text-[#5f5e5e]">考评模板</span>
@ -3268,7 +3336,7 @@ function CreateSurveyForm({
value={selectedTemplate}
onChange={(event) => setTemplateOptionKey(event.target.value)}
disabled={!selectedPositionGroupCode || templatesState.loading}
className="h-10 rounded border border-[#eeeeee] bg-white px-3 text-[14px] font-semibold text-[#1a1c1c] outline-none transition-colors focus:border-[#0050cb]"
className="h-11 rounded border border-[#eeeeee] bg-white px-3 text-[14px] font-semibold text-[#1a1c1c] outline-none transition-colors focus:border-[#0050cb]"
>
{templates.length === 0 && <option value="">该岗位暂无可用考核项</option>}
{templates.map((template) => (
@ -4128,35 +4196,118 @@ function AdminActions({
onMessage: (message: string | null) => void
}) {
const [busy, setBusy] = useState<string | null>(null)
const [preview, setPreview] = useState<any | null>(null)
const [error, setError] = useState<string | null>(null)
const run = async (key: string, path: string, success: string) => {
setBusy(key)
setError(null)
onMessage(null)
try {
const data = await apiRequest<any>(path, { method: 'POST', body: JSON.stringify({}) })
onMessage(`${success}${data?.upserted != null ? `:${data.upserted} 人` : ''}`)
if (key === 'sync') setPreview(null)
} catch (error) {
onMessage(error instanceof Error ? error.message : '操作失败')
setError(error instanceof Error ? error.message : '操作失败')
} finally {
setBusy(null)
}
}
const previewSync = async () => {
setBusy('preview')
setError(null)
onMessage(null)
try {
setPreview(await apiRequest<any>('/admin/sync-employees/preview', {
method: 'POST',
body: JSON.stringify({ limit: 3000 }),
}))
} catch (actionError) {
setError(actionError instanceof Error ? actionError.message : '人员同步影响检查失败')
} finally {
setBusy(null)
}
}
return (
<section className="border border-[#e2e2e2] bg-white px-4 py-4">
<h3 className="text-[16px] font-bold text-[#1a1c1c]">数据维护</h3>
<p className="mt-1 text-[12px] font-medium text-[#727687]">人员同步会更新本地花名册,不会修改历史调研。</p>
<section className="border border-[#e2e2e2] bg-white px-4 py-4" aria-labelledby="employee-sync-title">
<h3 id="employee-sync-title" className="text-[16px] font-bold text-[#1a1c1c]">数据维护</h3>
<p className="mt-1 text-[12px] font-medium leading-5 text-[#727687]">
先只读检查变更范围,确认后才会更新本地人员档案;历史调研不会被修改。
</p>
{error && (
<div role="alert" className="mt-3 border border-[#ffdad6] bg-[#fff6f4] px-3 py-2 text-[12px] font-semibold leading-5 text-[#93000a]">
{error}
</div>
)}
{preview && (
<section aria-label="人员同步影响预览" className="mt-4 border border-[#c2c6d8]">
<div className="border-b border-[#e2e2e2] bg-[#f7f7f7] px-3 py-3">
<div className="text-[13px] font-bold text-[#1a1c1c]">同步影响预览</div>
<div className="mt-1 text-[11px] leading-5 text-[#5f5e5e]">
数据来源:{preview.source?.name || '上游花名册'}
{preview.last?.latestLocalProfileSyncedAt
? ` · 最近一条本地档案更新于 ${new Date(preview.last.latestLocalProfileSyncedAt).toLocaleString('zh-CN')}`
: ' · 暂无可用的历史同步时间'}
</div>
</div>
<dl className="grid grid-cols-2 divide-x divide-y divide-[#eeeeee] sm:grid-cols-4">
{[
['预计新增', preview.counts?.created ?? 0],
['预计更新', preview.counts?.updated ?? 0],
['无需变化', preview.counts?.unchanged ?? 0],
['资料兜底', preview.counts?.fallback ?? 0],
].map(([label, value]) => (
<div key={String(label)} className="px-3 py-3">
<dt className="text-[11px] font-semibold text-[#727687]">{label}</dt>
<dd className="mt-1 text-[18px] font-bold text-[#1a1c1c]">{String(value)} 人</dd>
</div>
))}
</dl>
<div className="px-3 py-3 text-[11px] leading-5 text-[#5f5e5e]">
<p>
本次检查 {preview.now?.scannedAccounts ?? 0}/{preview.now?.totalAccounts ?? 0} 个素材库账号,
正式同步预计写入 {preview.counts?.plannedProfileWrites ?? 0} 份人员档案。
</p>
{preview.counts?.fallback > 0 && (
<p className="mt-1 font-semibold text-[#7a4b00]">
有 {preview.counts.fallback} 人未匹配上游花名册,将暂用素材库账号资料;建议同步后到“人员分配”确认。
</p>
)}
<p className="mt-1">当前规则不会根据“上游未返回”自动停用人员,因此停用人数不做推测。</p>
</div>
<div className="flex flex-wrap justify-end gap-2 border-t border-[#e2e2e2] px-3 py-3">
<button
type="button"
disabled={busy !== null}
onClick={() => setPreview(null)}
className="min-h-11 rounded border border-[#c9c9c9] px-3 text-[12px] font-bold text-[#1a1c1c] disabled:opacity-50"
>
取消
</button>
<button
type="button"
disabled={busy !== null}
onClick={() => void run('sync', '/admin/sync-employees', '人员档案已同步')}
className="min-h-11 rounded bg-[#1a1c1c] px-4 text-[12px] font-bold text-white disabled:opacity-50"
>
{busy === 'sync' ? '正在同步...' : '确认正式同步'}
</button>
</div>
</section>
)}
<div className="mt-4 grid grid-cols-2 gap-2">
<button
disabled={busy !== null}
onClick={() => run('sync', '/admin/sync-employees', '人员档案已同步')}
className="min-h-10 rounded border border-[#c9c9c9] px-3 py-2 text-sm font-bold text-[#1a1c1c] hover:border-[#1a1c1c] hover:bg-[#f7f7f7] disabled:opacity-50"
onClick={() => void previewSync()}
className="min-h-11 rounded border border-[#c9c9c9] px-3 py-2 text-sm font-bold text-[#1a1c1c] hover:border-[#1a1c1c] hover:bg-[#f7f7f7] disabled:opacity-50"
>
{busy === 'sync' ? '同步中' : '人员同步'}
{busy === 'preview' ? '检查中...' : preview ? '重新检查影响' : '检查同步影响'}
</button>
<a
href="/api/performance-survey/admin/export"
className="flex min-h-10 items-center justify-center rounded border border-[#c9c9c9] px-3 py-2 text-center text-sm font-bold text-[#1a1c1c] hover:border-[#1a1c1c] hover:bg-[#f7f7f7]"
className="flex min-h-11 items-center justify-center rounded border border-[#c9c9c9] px-3 py-2 text-center text-sm font-bold text-[#1a1c1c] hover:border-[#1a1c1c] hover:bg-[#f7f7f7]"
>
导出数据
</a>
@ -4183,10 +4334,11 @@ function NotificationList({
statusState: ApiState<any> & { refresh: () => Promise<void> }
}) {
const [busyId, setBusyId] = useState<string | null>(null)
const [showAll, setShowAll] = useState(false)
const workNotice = statusState.data?.notificationChannel || statusState.data?.workNotice
const counts = statusState.data?.counts || {}
const records = state.data || []
const visibleRecords = records.slice(0, 6)
const visibleRecords = showAll ? records : records.slice(0, 6)
const total = records.length
const sentCount = Number(counts.sent || counts.succeeded || 0)
const failedCount = Number(counts.exhausted || counts.skipped || counts.failed || 0)
@ -4212,7 +4364,7 @@ function NotificationList({
onClick={async () => {
await Promise.all([state.refresh(), statusState.refresh()])
}}
className="min-h-9 rounded px-3 py-1.5 text-sm font-bold text-[#0050cb] hover:bg-[#f4f7ff]"
className="min-h-11 rounded px-3 py-1.5 text-sm font-bold text-[#0050cb] hover:bg-[#f4f7ff]"
>
刷新
</button>
@ -4229,8 +4381,8 @@ function NotificationList({
</div>
)}
<div className="mt-3 divide-y divide-[#eef1f6] dark:divide-gray-800">
{state.loading && <div className="text-sm text-[#727687]">加载中...</div>}
{state.error && <div className="text-sm font-semibold text-[#93000a]">{state.error}</div>}
{state.loading && <div role="status" aria-live="polite" className="text-sm text-[#727687]">加载中...</div>}
{state.error && <div role="alert" className="text-sm font-semibold text-[#93000a]">{state.error}</div>}
{records.length === 0 && !state.loading && <div className="py-3 text-sm text-[#727687]">暂无消息记录</div>}
{visibleRecords.map((item) => {
const isRetryable = ['retrying', 'exhausted', 'skipped'].includes(item.status)
@ -4255,7 +4407,7 @@ function NotificationList({
<button
disabled={busyId === item.id}
onClick={() => retry(item.id)}
className="rounded border border-[#c9c9c9] px-2 py-1 text-xs font-bold text-[#1a1c1c] hover:border-[#1a1c1c] hover:bg-[#f7f7f7] disabled:opacity-50"
className="min-h-11 rounded border border-[#c9c9c9] px-3 py-1 text-xs font-bold text-[#1a1c1c] hover:border-[#1a1c1c] hover:bg-[#f7f7f7] disabled:opacity-50"
>
补发
</button>
@ -4266,6 +4418,15 @@ function NotificationList({
)
})}
</div>
{records.length > 6 && (
<button
type="button"
onClick={() => setShowAll((current) => !current)}
className="mt-3 min-h-11 w-full rounded border border-[#c9c9c9] px-3 text-[12px] font-bold text-[#1a1c1c] hover:border-[#1a1c1c] hover:bg-[#f7f7f7]"
>
{showAll ? '收起消息记录' : `查看全部 ${records.length} 条消息`}
</button>
)}
</section>
)
}

View File

@ -0,0 +1,310 @@
/** @jest-environment node */
import { prisma } from '@/lib/prisma'
import mssql from 'mssql'
import {
comparePerformanceSurveyEmployeeSyncPreview,
previewPerformanceSurveyEmployeeSync,
} from '@/lib/performance-survey-report-sync'
jest.mock('@/lib/prisma', () => ({
prisma: {
user: {
findMany: jest.fn(),
count: jest.fn(),
},
performanceSurveyEmployeeProfile: {
findMany: jest.fn(),
create: jest.fn(),
update: jest.fn(),
},
},
}))
jest.mock('mssql', () => ({
__esModule: true,
default: {
connect: jest.fn(),
Int: 'Int',
NVarChar: jest.fn((length: number) => `NVarChar(${length})`),
},
}))
describe('performance survey employee sync preview', () => {
const reportEnvKeys = [
'REPORT_DB_SERVER',
'REPORT_DB_DATABASE',
'REPORT_DB_USER',
'REPORT_DB_PASSWORD',
] as const
const originalReportEnv = Object.fromEntries(
reportEnvKeys.map((key) => [key, process.env[key]]),
)
beforeEach(() => {
jest.clearAllMocks()
for (const key of reportEnvKeys) delete process.env[key]
})
afterAll(() => {
for (const key of reportEnvKeys) {
const value = originalReportEnv[key]
if (value === undefined) delete process.env[key]
else process.env[key] = value
}
})
test('只读预检会区分新增、业务更新、无变化和素材库兜底', () => {
const identities = [
{ userId: 'user-1', dingtalkUserId: 'ding-1', email: 'one@example.com', username: '甲' },
{ userId: 'user-2', dingtalkUserId: 'ding-2', email: 'two@example.com', username: '乙' },
{ userId: 'user-3', dingtalkUserId: 'ding-3', email: 'three@example.com', username: '丙' },
{ userId: 'user-4', dingtalkUserId: 'ding-4', email: 'four@example.com', username: '丁' },
]
const rows = [
{
dingtalkUserId: 'ding-1',
dingEmail: 'one@example.com',
contactName: '甲',
departmentName: '品牌创意A部',
},
{
dingtalkUserId: 'ding-2',
dingEmail: 'two@example.com',
contactName: '乙',
departmentName: '品牌创意B部',
},
{
dingtalkUserId: 'ding-3',
dingEmail: 'three@example.com',
contactName: '丙',
departmentName: '综合支持部',
},
]
const existingProfiles = [
{
id: 'profile-1',
dingtalkUserId: 'ding-1',
dingEmail: 'one@example.com',
jobNumber: null,
flowerName: null,
realName: '甲',
displayName: '甲',
departmentName: '品牌创意A部',
departmentPath: '品牌创意A部',
positionTitle: null,
positionLevel: null,
levelType: null,
isLeadership: false,
managerDingtalkUserId: null,
managerJobNumber: null,
managerName: null,
employmentStatus: null,
workPlace: null,
sourcePayload: {
source: 'JSReportReplica.rpt',
materialUserId: 'user-1',
materialUserEmail: 'one@example.com',
},
},
{
id: 'profile-2',
dingtalkUserId: 'ding-2',
dingEmail: 'two@example.com',
jobNumber: null,
flowerName: null,
realName: '乙',
displayName: '乙',
departmentName: '旧部门',
departmentPath: '旧部门',
positionTitle: null,
positionLevel: null,
levelType: null,
isLeadership: false,
managerDingtalkUserId: null,
managerJobNumber: null,
managerName: null,
employmentStatus: null,
workPlace: null,
sourcePayload: {
source: 'JSReportReplica.rpt',
materialUserId: 'user-2',
materialUserEmail: 'two@example.com',
},
},
{
id: 'profile-4',
dingtalkUserId: 'ding-4',
dingEmail: 'four@example.com',
jobNumber: null,
flowerName: null,
realName: '丁',
displayName: '丁',
departmentName: null,
departmentPath: null,
positionTitle: null,
positionLevel: null,
levelType: null,
isLeadership: false,
managerDingtalkUserId: null,
managerJobNumber: null,
managerName: null,
employmentStatus: null,
workPlace: null,
sourcePayload: {
source: 'material_user_fallback',
materialUserId: 'user-4',
materialUserEmail: 'four@example.com',
},
},
]
const result = comparePerformanceSurveyEmployeeSyncPreview({
identities,
rows,
existingProfiles,
})
expect(result).toMatchObject({
fetched: 3,
matchedAccounts: 3,
created: 1,
updated: 1,
unchanged: 2,
fallback: 1,
skipped: 0,
plannedProfileWrites: 4,
})
expect(result.changedFields).toEqual(expect.arrayContaining([
{ field: 'departmentName', count: 1 },
{ field: 'departmentPath', count: 1 },
]))
})
test('未配置上游时只返回兜底预检,且不会写入本地数据库', async () => {
;(prisma.user.findMany as jest.Mock).mockResolvedValue([{
id: 'user-1',
email: 'one@example.com',
username: '甲',
realName: null,
dingtalkUserId: 'ding-1',
department: '综合支持部',
}])
;(prisma.user.count as jest.Mock).mockResolvedValue(1)
;(prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock).mockResolvedValue([])
const result = await previewPerformanceSurveyEmployeeSync({ limit: 3000 })
expect(result).toMatchObject({
mode: 'preview',
dryRun: true,
source: {
type: 'material_user_fallback',
upstreamQueried: false,
},
now: {
scannedAccounts: 1,
databaseWritten: false,
},
counts: {
created: 1,
fallback: 1,
deactivated: null,
},
deactivation: {
status: 'unsupported',
count: null,
},
})
expect(prisma.performanceSurveyEmployeeProfile.create).not.toHaveBeenCalled()
expect(prisma.performanceSurveyEmployeeProfile.update).not.toHaveBeenCalled()
})
test('管理员主动预检可只读访问上游,仍不会写入本地数据库', async () => {
process.env.REPORT_DB_SERVER = 'report.example.test'
process.env.REPORT_DB_DATABASE = 'report'
process.env.REPORT_DB_USER = 'readonly'
process.env.REPORT_DB_PASSWORD = 'secret'
;(prisma.user.findMany as jest.Mock).mockResolvedValue([{
id: 'user-1',
email: 'one@example.com',
username: '甲',
realName: null,
dingtalkUserId: 'ding-1',
department: '综合支持部',
}])
;(prisma.user.count as jest.Mock).mockResolvedValue(1)
;(prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock).mockResolvedValue([])
const pool = {
request: jest.fn(() => {
const inputs = new Map<string, unknown>()
const request: {
input: jest.Mock
query: jest.Mock
} = {
input: jest.fn(),
query: jest.fn(),
}
request.input.mockImplementation((name: string, ...args: unknown[]) => {
inputs.set(name, args[args.length - 1])
return request
})
request.query.mockImplementation(async (query: string) => {
if (query.includes('INFORMATION_SCHEMA.COLUMNS')) {
const table = inputs.get('table')
return {
recordset: table === 'hr_employee'
? ['userid', 'email', 'job_number', 'name', 'title', 'active']
.map((COLUMN_NAME) => ({ COLUMN_NAME }))
: [],
}
}
if (query.includes('[rpt].[hr_employee]')) {
return {
recordset: [{
dingtalkUserId: 'ding-1',
dingEmail: 'one@example.com',
jobNumber: 'JS001',
contactName: '甲',
contactTitle: '设计师',
}],
}
}
throw new Error(`未预期的查询:${query}`)
})
return request
}),
close: jest.fn(),
}
;(mssql.connect as jest.Mock).mockResolvedValue(pool)
const result = await previewPerformanceSurveyEmployeeSync({ limit: 3000 })
expect(result).toMatchObject({
mode: 'preview',
dryRun: true,
source: {
type: 'report_database',
access: 'read_only',
trigger: 'admin_manual_preview',
upstreamQueried: true,
},
now: {
databaseWritten: false,
},
counts: {
fetched: 1,
matchedAccounts: 1,
created: 1,
fallback: 0,
deactivated: null,
},
})
expect(mssql.connect).toHaveBeenCalledTimes(1)
expect(pool.close).toHaveBeenCalledTimes(1)
expect(prisma.performanceSurveyEmployeeProfile.create).not.toHaveBeenCalled()
expect(prisma.performanceSurveyEmployeeProfile.update).not.toHaveBeenCalled()
})
})

View File

@ -11,6 +11,7 @@ import {
getPerformanceSurveyMe,
getPerformanceSurveyResults,
listPerformanceSurveys,
previewPerformanceSurveyEmployeeProfiles,
searchPerformanceSurveyEmployees,
submitPerformanceSurveyResponse,
updatePerformanceSurvey,
@ -19,6 +20,7 @@ import { prisma } from '@/lib/prisma'
import {
ensurePerformanceSurveyEmployeeProfileForUser,
getPerformanceSurveyAccountProfileWhere,
previewPerformanceSurveyEmployeeSync,
} from '@/lib/performance-survey-report-sync'
import {
DEFAULT_PERFORMANCE_SURVEY_TEMPLATES,
@ -76,6 +78,7 @@ jest.mock('@/lib/performance-survey-report-sync', () => ({
ensurePerformanceSurveyDailyEmployeeSyncStarted: jest.fn(),
ensurePerformanceSurveyEmployeeProfileForUser: jest.fn(),
getPerformanceSurveyAccountProfileWhere: jest.fn(async () => ({ id: { not: '__hidden__' } })),
previewPerformanceSurveyEmployeeSync: jest.fn(),
syncPerformanceSurveyEmployees: jest.fn(),
}))
@ -213,6 +216,7 @@ describe('performance survey service policies', () => {
;(prisma.user.findUnique as jest.Mock).mockResolvedValue(baseUser)
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockReset()
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockResolvedValue(baseEmployee)
;(previewPerformanceSurveyEmployeeSync as jest.Mock).mockReset()
;(prisma.performanceSurvey.findUnique as jest.Mock).mockResolvedValue(buildSurvey())
;(prisma.performanceSurvey.findMany as jest.Mock).mockResolvedValue([])
;(prisma.performanceSurveyAssignment.findFirst as jest.Mock).mockResolvedValue(null)
@ -275,6 +279,52 @@ describe('performance survey service policies', () => {
;(prisma.$transaction as jest.Mock).mockImplementation(async (callback) => callback(transactionClient))
})
test('普通用户不能执行人员同步预检', async () => {
await expect(previewPerformanceSurveyEmployeeProfiles(session, { limit: 100 }))
.rejects.toMatchObject({
message: '需要系统管理员权限',
status: 403,
})
expect(previewPerformanceSurveyEmployeeSync).not.toHaveBeenCalled()
})
test('系统管理员可执行只读人员同步预检', async () => {
;(prisma.user.findUnique as jest.Mock).mockResolvedValue({
...baseUser,
role: 'ADMIN',
isSuperAdmin: true,
})
;(previewPerformanceSurveyEmployeeSync as jest.Mock).mockResolvedValue({
mode: 'preview',
dryRun: true,
})
await expect(previewPerformanceSurveyEmployeeProfiles(session, { limit: 200 }))
.resolves.toEqual({
mode: 'preview',
dryRun: true,
})
expect(previewPerformanceSurveyEmployeeSync).toHaveBeenCalledWith({ limit: 200 })
expect(ensurePerformanceSurveyEmployeeProfileForUser).not.toHaveBeenCalled()
})
test('人员同步预检超时会返回中文错误且强调未写入', async () => {
;(prisma.user.findUnique as jest.Mock).mockResolvedValue({
...baseUser,
role: 'ADMIN',
isSuperAdmin: true,
})
;(previewPerformanceSurveyEmployeeSync as jest.Mock).mockRejectedValue(
Object.assign(new Error('request timeout'), { code: 'ETIMEOUT' }),
)
await expect(previewPerformanceSurveyEmployeeProfiles(session, {}))
.rejects.toMatchObject({
message: expect.stringContaining('预检未写入任何数据'),
status: 504,
})
})
test('视觉模板统计只采用最终评分角色,不混入自评和主管评分', async () => {
;(listPerformanceSurveyTemplates as jest.Mock).mockResolvedValue([{
code: 'visual_brand_tone',

View File

@ -0,0 +1,100 @@
/** @jest-environment node */
import { getServerSession } from 'next-auth'
import { POST } from '@/app/api/performance-survey/[...path]/route'
import {
previewPerformanceSurveyEmployeeProfiles,
syncPerformanceSurveyEmployeeProfiles,
} from '@/lib/performance-survey-service'
jest.mock('next-auth', () => ({
getServerSession: jest.fn(),
}))
jest.mock('@/lib/auth', () => ({
authOptions: {},
}))
jest.mock('@/lib/dingtalk-performance-session', () => ({
DINGTALK_PERFORMANCE_SESSION_HEADER: 'x-performance-token',
verifyDingtalkPerformanceSessionToken: jest.fn(),
}))
jest.mock('@/lib/performance-survey-service', () => ({
PerformanceSurveyApiError: class PerformanceSurveyApiError extends Error {
status: number
constructor(message: string, status = 400) {
super(message)
this.status = status
}
},
previewPerformanceSurveyEmployeeProfiles: jest.fn(),
syncPerformanceSurveyEmployeeProfiles: jest.fn(),
}))
describe('performance survey employee sync route', () => {
beforeEach(() => {
jest.clearAllMocks()
;(getServerSession as jest.Mock).mockResolvedValue({
user: { id: 'admin-1' },
expires: '2099-01-01T00:00:00.000Z',
})
})
test('preview 子路径只执行只读预检', async () => {
;(previewPerformanceSurveyEmployeeProfiles as jest.Mock).mockResolvedValue({
mode: 'preview',
dryRun: true,
})
const response = await POST(
new Request('https://example.test/api/performance-survey/admin/sync-employees/preview', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ limit: 200 }),
}),
{ params: { path: ['admin', 'sync-employees', 'preview'] } },
)
const payload = await response.json()
expect(response.status).toBe(200)
expect(payload).toEqual({
success: true,
data: { mode: 'preview', dryRun: true },
})
expect(previewPerformanceSurveyEmployeeProfiles).toHaveBeenCalledWith(
expect.objectContaining({ user: expect.objectContaining({ id: 'admin-1' }) }),
{ limit: 200 },
)
expect(syncPerformanceSurveyEmployeeProfiles).not.toHaveBeenCalled()
})
test('原同步路径继续执行正式同步,契约不变', async () => {
;(syncPerformanceSurveyEmployeeProfiles as jest.Mock).mockResolvedValue({
scannedAccounts: 10,
upserted: 8,
})
const response = await POST(
new Request('https://example.test/api/performance-survey/admin/sync-employees', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ limit: 3000 }),
}),
{ params: { path: ['admin', 'sync-employees'] } },
)
const payload = await response.json()
expect(response.status).toBe(200)
expect(payload).toEqual({
success: true,
data: { scannedAccounts: 10, upserted: 8 },
})
expect(syncPerformanceSurveyEmployeeProfiles).toHaveBeenCalledWith(
expect.objectContaining({ user: expect.objectContaining({ id: 'admin-1' }) }),
{ limit: 3000 },
)
expect(previewPerformanceSurveyEmployeeProfiles).not.toHaveBeenCalled()
})
})

View File

@ -51,6 +51,29 @@ type ReportIdentity = {
department?: string | null
}
type EmployeeProfileSnapshot = {
id: string
dingtalkUserId?: string | null
dingEmail?: string | null
jobNumber?: string | null
flowerName?: string | null
realName?: string | null
displayName: string
departmentName?: string | null
departmentPath?: string | null
positionTitle?: string | null
positionLevel?: string | null
levelType?: string | null
isLeadership: boolean
managerDingtalkUserId?: string | null
managerJobNumber?: string | null
managerName?: string | null
employmentStatus?: string | null
workPlace?: string | null
sourcePayload?: unknown
syncedAt?: Date | null
}
type TableColumns = Map<string, string>
const EMPLOYEE_TABLE = {
@ -130,6 +153,11 @@ const FIELD_CANDIDATES = {
let dailyWorkerStarted = false
function normalizeEmployeeSyncLimit(value: unknown, fallback = 3000) {
const parsed = Number(value)
return Math.max(1, Math.min(Number.isFinite(parsed) ? parsed : fallback, 10_000))
}
export function isPerformanceSurveyReportDbConfigured() {
return Boolean(
process.env.REPORT_DB_SERVER &&
@ -790,6 +818,10 @@ async function listMaterialAccountSyncIdentities(limit?: number) {
}))
}
async function countMaterialAccountSyncIdentities() {
return prisma.user.count({ where: getSyncableUserWhere() })
}
export async function getPerformanceSurveyAccountProfileWhere() {
if (accountProfileWhereCache && accountProfileWhereCache.expiresAt > Date.now()) {
return accountProfileWhereCache.where
@ -1270,6 +1302,262 @@ function normalizeEmployeeRow(row: ReportEmployeeRow) {
}
}
type PreviewProfileData = Partial<Omit<ReturnType<typeof normalizeEmployeeRow>, 'sourcePayload' | 'syncedAt'>> & {
sourcePayload?: unknown
syncedAt?: Date
}
const PREVIEW_PROFILE_FIELDS = [
'dingtalkUserId',
'dingEmail',
'jobNumber',
'flowerName',
'realName',
'displayName',
'departmentName',
'departmentPath',
'positionTitle',
'positionLevel',
'levelType',
'isLeadership',
'managerDingtalkUserId',
'managerJobNumber',
'managerName',
'employmentStatus',
'workPlace',
] as const
type PreviewChangedField = (typeof PREVIEW_PROFILE_FIELDS)[number] | 'sourcePayload'
function getSourcePayloadLink(payload: unknown) {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
return { source: null, materialUserId: null, materialUserEmail: null }
}
const record = payload as Record<string, unknown>
return {
source: clean(record.source),
materialUserId: clean(record.materialUserId) || clean(record.userId),
materialUserEmail: clean(record.materialUserEmail),
}
}
function previewValueEquals(left: unknown, right: unknown) {
if (typeof left === 'boolean' || typeof right === 'boolean') {
return Boolean(left) === Boolean(right)
}
return clean(left) === clean(right)
}
function hasBusinessProfileChanges(existing: EmployeeProfileSnapshot, proposed: PreviewProfileData) {
const changedFields: PreviewChangedField[] = PREVIEW_PROFILE_FIELDS.filter((field) => (
Object.prototype.hasOwnProperty.call(proposed, field)
&& !previewValueEquals(existing[field], proposed[field])
))
if (Object.prototype.hasOwnProperty.call(proposed, 'sourcePayload')) {
const currentLink = getSourcePayloadLink(existing.sourcePayload)
const proposedLink = getSourcePayloadLink(proposed.sourcePayload)
if (
currentLink.source !== proposedLink.source
|| currentLink.materialUserId !== proposedLink.materialUserId
|| currentLink.materialUserEmail !== proposedLink.materialUserEmail
) {
changedFields.push('sourcePayload')
}
}
return changedFields
}
function getExistingProfileMatchKeys(profile: Partial<EmployeeProfileSnapshot>) {
return [
...uniqueClean([profile.dingtalkUserId]).map((value) => `ding:${value.toLowerCase()}`),
...uniqueClean([profile.jobNumber]).map((value) => `job:${value.toLowerCase()}`),
...uniqueClean([profile.dingEmail]).map((value) => `email:${value.toLowerCase()}`),
]
}
function getProposedProfileMatchKeys(profile: PreviewProfileData) {
return [
...uniqueClean([profile.dingtalkUserId]).map((value) => `ding:${value.toLowerCase()}`),
...uniqueClean([profile.jobNumber]).map((value) => `job:${value.toLowerCase()}`),
...uniqueClean([profile.dingEmail]).map((value) => `email:${value.toLowerCase()}`),
]
}
function buildFallbackPreviewProfile(identity: ReportIdentity & { userId?: string }): PreviewProfileData {
return {
dingtalkUserId: clean(identity.dingtalkUserId),
dingEmail: clean(identity.email),
displayName: clean(identity.flowerName)
|| clean(identity.displayName)
|| clean(identity.realName)
|| clean(identity.username)
|| '未知员工',
realName: clean(identity.realName) || clean(identity.username),
flowerName: clean(identity.flowerName),
departmentName: clean(identity.department),
departmentPath: clean(identity.department),
sourcePayload: {
source: 'material_user_fallback',
userId: identity.userId || null,
materialUserId: identity.userId || null,
materialUserEmail: clean(identity.email),
},
}
}
function matchNormalizedRowsToIdentities(
identities: Array<ReportIdentity & { userId?: string }>,
rows: ReportEmployeeRow[],
) {
const identityIndexesByKey = new Map<string, number[]>()
identities.forEach((identity, index) => {
for (const key of getIdentityMatchKeys(identity)) {
const indexes = identityIndexesByKey.get(key) || []
indexes.push(index)
identityIndexesByKey.set(key, indexes)
}
})
let skippedRows = 0
const bestMatchesByIdentity = new Map<number, {
normalized: ReturnType<typeof normalizeEmployeeRow>
score: number
}>()
for (const row of rows) {
const normalized = normalizeEmployeeRow(row)
if (!normalized.dingtalkUserId && !normalized.jobNumber && !normalized.dingEmail) {
skippedRows += 1
continue
}
const candidateIndexes = new Set<number>()
for (const key of getNormalizedProfileMatchKeys(normalized)) {
for (const index of identityIndexesByKey.get(key) || []) {
candidateIndexes.add(index)
}
}
for (const index of Array.from(candidateIndexes)) {
const score = getIdentityProfileMatchScore(identities[index], normalized)
if (score <= 0) continue
const current = bestMatchesByIdentity.get(index)
if (!current || score > current.score) {
bestMatchesByIdentity.set(index, { normalized, score })
}
}
}
return { bestMatchesByIdentity, skippedRows }
}
export function comparePerformanceSurveyEmployeeSyncPreview(input: {
identities: Array<ReportIdentity & { userId?: string }>
rows: ReportEmployeeRow[]
existingProfiles: EmployeeProfileSnapshot[]
}) {
const { identities, rows, existingProfiles } = input
const { bestMatchesByIdentity, skippedRows } = matchNormalizedRowsToIdentities(identities, rows)
const existingByKey = new Map<string, EmployeeProfileSnapshot>()
for (const profile of existingProfiles) {
for (const key of getExistingProfileMatchKeys(profile)) {
if (!existingByKey.has(key)) existingByKey.set(key, profile)
}
}
const findExisting = (proposed: PreviewProfileData) => {
for (const key of getProposedProfileMatchKeys(proposed)) {
const existing = existingByKey.get(key)
if (existing) return existing
}
return null
}
let created = 0
let updated = 0
let unchanged = 0
let fallback = 0
let skipped = skippedRows
let deduplicated = 0
const matchedIdentityIndexes = new Set<number>()
const plannedProfileKeys = new Set<string>()
const changedFields = new Map<string, number>()
const classify = (proposed: PreviewProfileData) => {
const existing = findExisting(proposed)
if (!existing) {
created += 1
return
}
const fields = hasBusinessProfileChanges(existing, proposed)
if (fields.length === 0) {
unchanged += 1
return
}
updated += 1
for (const field of fields) {
changedFields.set(field, (changedFields.get(field) || 0) + 1)
}
}
for (const [index, match] of Array.from(bestMatchesByIdentity.entries())) {
const identity = identities[index]
const proposed: PreviewProfileData = {
...match.normalized,
sourcePayload: {
...(match.normalized.sourcePayload || {}),
materialUserId: identity.userId || null,
materialUserEmail: clean(identity.email),
},
}
const profileKey = getProposedProfileMatchKeys(proposed)[0]
|| `name:${clean(proposed.displayName)?.toLowerCase() || index}`
if (plannedProfileKeys.has(profileKey)) {
deduplicated += 1
matchedIdentityIndexes.add(index)
continue
}
plannedProfileKeys.add(profileKey)
matchedIdentityIndexes.add(index)
classify(proposed)
}
identities.forEach((identity, index) => {
if (matchedIdentityIndexes.has(index)) return
if (
!clean(identity.dingtalkUserId)
&& !clean(identity.email)
&& !clean(identity.username)
&& !clean(identity.realName)
) {
skipped += 1
return
}
fallback += 1
classify(buildFallbackPreviewProfile(identity))
})
return {
fetched: rows.length,
matchedAccounts: matchedIdentityIndexes.size,
created,
updated,
unchanged,
fallback,
skipped,
deduplicated,
plannedProfileWrites: created + updated + unchanged,
changedFields: Array.from(changedFields.entries())
.map(([field, count]) => ({ field, count }))
.sort((left, right) => right.count - left.count || left.field.localeCompare(right.field)),
}
}
async function findExistingEmployeeProfile(data: Partial<ReturnType<typeof normalizeEmployeeRow>>) {
const or = [
data.dingtalkUserId ? { dingtalkUserId: data.dingtalkUserId } : null,
@ -1564,8 +1852,137 @@ export function ensurePerformanceSurveyDailyEmployeeSyncStarted() {
timer.unref?.()
}
export async function previewPerformanceSurveyEmployeeSync(options?: { limit?: number }) {
const startedAt = new Date()
const limit = normalizeEmployeeSyncLimit(options?.limit)
const [identities, totalAccounts, existingProfiles] = await Promise.all([
listMaterialAccountSyncIdentities(limit),
countMaterialAccountSyncIdentities(),
prisma.performanceSurveyEmployeeProfile.findMany({
select: {
id: true,
dingtalkUserId: true,
dingEmail: true,
jobNumber: true,
flowerName: true,
realName: true,
displayName: true,
departmentName: true,
departmentPath: true,
positionTitle: true,
positionLevel: true,
levelType: true,
isLeadership: true,
managerDingtalkUserId: true,
managerJobNumber: true,
managerName: true,
employmentStatus: true,
workPlace: true,
sourcePayload: true,
syncedAt: true,
},
}),
])
const configured = isPerformanceSurveyReportDbConfigured()
let rows: ReportEmployeeRow[] = []
if (configured) {
const { sql, pool } = await getReportPool()
try {
const schema = await getReportSchema(pool)
rows = await fetchAccountScopedSyncRows(pool, sql, schema, identities, limit)
} finally {
await pool.close()
}
}
const comparison = comparePerformanceSurveyEmployeeSyncPreview({
identities,
rows,
existingProfiles: existingProfiles as EmployeeProfileSnapshot[],
})
const completedAt = new Date()
const latestLocalSyncedAt = existingProfiles.reduce<Date | null>((latest, profile) => {
if (!profile.syncedAt) return latest
return !latest || profile.syncedAt > latest ? profile.syncedAt : latest
}, null)
const warnings = [
'这是只读预检:只读取素材库账号、本地人员档案和上游花名册,不会写入或停用任何人员。',
'系统尚未记录“整批同步成功时间”;last.latestLocalProfileSyncedAt 仅表示最近一条本地人员档案的同步时间。',
'现有正式同步不会把“本次上游未返回”直接视为离职或停用,因此停用人数无法可靠推断。',
]
if (totalAccounts > identities.length) {
warnings.push(`本次按上限 ${limit} 预检了 ${identities.length}/${totalAccounts} 个素材库账号,结果不是全量。`)
}
if (!configured) {
warnings.push('上游花名册数据库未配置;正式同步只会使用素材库账号建立或更新兜底档案。')
} else if (comparison.fallback > 0) {
warnings.push(`${comparison.fallback} 个素材库账号未匹配到上游花名册,正式同步时会使用素材库账号信息作为兜底。`)
}
if (comparison.skipped > 0) {
warnings.push(`${comparison.skipped} 条数据缺少可用身份标识,正式同步时会跳过。`)
}
return {
mode: 'preview',
dryRun: true,
source: {
type: configured ? 'report_database' : 'material_user_fallback',
name: configured ? 'JSReportReplica.rpt' : '素材库用户表',
tables: configured
? [
`${EMPLOYEE_TABLE.schema}.${EMPLOYEE_TABLE.table}`,
`${REGISTER_TABLE.schema}.${REGISTER_TABLE.table}`,
`${FLOWER_TABLE.schema}.${FLOWER_TABLE.table}`,
]
: ['User'],
access: 'read_only',
trigger: 'admin_manual_preview',
upstreamQueried: configured,
},
last: {
status: latestLocalSyncedAt ? 'approximate' : 'unavailable',
latestLocalProfileSyncedAt: latestLocalSyncedAt?.toISOString() || null,
localProfileCount: existingProfiles.length,
note: latestLocalSyncedAt
? '该时间来自最近一条本地人员档案,不代表最近一次整批同步成功时间。'
: '本地尚无可用的人员档案同步时间。',
},
now: {
requestedLimit: limit,
totalAccounts,
scannedAccounts: identities.length,
truncated: totalAccounts > identities.length,
previewStartedAt: startedAt.toISOString(),
previewCompletedAt: completedAt.toISOString(),
durationMs: completedAt.getTime() - startedAt.getTime(),
databaseWritten: false,
},
counts: {
fetched: comparison.fetched,
matchedAccounts: comparison.matchedAccounts,
created: comparison.created,
updated: comparison.updated,
unchanged: comparison.unchanged,
fallback: comparison.fallback,
skipped: comparison.skipped,
deduplicated: comparison.deduplicated,
plannedProfileWrites: comparison.plannedProfileWrites,
deactivated: null,
},
deactivation: {
status: 'unsupported',
count: null,
reason: '当前同步范围仅覆盖素材库现有账号,且正式同步没有“上游缺失即停用”的规则,无法可靠计算停用人数。',
},
changedFields: comparison.changedFields,
warnings,
}
}
export async function syncPerformanceSurveyEmployees(options?: { limit?: number }) {
const limit = Math.max(1, Math.min(Number(options?.limit || 3000), 10_000))
const limit = normalizeEmployeeSyncLimit(options?.limit)
const identities = await listMaterialAccountSyncIdentities(limit)
if (!isPerformanceSurveyReportDbConfigured()) {

View File

@ -64,6 +64,7 @@ import {
ensurePerformanceSurveyDailyEmployeeSyncStarted,
ensurePerformanceSurveyEmployeeProfileForUser,
getPerformanceSurveyAccountProfileWhere,
previewPerformanceSurveyEmployeeSync,
syncPerformanceSurveyEmployees,
} from '@/lib/performance-survey-report-sync'
import {
@ -796,6 +797,27 @@ function ensureSystemAdministrator(ctx: UserContext) {
}
}
async function ensureReadOnlySystemAdministrator(session: Session | null) {
const sessionUserId = (session?.user as any)?.id
if (!sessionUserId) {
throw new PerformanceSurveyApiError('请先登录', 401)
}
const user = await prisma.user.findUnique({
where: { id: sessionUserId },
select: {
role: true,
isSuperAdmin: true,
},
})
if (!user) {
throw new PerformanceSurveyApiError('登录用户不存在', 401)
}
if (!user.isSuperAdmin && user.role !== 'ADMIN' && user.role !== 'SYSTEM_ADMIN') {
throw new PerformanceSurveyApiError('需要系统管理员权限', 403)
}
}
function rethrowPositionConfigError(error: unknown): never {
if (error instanceof PerformanceSurveyPositionConfigError) {
throw new PerformanceSurveyApiError(error.message, error.status)
@ -4285,6 +4307,31 @@ export async function syncPerformanceSurveyEmployeeProfiles(session: Session | n
return result
}
export async function previewPerformanceSurveyEmployeeProfiles(session: Session | null, body: any) {
await ensureReadOnlySystemAdministrator(session)
try {
return await previewPerformanceSurveyEmployeeSync({ limit: Number(body?.limit || 3000) })
} catch (error) {
const code = error && typeof error === 'object' && 'code' in error
? String((error as { code?: unknown }).code || '').toUpperCase()
: ''
const message = error instanceof Error ? error.message.toLowerCase() : ''
const timeout = ['ETIMEOUT', 'ESOCKETTIMEDOUT', 'ECONNTIMEOUT'].includes(code)
|| message.includes('timeout')
|| message.includes('timed out')
|| message.includes('超时')
console.error('[performance-survey] 人员同步预检失败:', error)
throw new PerformanceSurveyApiError(
timeout
? '人员同步预检超时:上游花名册暂时响应较慢,请稍后重试。预检未写入任何数据。'
: '人员同步预检失败:暂时无法读取上游花名册,请稍后重试。预检未写入任何数据。',
timeout ? 504 : 502,
)
}
}
export async function exportPerformanceSurveyCsv(session: Session | null) {
const ctx = await getPerformanceSurveyContext(session)
ensureManager(ctx)