feat: 按岗位配置考核调研流程
This commit is contained in:
parent
10e6b525f8
commit
9d812f8c84
1
.gitignore
vendored
1
.gitignore
vendored
@ -95,6 +95,7 @@ missing-video-files*.json
|
||||
/.claude/settings.local.json
|
||||
/.claude/worktrees/
|
||||
/.playwright-mcp/
|
||||
/.performance-survey-audits/
|
||||
|
||||
# Temporary investigation/probe artifacts
|
||||
/tmp/
|
||||
|
||||
@ -14,11 +14,13 @@ import {
|
||||
exportPerformanceSurveyCsv,
|
||||
getPerformanceSurveyDashboard,
|
||||
getPerformanceSurveyDashboardDetail,
|
||||
getPerformanceSurveyAdminConfiguration,
|
||||
getPerformanceSurveyDetail,
|
||||
getPerformanceSurveyMe,
|
||||
getPerformanceSurveyNotificationStatus,
|
||||
getPerformanceSurveyResults,
|
||||
getPerformanceSurveyTemplates,
|
||||
getPerformanceSurveyPositionGroups,
|
||||
listPerformanceSurveyDepartments,
|
||||
listPerformanceSurveyNotifications,
|
||||
listPerformanceSurveys,
|
||||
@ -30,6 +32,11 @@ import {
|
||||
submitPerformanceSurveyResponse,
|
||||
syncPerformanceSurveyEmployeeProfiles,
|
||||
updatePerformanceSurvey,
|
||||
savePerformanceSurveyAdminPositionGroup,
|
||||
publishPerformanceSurveyAdminPositionGroup,
|
||||
savePerformanceSurveyAdminTemplate,
|
||||
clonePerformanceSurveyAdminTemplateVersion,
|
||||
publishPerformanceSurveyAdminTemplateVersion,
|
||||
} from '@/lib/performance-survey-service'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
@ -51,6 +58,13 @@ function errorResponse(error: unknown) {
|
||||
return NextResponse.json({ success: false, error: error.message }, { status: error.status })
|
||||
}
|
||||
|
||||
if (error && typeof error === 'object' && typeof (error as { status?: unknown }).status === 'number') {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: error instanceof Error ? error.message : '请求失败' },
|
||||
{ status: (error as { status: number }).status },
|
||||
)
|
||||
}
|
||||
|
||||
const message = error instanceof Error ? error.message : '服务器错误'
|
||||
console.error('[performance-survey] API error:', error)
|
||||
return NextResponse.json({ success: false, error: message }, { status: 500 })
|
||||
@ -108,7 +122,11 @@ export async function GET(request: Request, context: RouteContext) {
|
||||
}
|
||||
|
||||
if (path[0] === 'templates') {
|
||||
return ok(await getPerformanceSurveyTemplates(session))
|
||||
return ok(await getPerformanceSurveyTemplates(session, url.searchParams))
|
||||
}
|
||||
|
||||
if (path[0] === 'position-groups') {
|
||||
return ok(await getPerformanceSurveyPositionGroups(session, url.searchParams))
|
||||
}
|
||||
|
||||
if (path[0] === 'employees') {
|
||||
@ -147,6 +165,10 @@ export async function GET(request: Request, context: RouteContext) {
|
||||
return ok(await getPerformanceSurveyNotificationStatus(session))
|
||||
}
|
||||
|
||||
if (path[0] === 'admin' && path[1] === 'config') {
|
||||
return ok(await getPerformanceSurveyAdminConfiguration(session, url.searchParams))
|
||||
}
|
||||
|
||||
if (path[0] === 'admin' && path[1] === 'notifications') {
|
||||
return ok(await listPerformanceSurveyNotifications(session, url.searchParams))
|
||||
}
|
||||
@ -202,6 +224,22 @@ export async function POST(request: Request, context: RouteContext) {
|
||||
return ok(await syncPerformanceSurveyEmployeeProfiles(session, body))
|
||||
}
|
||||
|
||||
if (path[0] === 'admin' && path[1] === 'position-groups' && path[2] && path[3] === 'publish') {
|
||||
return ok(await publishPerformanceSurveyAdminPositionGroup(session, path[2], body))
|
||||
}
|
||||
|
||||
if (path[0] === 'admin' && path[1] === 'templates' && path.length === 2) {
|
||||
return ok(await savePerformanceSurveyAdminTemplate(session, body), { status: 201 })
|
||||
}
|
||||
|
||||
if (path[0] === 'admin' && path[1] === 'templates' && path[2] && path[3] === 'clone') {
|
||||
return ok(await clonePerformanceSurveyAdminTemplateVersion(session, path[2]), { status: 201 })
|
||||
}
|
||||
|
||||
if (path[0] === 'admin' && path[1] === 'templates' && path[2] && path[3] === 'publish') {
|
||||
return ok(await publishPerformanceSurveyAdminTemplateVersion(session, path[2], body))
|
||||
}
|
||||
|
||||
if (path[0] === 'admin' && path[1] === 'notifications' && path[2] === 'maintenance') {
|
||||
return ok(await runPerformanceSurveyNotificationMaintenance(session))
|
||||
}
|
||||
@ -226,6 +264,14 @@ export async function PATCH(request: Request, context: RouteContext) {
|
||||
return ok(await updatePerformanceSurvey(session, path[1], body))
|
||||
}
|
||||
|
||||
if (path[0] === 'admin' && path[1] === 'position-groups' && path[2] && path.length === 3) {
|
||||
return ok(await savePerformanceSurveyAdminPositionGroup(session, path[2], body))
|
||||
}
|
||||
|
||||
if (path[0] === 'admin' && path[1] === 'templates' && path[2] && path.length === 3) {
|
||||
return ok(await savePerformanceSurveyAdminTemplate(session, { ...body, versionId: path[2] }))
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: false, error: '接口不存在' }, { status: 404 })
|
||||
} catch (error) {
|
||||
return errorResponse(error)
|
||||
|
||||
110
app/performance-survey/PerformanceSurveyAdminConfig.test.tsx
Normal file
110
app/performance-survey/PerformanceSurveyAdminConfig.test.tsx
Normal file
@ -0,0 +1,110 @@
|
||||
/** @jest-environment jsdom */
|
||||
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { PerformanceSurveyAdminConfig } from './PerformanceSurveyAdminConfig'
|
||||
|
||||
const config = {
|
||||
month: '2026-07',
|
||||
groups: [{
|
||||
id: 'group-1',
|
||||
code: 'brand_designer',
|
||||
name: '品牌设计师',
|
||||
sortOrder: 10,
|
||||
isActive: true,
|
||||
status: 'ready',
|
||||
memberCount: 6,
|
||||
rules: [{
|
||||
id: 'rule-1',
|
||||
departmentPathPrefix: '集团/品牌中心',
|
||||
positionTitle: '品牌设计师',
|
||||
isActive: true,
|
||||
sortOrder: 0,
|
||||
}],
|
||||
effectivePlan: {
|
||||
id: 'plan-1',
|
||||
version: 1,
|
||||
effectiveMonth: '2026-07',
|
||||
templateVersionIds: ['version-1'],
|
||||
},
|
||||
draftPlan: null,
|
||||
}],
|
||||
templates: [{
|
||||
id: 'template-1',
|
||||
code: 'visual_review',
|
||||
name: '视觉案例评分',
|
||||
description: '视觉案例评分',
|
||||
surveyType: 'visual_case',
|
||||
isActive: true,
|
||||
versions: [{
|
||||
id: 'version-1',
|
||||
version: 1,
|
||||
status: 'published',
|
||||
effectiveMonth: '2026-07',
|
||||
definition: {
|
||||
code: 'visual_review',
|
||||
name: '视觉案例评分',
|
||||
shortName: '视觉评分',
|
||||
description: '视觉案例评分',
|
||||
surveyType: 'visual_case',
|
||||
weight: 1,
|
||||
maxTotal: 120,
|
||||
questionMaxScore: 20,
|
||||
requiredWorkItemCount: 3,
|
||||
workItemImageRequired: true,
|
||||
questions: [{ id: 'quality', title: '作品质量', maxScore: 20 }],
|
||||
scoreBands: [],
|
||||
workflow: {
|
||||
stages: [{
|
||||
key: 'review',
|
||||
label: '终评',
|
||||
order: 0,
|
||||
reviewers: [{ source: 'direct_manager', label: '直属主管' }],
|
||||
}],
|
||||
scoring: { mode: 'final_reviewer', stageKey: 'review', reviewerSource: 'direct_manager' },
|
||||
},
|
||||
},
|
||||
}],
|
||||
}],
|
||||
issues: {
|
||||
unmatched: [{ id: 'employee-1', displayName: '待配置人员', departmentPath: '集团/品牌中心', positionTitle: '设计师' }],
|
||||
conflicts: [],
|
||||
},
|
||||
} as const
|
||||
|
||||
describe('PerformanceSurveyAdminConfig', () => {
|
||||
test('岗位配置使用岗位列表和右侧编辑区,并展示配置问题', async () => {
|
||||
const request = jest.fn().mockResolvedValue(config)
|
||||
render(<PerformanceSurveyAdminConfig mode="positions" request={request} />)
|
||||
|
||||
expect(screen.getByText('配置加载中...')).toBeInTheDocument()
|
||||
await waitFor(() => expect(screen.getByText('品牌设计师')).toBeInTheDocument())
|
||||
expect(screen.getByText('人员匹配规则')).toBeInTheDocument()
|
||||
expect(screen.getByText('考核项与顺序')).toBeInTheDocument()
|
||||
expect(screen.getByText(/未匹配 1 人/)).toBeInTheDocument()
|
||||
expect(screen.getByText('待配置人员')).toBeInTheDocument()
|
||||
expect(request).toHaveBeenCalledWith(expect.stringContaining('/admin/config?month='))
|
||||
})
|
||||
|
||||
test('模板管理展示版本状态、评分项和评审流程', async () => {
|
||||
const request = jest.fn().mockResolvedValue(config)
|
||||
render(<PerformanceSurveyAdminConfig mode="templates" request={request} />)
|
||||
|
||||
await waitFor(() => expect(screen.getAllByText('视觉案例评分').length).toBeGreaterThan(0))
|
||||
expect(screen.getByText('评分项')).toBeInTheDocument()
|
||||
expect(screen.getByText('评审流程')).toBeInTheDocument()
|
||||
expect(screen.getByText(/v1 · 已发布/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('岗位发布失败时直接展示服务端业务错误', async () => {
|
||||
const request = jest.fn().mockImplementation((path: string) => (
|
||||
path.startsWith('/admin/config')
|
||||
? Promise.resolve(config)
|
||||
: Promise.reject(new Error('岗位规则存在重复匹配人员'))
|
||||
))
|
||||
render(<PerformanceSurveyAdminConfig mode="positions" request={request} />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('品牌设计师')).toBeInTheDocument())
|
||||
fireEvent.click(screen.getByRole('button', { name: /发布至/ }))
|
||||
await waitFor(() => expect(screen.getByText('岗位规则存在重复匹配人员')).toBeInTheDocument())
|
||||
})
|
||||
})
|
||||
892
app/performance-survey/PerformanceSurveyAdminConfig.tsx
Normal file
892
app/performance-survey/PerformanceSurveyAdminConfig.tsx
Normal file
@ -0,0 +1,892 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
|
||||
type RequestFn = <T>(path: string, options?: RequestInit) => Promise<T>
|
||||
|
||||
type RuleDraft = {
|
||||
departmentPathPrefix: string
|
||||
positionTitle: string
|
||||
}
|
||||
|
||||
type ReviewerSource = 'self' | 'direct_manager' | 'fixed_employee' | 'manual_selection'
|
||||
|
||||
type ReviewerDraft = {
|
||||
source: ReviewerSource
|
||||
label: string
|
||||
employeeId?: string
|
||||
employeeName?: string
|
||||
}
|
||||
|
||||
type StageDraft = {
|
||||
key: string
|
||||
label: string
|
||||
order: number
|
||||
reviewers: ReviewerDraft[]
|
||||
}
|
||||
|
||||
type TemplateDefinition = {
|
||||
code: string
|
||||
name: string
|
||||
shortName?: string
|
||||
description: string
|
||||
surveyType: 'person_period' | 'visual_case' | 'item_course'
|
||||
weight: number
|
||||
maxTotal?: number
|
||||
questionMaxScore?: number
|
||||
requiredWorkItemCount?: number
|
||||
workItemImageRequired?: boolean
|
||||
questions: Array<{ id: string; title: string; description?: string; maxScore?: number }>
|
||||
scoreBands: unknown[]
|
||||
workflow: {
|
||||
stages: StageDraft[]
|
||||
scoring: {
|
||||
mode: 'final_reviewer' | 'average_reviewers'
|
||||
stageKey?: string
|
||||
reviewerSource?: ReviewerSource
|
||||
stageKeys?: string[]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type TemplateVersion = {
|
||||
id: string
|
||||
version: number
|
||||
status: 'draft' | 'published' | 'archived'
|
||||
effectiveMonth?: string | null
|
||||
definition: TemplateDefinition
|
||||
}
|
||||
|
||||
type TemplateRecord = {
|
||||
id: string
|
||||
code: string
|
||||
name: string
|
||||
description: string
|
||||
surveyType: string
|
||||
isActive: boolean
|
||||
versions: TemplateVersion[]
|
||||
}
|
||||
|
||||
type PositionGroupRecord = {
|
||||
id: string
|
||||
code: string
|
||||
name: string
|
||||
sortOrder: number
|
||||
isActive: boolean
|
||||
status: 'ready' | 'pending' | 'disabled'
|
||||
memberCount: number
|
||||
rules: Array<RuleDraft & { id: string; isActive: boolean; sortOrder: number }>
|
||||
effectivePlan: null | {
|
||||
id: string
|
||||
version: number
|
||||
effectiveMonth: string
|
||||
templateVersionIds: string[]
|
||||
}
|
||||
draftPlan: null | {
|
||||
id: string
|
||||
version: number
|
||||
templateVersionIds: string[]
|
||||
}
|
||||
}
|
||||
|
||||
type AdminConfig = {
|
||||
month: string
|
||||
groups: PositionGroupRecord[]
|
||||
templates: TemplateRecord[]
|
||||
issues: {
|
||||
unmatched: Array<{ id: string; displayName: string; departmentName?: string; departmentPath?: string; positionTitle?: string }>
|
||||
conflicts: Array<{ id: string; displayName: string; groupNames: string[]; departmentName?: string; departmentPath?: string; positionTitle?: string }>
|
||||
}
|
||||
}
|
||||
|
||||
function currentMonth() {
|
||||
const now = new Date()
|
||||
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
function clone<T>(value: T): T {
|
||||
return JSON.parse(JSON.stringify(value)) as T
|
||||
}
|
||||
|
||||
function newTemplateDefinition(): TemplateDefinition {
|
||||
return {
|
||||
code: '',
|
||||
name: '',
|
||||
shortName: '',
|
||||
description: '',
|
||||
surveyType: 'person_period',
|
||||
weight: 1,
|
||||
maxTotal: 120,
|
||||
questions: [{ id: 'score_1', title: '评分项 1', description: '', maxScore: 20 }],
|
||||
scoreBands: [],
|
||||
workflow: {
|
||||
stages: [{
|
||||
key: 'review',
|
||||
label: '评价',
|
||||
order: 0,
|
||||
reviewers: [{ source: 'manual_selection', label: '评价人' }],
|
||||
}],
|
||||
scoring: { mode: 'average_reviewers', stageKeys: ['review'] },
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function reviewerSourceLabel(source: ReviewerSource) {
|
||||
return {
|
||||
self: '本人',
|
||||
direct_manager: '直属主管',
|
||||
fixed_employee: '固定员工',
|
||||
manual_selection: '发起时选择',
|
||||
}[source]
|
||||
}
|
||||
|
||||
export function PerformanceSurveyAdminConfig({
|
||||
mode,
|
||||
request,
|
||||
}: {
|
||||
mode: 'positions' | 'templates'
|
||||
request: RequestFn
|
||||
}) {
|
||||
const [month, setMonth] = useState(currentMonth())
|
||||
const [data, setData] = useState<AdminConfig | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [notice, setNotice] = useState<string | null>(null)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
setData(await request<AdminConfig>(`/admin/config?month=${encodeURIComponent(month)}`))
|
||||
} catch (loadError) {
|
||||
setError(loadError instanceof Error ? loadError.message : '配置加载失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [month, request])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
return (
|
||||
<section className="min-w-0 border border-[#e2e2e2] bg-white">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-[#e2e2e2] px-4 py-3">
|
||||
<div>
|
||||
<h2 className="text-[16px] font-bold text-[#1a1c1c]">{mode === 'positions' ? '岗位配置' : '模板管理'}</h2>
|
||||
<p className="mt-0.5 text-[12px] text-[#727687]">草稿保存后按月份发布,已发布版本保持不变</p>
|
||||
</div>
|
||||
<label className="flex items-center gap-2 text-[12px] font-semibold text-[#5f5e5e]">
|
||||
查看月份
|
||||
<input
|
||||
type="month"
|
||||
value={month}
|
||||
onChange={(event) => setMonth(event.target.value)}
|
||||
className="h-9 rounded border border-[#e2e2e2] px-3 text-[13px] font-semibold text-[#1a1c1c] outline-none focus:border-[#0050cb]"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
{notice && <div className="border-b border-[#b3c5ff] bg-[#f8faff] px-4 py-3 text-[13px] font-semibold text-[#0050cb]">{notice}</div>}
|
||||
{error && <div className="border-b border-[#ffdad6] bg-[#fff6f4] px-4 py-3 text-[13px] font-semibold text-[#93000a]">{error}</div>}
|
||||
{loading && <div className="px-5 py-12 text-center text-[13px] font-semibold text-[#727687]">配置加载中...</div>}
|
||||
{!loading && data && mode === 'positions' && (
|
||||
<PositionConfigWorkspace
|
||||
data={data}
|
||||
month={month}
|
||||
request={request}
|
||||
onError={setError}
|
||||
onChanged={async (message) => {
|
||||
setNotice(message)
|
||||
await load()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{!loading && data && mode === 'templates' && (
|
||||
<TemplateConfigWorkspace
|
||||
data={data}
|
||||
month={month}
|
||||
request={request}
|
||||
onError={setError}
|
||||
onChanged={async (message) => {
|
||||
setNotice(message)
|
||||
await load()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function PositionConfigWorkspace({
|
||||
data,
|
||||
month,
|
||||
request,
|
||||
onError,
|
||||
onChanged,
|
||||
}: {
|
||||
data: AdminConfig
|
||||
month: string
|
||||
request: RequestFn
|
||||
onError: (message: string | null) => void
|
||||
onChanged: (message: string) => Promise<void>
|
||||
}) {
|
||||
const [selectedId, setSelectedId] = useState(data.groups[0]?.id || '')
|
||||
const selected = data.groups.find((group) => group.id === selectedId) || data.groups[0]
|
||||
const [name, setName] = useState(selected?.name || '')
|
||||
const [sortOrder, setSortOrder] = useState(selected?.sortOrder || 0)
|
||||
const [isActive, setIsActive] = useState(selected?.isActive ?? true)
|
||||
const [rules, setRules] = useState<RuleDraft[]>(selected?.rules.map((rule) => ({
|
||||
departmentPathPrefix: rule.departmentPathPrefix || '',
|
||||
positionTitle: rule.positionTitle || '',
|
||||
})) || [])
|
||||
const [templateVersionIds, setTemplateVersionIds] = useState<string[]>(
|
||||
selected?.draftPlan?.templateVersionIds || selected?.effectivePlan?.templateVersionIds || [],
|
||||
)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const editorRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!selected) return
|
||||
setName(selected.name)
|
||||
setSortOrder(selected.sortOrder)
|
||||
setIsActive(selected.isActive)
|
||||
setRules(selected.rules.map((rule) => ({
|
||||
departmentPathPrefix: rule.departmentPathPrefix || '',
|
||||
positionTitle: rule.positionTitle || '',
|
||||
})))
|
||||
setTemplateVersionIds(selected.draftPlan?.templateVersionIds || selected.effectivePlan?.templateVersionIds || [])
|
||||
}, [selected])
|
||||
|
||||
const publishedVersions = useMemo(() => data.templates.flatMap((template) => (
|
||||
template.versions
|
||||
.filter((version) => version.status === 'published')
|
||||
.map((version) => ({ template, version }))
|
||||
)), [data.templates])
|
||||
|
||||
if (!selected) return <div className="px-5 py-12 text-center text-sm text-[#727687]">暂无岗位组</div>
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true)
|
||||
onError(null)
|
||||
try {
|
||||
await request(`/admin/position-groups/${selected.id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ name, sortOrder, isActive, rules, templateVersionIds }),
|
||||
})
|
||||
await onChanged('岗位方案草稿已保存')
|
||||
} catch (actionError) {
|
||||
onError(actionError instanceof Error ? actionError.message : '岗位方案保存失败')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const publish = async () => {
|
||||
setSaving(true)
|
||||
onError(null)
|
||||
try {
|
||||
await request(`/admin/position-groups/${selected.id}/publish`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ effectiveMonth: month }),
|
||||
})
|
||||
await onChanged(`${selected.name} 已从 ${month} 起生效`)
|
||||
} catch (actionError) {
|
||||
onError(actionError instanceof Error ? actionError.message : '岗位方案发布失败')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const selectGroup = (groupId: string) => {
|
||||
setSelectedId(groupId)
|
||||
if (window.matchMedia('(max-width: 767px)').matches) {
|
||||
window.requestAnimationFrame(() => editorRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }))
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid min-h-[620px] md:grid-cols-[240px_minmax(0,1fr)]">
|
||||
<aside className="border-b border-[#e2e2e2] md:border-b-0 md:border-r">
|
||||
{data.groups.map((group) => (
|
||||
<button
|
||||
key={group.id}
|
||||
type="button"
|
||||
onClick={() => selectGroup(group.id)}
|
||||
className={`grid w-full grid-cols-[minmax(0,1fr)_auto] items-center gap-3 border-b border-[#eeeeee] px-4 py-3 text-left ${selected.id === group.id ? 'bg-[#f1f4ff]' : 'hover:bg-[#fafafa]'}`}
|
||||
>
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate text-[13px] font-bold text-[#1a1c1c]">{group.name}</span>
|
||||
<span className="mt-0.5 block text-[11px] text-[#727687]">{group.memberCount} 人 · {group.status === 'ready' ? '已配置' : '待配置'}</span>
|
||||
</span>
|
||||
<span className={`h-2 w-2 rounded-full ${group.status === 'ready' ? 'bg-[#16794b]' : 'bg-[#b26a00]'}`} />
|
||||
</button>
|
||||
))}
|
||||
</aside>
|
||||
|
||||
<div ref={editorRef} className="min-w-0 scroll-mt-4 p-4 sm:p-5">
|
||||
<div className="mb-4 text-[12px] font-bold text-[#0050cb] md:hidden">正在编辑:{selected.name}</div>
|
||||
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_120px_auto]">
|
||||
<AdminField label="岗位名称" value={name} onChange={setName} />
|
||||
<AdminField label="排序" value={String(sortOrder)} onChange={(value) => setSortOrder(Number(value) || 0)} type="number" />
|
||||
<label className="flex h-10 items-center gap-2 self-end text-[13px] font-semibold text-[#1a1c1c]">
|
||||
<input type="checkbox" checked={isActive} onChange={(event) => setIsActive(event.target.checked)} />
|
||||
启用岗位
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 border-t border-[#eeeeee] pt-5">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<h3 className="text-[14px] font-bold text-[#1a1c1c]">人员匹配规则</h3>
|
||||
<p className="mt-1 text-[12px] text-[#727687]">每行内条件同时满足,多行之间满足任意一行即可</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setRules((current) => [...current, { departmentPathPrefix: '', positionTitle: '' }])}
|
||||
className="h-9 border border-[#e2e2e2] px-3 text-[12px] font-bold text-[#1a1c1c] hover:bg-[#f7f7f7]"
|
||||
>
|
||||
添加规则
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-3 grid gap-2">
|
||||
{rules.map((rule, index) => (
|
||||
<div key={index} className="grid gap-2 sm:grid-cols-[minmax(0,1fr)_minmax(180px,0.7fr)_36px]">
|
||||
<input
|
||||
value={rule.departmentPathPrefix}
|
||||
onChange={(event) => setRules((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, departmentPathPrefix: event.target.value } : item))}
|
||||
placeholder="部门路径前缀,例如 品牌中心/品牌创意A部"
|
||||
className="h-10 rounded border border-[#e2e2e2] px-3 text-[13px] outline-none focus:border-[#0050cb]"
|
||||
/>
|
||||
<input
|
||||
value={rule.positionTitle}
|
||||
onChange={(event) => setRules((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, positionTitle: event.target.value } : item))}
|
||||
placeholder="职位名称(精确匹配)"
|
||||
className="h-10 rounded border border-[#e2e2e2] px-3 text-[13px] outline-none focus:border-[#0050cb]"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="删除规则"
|
||||
title="删除规则"
|
||||
onClick={() => setRules((current) => current.filter((_, itemIndex) => itemIndex !== index))}
|
||||
className="h-10 border border-[#e2e2e2] text-[18px] text-[#8c1d18] hover:bg-[#fff6f4]"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
{rules.length === 0 && <div className="border border-dashed border-[#d0d0d0] px-4 py-6 text-center text-[12px] text-[#727687]">未配置规则,岗位不能发布</div>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 border-t border-[#eeeeee] pt-5">
|
||||
<h3 className="text-[14px] font-bold text-[#1a1c1c]">考核项与顺序</h3>
|
||||
<div className="mt-3 grid gap-2">
|
||||
{publishedVersions.map(({ template, version }) => {
|
||||
const checked = templateVersionIds.includes(version.id)
|
||||
return (
|
||||
<label key={version.id} className={`grid grid-cols-[20px_minmax(0,1fr)_auto] items-center gap-3 border px-3 py-3 ${checked ? 'border-[#b3c5ff] bg-[#f8faff]' : 'border-[#eeeeee]'}`}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={(event) => setTemplateVersionIds((current) => event.target.checked
|
||||
? [...current, version.id]
|
||||
: current.filter((id) => id !== version.id))}
|
||||
/>
|
||||
<span className="min-w-0 truncate text-[13px] font-semibold text-[#1a1c1c]">{version.definition.shortName || template.name}</span>
|
||||
<span className="text-[11px] text-[#727687]">v{version.version}</span>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex flex-wrap justify-end gap-2 border-t border-[#eeeeee] pt-4">
|
||||
<button type="button" disabled={saving} onClick={save} className="h-10 border border-[#1a1c1c] px-4 text-[13px] font-bold text-[#1a1c1c] disabled:opacity-50">保存草稿</button>
|
||||
<button type="button" disabled={saving} onClick={publish} className="h-10 bg-[#0050cb] px-4 text-[13px] font-bold text-white disabled:opacity-50">发布至 {month}</button>
|
||||
</div>
|
||||
|
||||
{(data.issues.conflicts.length > 0 || data.issues.unmatched.length > 0) && (
|
||||
<div className="mt-6 border-t border-[#eeeeee] pt-5">
|
||||
<h3 className="text-[14px] font-bold text-[#1a1c1c]">配置问题</h3>
|
||||
<div className="mt-2 text-[12px] text-[#727687]">
|
||||
未匹配 {data.issues.unmatched.length} 人 · 重复匹配 {data.issues.conflicts.length} 人
|
||||
</div>
|
||||
<div className="mt-3 grid max-h-64 gap-4 overflow-y-auto pr-1 sm:grid-cols-2">
|
||||
{data.issues.unmatched.length > 0 && (
|
||||
<div>
|
||||
<div className="mb-2 text-[12px] font-bold text-[#8a5700]">未匹配人员</div>
|
||||
<div className="grid gap-2">
|
||||
{data.issues.unmatched.map((item) => (
|
||||
<div key={item.id} className="border-l-2 border-[#c78512] pl-3 text-[12px] text-[#5f5e5e]">
|
||||
<strong className="text-[#1a1c1c]">{item.displayName}</strong>
|
||||
<span className="block text-[11px] text-[#727687]">{item.departmentPath || item.departmentName || '未填写部门'} · {item.positionTitle || '未填写职位'}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{data.issues.conflicts.length > 0 && (
|
||||
<div>
|
||||
<div className="mb-2 text-[12px] font-bold text-[#b42318]">重复匹配人员</div>
|
||||
<div className="grid gap-2">
|
||||
{data.issues.conflicts.map((item) => (
|
||||
<div key={item.id} className="border-l-2 border-[#b42318] pl-3 text-[12px] text-[#5f5e5e]">
|
||||
<strong className="text-[#1a1c1c]">{item.displayName}</strong>:{item.groupNames.join('、')}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TemplateConfigWorkspace({
|
||||
data,
|
||||
month,
|
||||
request,
|
||||
onError,
|
||||
onChanged,
|
||||
}: {
|
||||
data: AdminConfig
|
||||
month: string
|
||||
request: RequestFn
|
||||
onError: (message: string | null) => void
|
||||
onChanged: (message: string) => Promise<void>
|
||||
}) {
|
||||
const firstTemplate = data.templates[0]
|
||||
const [selectedTemplateId, setSelectedTemplateId] = useState(firstTemplate?.id || 'new')
|
||||
const selectedTemplate = data.templates.find((template) => template.id === selectedTemplateId) || null
|
||||
const selectedVersion = selectedTemplate?.versions.find((version) => version.status === 'draft')
|
||||
|| selectedTemplate?.versions[0]
|
||||
|| null
|
||||
const [versionId, setVersionId] = useState<string | null>(selectedVersion?.id || null)
|
||||
const [definition, setDefinition] = useState<TemplateDefinition>(() => clone(selectedVersion?.definition || newTemplateDefinition()))
|
||||
const [saving, setSaving] = useState(false)
|
||||
const editorRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const nextVersion = selectedTemplate?.versions.find((version) => version.status === 'draft')
|
||||
|| selectedTemplate?.versions[0]
|
||||
|| null
|
||||
setVersionId(nextVersion?.id || null)
|
||||
setDefinition(clone(nextVersion?.definition || newTemplateDefinition()))
|
||||
}, [selectedTemplate])
|
||||
|
||||
const version = selectedTemplate?.versions.find((item) => item.id === versionId) || null
|
||||
const editable = !version || version.status === 'draft'
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true)
|
||||
onError(null)
|
||||
try {
|
||||
const saved = versionId
|
||||
? await request<{ id: string }>(`/admin/templates/${versionId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ definition }),
|
||||
})
|
||||
: await request<{ id: string }>('/admin/templates', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ definition }),
|
||||
})
|
||||
setVersionId(saved.id)
|
||||
await onChanged('模板草稿已保存')
|
||||
} catch (actionError) {
|
||||
onError(actionError instanceof Error ? actionError.message : '模板草稿保存失败')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const cloneVersion = async () => {
|
||||
if (!versionId) return
|
||||
setSaving(true)
|
||||
onError(null)
|
||||
try {
|
||||
const draft = await request<{ id: string }>(`/admin/templates/${versionId}/clone`, { method: 'POST', body: '{}' })
|
||||
setVersionId(draft.id)
|
||||
await onChanged('已创建新的模板草稿')
|
||||
} catch (actionError) {
|
||||
onError(actionError instanceof Error ? actionError.message : '模板草稿创建失败')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const publish = async () => {
|
||||
if (!versionId) return
|
||||
setSaving(true)
|
||||
onError(null)
|
||||
try {
|
||||
await request(`/admin/templates/${versionId}/publish`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ effectiveMonth: month }),
|
||||
})
|
||||
await onChanged(`${definition.name} 已从 ${month} 起发布`)
|
||||
} catch (actionError) {
|
||||
onError(actionError instanceof Error ? actionError.message : '模板发布失败')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const selectTemplate = (templateId: string) => {
|
||||
setSelectedTemplateId(templateId)
|
||||
if (window.matchMedia('(max-width: 767px)').matches) {
|
||||
window.requestAnimationFrame(() => editorRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }))
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid min-h-[680px] md:grid-cols-[260px_minmax(0,1fr)]">
|
||||
<aside className="border-b border-[#e2e2e2] md:border-b-0 md:border-r">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => selectTemplate('new')}
|
||||
className={`w-full border-b border-[#eeeeee] px-4 py-3 text-left text-[13px] font-bold ${selectedTemplateId === 'new' ? 'bg-[#f1f4ff] text-[#0050cb]' : 'text-[#1a1c1c] hover:bg-[#fafafa]'}`}
|
||||
>
|
||||
新建模板
|
||||
</button>
|
||||
{data.templates.map((template) => (
|
||||
<button
|
||||
key={template.id}
|
||||
type="button"
|
||||
onClick={() => selectTemplate(template.id)}
|
||||
className={`w-full border-b border-[#eeeeee] px-4 py-3 text-left ${selectedTemplateId === template.id ? 'bg-[#f1f4ff]' : 'hover:bg-[#fafafa]'}`}
|
||||
>
|
||||
<span className="block truncate text-[13px] font-bold text-[#1a1c1c]">{template.name}</span>
|
||||
<span className="mt-0.5 block text-[11px] text-[#727687]">{template.versions.length} 个版本</span>
|
||||
</button>
|
||||
))}
|
||||
</aside>
|
||||
|
||||
<div ref={editorRef} className="min-w-0 scroll-mt-4 p-4 sm:p-5">
|
||||
<div className="mb-4 text-[12px] font-bold text-[#0050cb] md:hidden">正在编辑:{selectedTemplate?.name || '新建模板'}</div>
|
||||
{selectedTemplate && (
|
||||
<div className="mb-4 flex flex-wrap items-center gap-2 border-b border-[#eeeeee] pb-3">
|
||||
{selectedTemplate.versions.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setVersionId(item.id)
|
||||
setDefinition(clone(item.definition))
|
||||
}}
|
||||
className={`h-8 border px-3 text-[12px] font-bold ${versionId === item.id ? 'border-[#0050cb] bg-[#f1f4ff] text-[#0050cb]' : 'border-[#e2e2e2] text-[#5f5e5e]'}`}
|
||||
>
|
||||
v{item.version} · {item.status === 'draft' ? '草稿' : item.status === 'published' ? '已发布' : '已归档'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<AdminField label="模板代码" value={definition.code} onChange={(value) => setDefinition((current) => ({ ...current, code: value }))} disabled={Boolean(selectedTemplate)} />
|
||||
<AdminField label="模板名称" value={definition.name} onChange={(value) => setDefinition((current) => ({ ...current, name: value }))} disabled={!editable} />
|
||||
<AdminField label="看板简称" value={definition.shortName || ''} onChange={(value) => setDefinition((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) => setDefinition((current) => ({ ...current, surveyType: event.target.value as TemplateDefinition['surveyType'] }))}
|
||||
className="h-10 rounded border border-[#e2e2e2] 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) => setDefinition((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) => setDefinition((current) => ({ ...current, requiredWorkItemCount: Math.max(1, Number(value) || 1), workItemImageRequired: true }))}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<QuestionEditor definition={definition} editable={editable} onChange={setDefinition} />
|
||||
<WorkflowEditor definition={definition} editable={editable} request={request} onChange={setDefinition} />
|
||||
|
||||
<div className="mt-6 flex flex-wrap justify-end gap-2 border-t border-[#eeeeee] pt-4">
|
||||
{!editable && <button type="button" disabled={saving} onClick={cloneVersion} className="h-10 border border-[#1a1c1c] px-4 text-[13px] font-bold text-[#1a1c1c]">创建新草稿</button>}
|
||||
{editable && <button type="button" disabled={saving} onClick={save} className="h-10 border border-[#1a1c1c] px-4 text-[13px] font-bold text-[#1a1c1c] disabled:opacity-50">保存草稿</button>}
|
||||
{editable && versionId && <button type="button" disabled={saving} onClick={publish} className="h-10 bg-[#0050cb] px-4 text-[13px] font-bold text-white disabled:opacity-50">发布至 {month}</button>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function QuestionEditor({
|
||||
definition,
|
||||
editable,
|
||||
onChange,
|
||||
}: {
|
||||
definition: TemplateDefinition
|
||||
editable: boolean
|
||||
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>
|
||||
{editable && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange({
|
||||
...definition,
|
||||
questions: [...definition.questions, {
|
||||
id: `score_${definition.questions.length + 1}`,
|
||||
title: `评分项 ${definition.questions.length + 1}`,
|
||||
description: '',
|
||||
maxScore: definition.questionMaxScore || 20,
|
||||
}],
|
||||
})}
|
||||
className="h-9 border border-[#e2e2e2] px-3 text-[12px] font-bold text-[#1a1c1c]"
|
||||
>
|
||||
添加评分项
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-3 grid gap-2">
|
||||
{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>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function WorkflowEditor({
|
||||
definition,
|
||||
editable,
|
||||
request,
|
||||
onChange,
|
||||
}: {
|
||||
definition: TemplateDefinition
|
||||
editable: boolean
|
||||
request: RequestFn
|
||||
onChange: (definition: TemplateDefinition) => void
|
||||
}) {
|
||||
const updateStages = (stages: StageDraft[]) => onChange({
|
||||
...definition,
|
||||
workflow: { ...definition.workflow, stages: stages.map((stage, index) => ({ ...stage, order: index })) },
|
||||
})
|
||||
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">
|
||||
<div>
|
||||
<h3 className="text-[14px] 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>}
|
||||
</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>
|
||||
<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]">
|
||||
<select
|
||||
value={reviewer.source}
|
||||
disabled={!editable}
|
||||
onChange={(event) => updateStages(stages.map((item, index) => index === stageIndex ? {
|
||||
...item,
|
||||
reviewers: item.reviewers.map((entry, entryIndex) => entryIndex === reviewerIndex ? {
|
||||
source: event.target.value as ReviewerSource,
|
||||
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]"
|
||||
>
|
||||
<option value="self">本人</option>
|
||||
<option value="direct_manager">直属主管</option>
|
||||
<option value="fixed_employee">固定员工</option>
|
||||
<option value="manual_selection">发起时选择</option>
|
||||
</select>
|
||||
{reviewer.source === 'fixed_employee' ? (
|
||||
<FixedReviewerPicker
|
||||
value={reviewer}
|
||||
disabled={!editable}
|
||||
request={request}
|
||||
onChange={(value) => updateStages(stages.map((item, index) => index === stageIndex ? {
|
||||
...item,
|
||||
reviewers: item.reviewers.map((entry, entryIndex) => entryIndex === reviewerIndex ? value : entry),
|
||||
} : 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]" />
|
||||
)}
|
||||
{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>}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="mt-4 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}
|
||||
onChange={(event) => onChange({
|
||||
...definition,
|
||||
workflow: {
|
||||
...definition.workflow,
|
||||
scoring: event.target.value === 'final_reviewer'
|
||||
? { mode: 'final_reviewer', stageKey: stages[stages.length - 1]?.key || '', reviewerSource: stages[stages.length - 1]?.reviewers[0]?.source || 'manual_selection' }
|
||||
: { 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]"
|
||||
>
|
||||
<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]">
|
||||
{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]">
|
||||
{(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>
|
||||
)
|
||||
}
|
||||
|
||||
function FixedReviewerPicker({
|
||||
value,
|
||||
disabled,
|
||||
request,
|
||||
onChange,
|
||||
}: {
|
||||
value: ReviewerDraft
|
||||
disabled: boolean
|
||||
request: RequestFn
|
||||
onChange: (value: ReviewerDraft) => void
|
||||
}) {
|
||||
const [search, setSearch] = useState('')
|
||||
const [items, setItems] = useState<Array<{ id: string; displayName: string; departmentName?: string }>>([])
|
||||
|
||||
useEffect(() => {
|
||||
if (disabled || search.trim().length < 1) {
|
||||
setItems([])
|
||||
return
|
||||
}
|
||||
const timer = window.setTimeout(async () => {
|
||||
try {
|
||||
setItems(await request(`/employees?purpose=evaluator&limit=20&search=${encodeURIComponent(search.trim())}`))
|
||||
} catch {
|
||||
setItems([])
|
||||
}
|
||||
}, 250)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [disabled, request, search])
|
||||
|
||||
return (
|
||||
<div className="relative min-w-0">
|
||||
<input
|
||||
value={search || value.employeeName || ''}
|
||||
disabled={disabled}
|
||||
onChange={(event) => {
|
||||
setSearch(event.target.value)
|
||||
onChange({ source: 'fixed_employee', label: '固定员工' })
|
||||
}}
|
||||
placeholder="搜索固定评分人"
|
||||
className="h-9 w-full rounded border border-[#e2e2e2] px-2 text-[12px] outline-none 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)]">
|
||||
{items.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onChange({ source: 'fixed_employee', label: '固定员工', employeeId: item.id, employeeName: item.displayName })
|
||||
setSearch('')
|
||||
setItems([])
|
||||
}}
|
||||
className="block 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>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AdminField({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
type = 'text',
|
||||
disabled = false,
|
||||
}: {
|
||||
label: string
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
type?: string
|
||||
disabled?: boolean
|
||||
}) {
|
||||
return (
|
||||
<label className="grid gap-1 text-[12px] font-semibold text-[#5f5e5e]">
|
||||
{label}
|
||||
<input
|
||||
type={type}
|
||||
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]"
|
||||
/>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
@ -14,6 +14,7 @@ import {
|
||||
calculatePerformanceSurveyWorkItemProgress,
|
||||
} from '@/lib/performance-survey-response-progress'
|
||||
import { groupVisualScoresByEvaluator } from '@/lib/performance-survey-result-grouping'
|
||||
import { PerformanceSurveyAdminConfig } from '@/app/performance-survey/PerformanceSurveyAdminConfig'
|
||||
|
||||
type ApiState<T> = {
|
||||
loading: boolean
|
||||
@ -52,6 +53,8 @@ type DepartmentOption = {
|
||||
}
|
||||
|
||||
type Template = {
|
||||
templateVersionId?: string
|
||||
templateVersion?: number
|
||||
code: string
|
||||
templateVariant?: 'with_copy' | 'without_copy'
|
||||
templateVariantName?: string
|
||||
@ -84,6 +87,25 @@ type Template = {
|
||||
trimmedNote?: string
|
||||
belowBand?: string
|
||||
questions: Array<{ id: string; title: string; description?: string; maxScore?: number }>
|
||||
workflow?: {
|
||||
stages: Array<{
|
||||
key: string
|
||||
label: string
|
||||
order: number
|
||||
reviewers: Array<{
|
||||
source: 'self' | 'direct_manager' | 'fixed_employee' | 'manual_selection'
|
||||
label: string
|
||||
employeeId?: string
|
||||
employeeName?: string
|
||||
}>
|
||||
}>
|
||||
scoring: {
|
||||
mode: 'final_reviewer' | 'average_reviewers'
|
||||
stageKey?: string
|
||||
reviewerSource?: string
|
||||
stageKeys?: string[]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type VisualCaseDraft = {
|
||||
@ -117,20 +139,6 @@ const DINGTALK_PERFORMANCE_SESSION_EXPIRED_EVENT = 'performance-survey:dingtalk-
|
||||
const PERFORMANCE_SURVEY_MAX_IMAGE_COUNT = 60
|
||||
const PERFORMANCE_SURVEY_MAX_IMAGE_BYTES = 200 * 1024 * 1024
|
||||
const DEFAULT_VISUAL_CASE_COUNT = 3
|
||||
const AUTOMATIC_WORK_COOPERATION_DEPARTMENTS = new Set(['品牌创意A部', '品牌创意B部', '综合支持部'])
|
||||
const GUANSHI_DINGTALK_USER_ID = '17642061233583361'
|
||||
|
||||
function usesAutomaticWorkCooperationEvaluators(templateCode: string, employee: Employee | null) {
|
||||
if (templateCode !== 'work_cooperation' || !employee) return false
|
||||
if (String(employee.dingtalkUserId || '').trim() === GUANSHI_DINGTALK_USER_ID) return true
|
||||
const departmentParts = String(employee.departmentPath || '')
|
||||
.split('/')
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean)
|
||||
const departmentName = String(employee.departmentName || '').trim()
|
||||
return AUTOMATIC_WORK_COOPERATION_DEPARTMENTS.has(departmentName)
|
||||
|| departmentParts.some((part) => AUTOMATIC_WORK_COOPERATION_DEPARTMENTS.has(part))
|
||||
}
|
||||
const PERFORMANCE_SURVEY_IMAGE_PROXY_HOSTS = new Set([
|
||||
's3.jiansun.vip',
|
||||
's3.yydd.ai',
|
||||
@ -782,7 +790,15 @@ function Dashboard({ me, permissionsLoading }: { me: any | null; permissionsLoad
|
||||
{tab === 'personal' && <PerformanceSurveyWorkspace canCreateSurvey={canCreateSurvey} />}
|
||||
{tab === 'public' && <PerformanceDashboardBoard view="public" />}
|
||||
{tab === 'manage' && permissionsResolved && canCreateSurvey && (
|
||||
<ManagePanel currentEmployee={me?.employee || null} />
|
||||
<ManagePanel
|
||||
currentEmployee={me?.employee || null}
|
||||
isSystemAdmin={Boolean(me?.permissions?.isSystemAdmin)}
|
||||
canSelectAnyPosition={Boolean(
|
||||
me?.permissions?.isSystemAdmin
|
||||
|| me?.permissions?.isDepartmentAdmin
|
||||
|| me?.permissions?.isLeadership,
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</main>
|
||||
<nav className={`fixed inset-x-0 bottom-0 z-30 grid h-[68px] ${tabItems.length === 3 ? 'grid-cols-3' : 'grid-cols-2'} border-t border-[#e2e2e2] bg-white sm:hidden`}>
|
||||
@ -985,7 +1001,7 @@ function PerformanceSurveyWorkspace({ canCreateSurvey }: { canCreateSurvey: bool
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
{state.data && <DashboardStats data={state.data} activeTab={activeTab} onSelectTab={selectTab} />}
|
||||
<DashboardStats data={state.data || {}} activeTab={activeTab} onSelectTab={selectTab} />
|
||||
<div
|
||||
id="performance-survey-workspace-panel"
|
||||
className="mt-4"
|
||||
@ -1020,13 +1036,16 @@ function PerformanceDashboardBoard({
|
||||
const [month, setMonth] = useState(getCurrentMonthValue())
|
||||
const [department, setDepartment] = useState('')
|
||||
const [employee, setEmployee] = useState<Employee | null>(null)
|
||||
const [positionGroupCode, setPositionGroupCode] = useState('')
|
||||
const [itemPage, setItemPage] = useState(1)
|
||||
const [detailRequest, setDetailRequest] = useState<{
|
||||
month: string
|
||||
employeeId: string
|
||||
templateCode: string
|
||||
positionGroupCode?: string
|
||||
} | null>(null)
|
||||
const publicDepartmentsPath = view === 'public'
|
||||
? `/departments?purpose=dashboard&month=${encodeURIComponent(month)}`
|
||||
? `/departments?purpose=dashboard&month=${encodeURIComponent(month)}${positionGroupCode ? `&positionGroupCode=${encodeURIComponent(positionGroupCode)}` : ''}`
|
||||
: null
|
||||
const departments = useApi<DepartmentOption[]>(publicDepartmentsPath, [publicDepartmentsPath])
|
||||
const dashboardPath = useMemo(() => {
|
||||
@ -1035,21 +1054,36 @@ function PerformanceDashboardBoard({
|
||||
if (month) params.set('month', month)
|
||||
if (department) params.set('department', department)
|
||||
if (employee?.id) params.set('employeeId', employee.id)
|
||||
if (positionGroupCode) params.set('positionGroupCode', positionGroupCode)
|
||||
params.set('itemPage', String(itemPage))
|
||||
const query = params.toString()
|
||||
return `/dashboard${query ? `?${query}` : ''}`
|
||||
}, [view, month, department, employee?.id])
|
||||
}, [view, month, department, employee?.id, positionGroupCode, itemPage])
|
||||
const dashboard = useApi<any>(dashboardPath, [dashboardPath])
|
||||
const templates = dashboard.data?.templates || []
|
||||
const permissions = dashboard.data?.permissions || {}
|
||||
const personalRows = dashboard.data?.personal?.rows || []
|
||||
const publicRows = (dashboard.data?.public?.rows || []).filter((row: any) => row.hasData)
|
||||
const publicRows = dashboard.data?.public?.rows || []
|
||||
const positionGroups = dashboard.data?.positionGroups || []
|
||||
const selectedPositionGroup = dashboard.data?.selectedPositionGroup || null
|
||||
const positionMembership = dashboard.data?.positionMembership || null
|
||||
const templatePager = dashboard.data?.templatePager || { page: 1, totalPages: 1, totalItems: 0, start: 0, end: 0 }
|
||||
|
||||
return (
|
||||
<section className="mb-5 space-y-4">
|
||||
{view === 'public' && (
|
||||
<div className="border-b border-[#e2e2e2] pb-5">
|
||||
<div className="grid gap-3 sm:grid-cols-[auto_150px_auto_minmax(220px,0.8fr)_minmax(260px,1fr)_auto] sm:items-center">
|
||||
<div className="hidden text-[13px] font-semibold text-[#5f5e5e] sm:block">统计周期</div>
|
||||
<div className="grid gap-3 md:grid-cols-[minmax(190px,0.8fr)_150px_minmax(220px,0.9fr)_minmax(240px,1fr)_auto] md:items-center">
|
||||
<PositionGroupSelect
|
||||
groups={positionGroups}
|
||||
value={positionGroupCode || selectedPositionGroup?.code || ''}
|
||||
onChange={(value) => {
|
||||
setPositionGroupCode(value)
|
||||
setItemPage(1)
|
||||
setDepartment('')
|
||||
setEmployee(null)
|
||||
}}
|
||||
/>
|
||||
<input
|
||||
type="month"
|
||||
value={month}
|
||||
@ -1079,6 +1113,29 @@ function PerformanceDashboardBoard({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{dashboard.data && (
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-[#eeeeee] pb-3">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-[14px] font-bold text-[#1a1c1c]">
|
||||
{selectedPositionGroup?.name || (positionMembership?.status === 'conflict' ? '岗位配置冲突' : '尚未匹配考核岗位')}
|
||||
</div>
|
||||
<div className="mt-0.5 text-[12px] text-[#787777]">
|
||||
{selectedPositionGroup?.status === 'ready'
|
||||
? `${templatePager.totalItems} 个考核项`
|
||||
: selectedPositionGroup
|
||||
? '待管理员完成岗位规则与考核项配置'
|
||||
: positionMembership?.status === 'conflict'
|
||||
? `同时命中:${(positionMembership.conflictGroupNames || []).join('、')}`
|
||||
: '当前人员没有可用的岗位配置'}
|
||||
</div>
|
||||
</div>
|
||||
<TemplatePager
|
||||
pager={templatePager}
|
||||
onChange={setItemPage}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{dashboard.loading && (
|
||||
<div className="border border-[#e2e2e2] bg-white px-5 py-8 text-sm font-semibold text-[#5f5e5e]">
|
||||
看板加载中...
|
||||
@ -1091,12 +1148,13 @@ function PerformanceDashboardBoard({
|
||||
<MonthlyPersonalLedger
|
||||
rows={personalRows}
|
||||
templates={templates}
|
||||
onOpenDetail={setDetailRequest}
|
||||
onOpenDetail={(value) => setDetailRequest({ ...value, positionGroupCode: selectedPositionGroup?.code })}
|
||||
onQuickCreate={canCreateSurvey ? ({ month: targetMonth, templateCode }) => {
|
||||
const params = new URLSearchParams()
|
||||
params.set('tab', 'manage')
|
||||
params.set('prefillMonth', targetMonth)
|
||||
params.set('prefillTemplate', templateCode)
|
||||
if (selectedPositionGroup?.code) params.set('prefillPositionGroup', selectedPositionGroup.code)
|
||||
router.push(`/performance-survey?${params.toString()}`)
|
||||
} : undefined}
|
||||
/>
|
||||
@ -1105,7 +1163,7 @@ function PerformanceDashboardBoard({
|
||||
rows={publicRows}
|
||||
templates={templates}
|
||||
canOpenPublicDetail={Boolean(permissions.canOpenPublicDetail)}
|
||||
onOpenDetail={setDetailRequest}
|
||||
onOpenDetail={(value) => setDetailRequest({ ...value, positionGroupCode: selectedPositionGroup?.code })}
|
||||
/>
|
||||
)}
|
||||
<MonthlyScoreDetailModal
|
||||
@ -1118,6 +1176,71 @@ function PerformanceDashboardBoard({
|
||||
)
|
||||
}
|
||||
|
||||
function PositionGroupSelect({
|
||||
groups,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
groups: Array<{ code: string; name: string; status: string; templateCount: number }>
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
}) {
|
||||
return (
|
||||
<label className="grid min-w-0 gap-1">
|
||||
<span className="sr-only">考核岗位</span>
|
||||
<select
|
||||
value={value}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
className="h-10 min-w-0 rounded border border-[#e2e2e2] bg-white px-3 text-[13px] font-semibold text-[#1a1c1c] outline-none transition-colors focus:border-[#0050cb]"
|
||||
>
|
||||
<option value="">选择考核岗位</option>
|
||||
{groups.map((group) => (
|
||||
<option key={group.code} value={group.code}>
|
||||
{group.name}{group.status === 'ready' ? ` · ${group.templateCount}项` : ' · 待配置'}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
function TemplatePager({
|
||||
pager,
|
||||
onChange,
|
||||
}: {
|
||||
pager: { page: number; totalPages: number; totalItems: number; start: number; end: number }
|
||||
onChange: (page: number) => void
|
||||
}) {
|
||||
if (pager.totalItems <= 4) return null
|
||||
return (
|
||||
<div className="flex h-9 shrink-0 items-center border border-[#e2e2e2] bg-white" aria-label="考核项分页">
|
||||
<button
|
||||
type="button"
|
||||
aria-label="上一组考核项"
|
||||
title="上一组"
|
||||
disabled={pager.page <= 1}
|
||||
onClick={() => onChange(Math.max(1, pager.page - 1))}
|
||||
className="flex h-9 w-9 items-center justify-center border-r border-[#eeeeee] text-[16px] font-bold text-[#1a1c1c] hover:bg-[#f7f7f7] disabled:cursor-not-allowed disabled:text-[#b8b8b8]"
|
||||
>
|
||||
←
|
||||
</button>
|
||||
<span className="min-w-[88px] px-3 text-center text-[12px] font-semibold tabular-nums text-[#5f5e5e]">
|
||||
{pager.start}-{pager.end} / {pager.totalItems}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="下一组考核项"
|
||||
title="下一组"
|
||||
disabled={pager.page >= pager.totalPages}
|
||||
onClick={() => onChange(Math.min(pager.totalPages, pager.page + 1))}
|
||||
className="flex h-9 w-9 items-center justify-center border-l border-[#eeeeee] text-[16px] font-bold text-[#1a1c1c] hover:bg-[#f7f7f7] disabled:cursor-not-allowed disabled:text-[#b8b8b8]"
|
||||
>
|
||||
→
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function MonthlyPersonalLedger({
|
||||
rows,
|
||||
templates,
|
||||
@ -1465,7 +1588,7 @@ function MonthlyScoreDetailModal({
|
||||
request,
|
||||
onClose,
|
||||
}: {
|
||||
request: { month: string; employeeId: string; templateCode: string } | null
|
||||
request: { month: string; employeeId: string; templateCode: string; positionGroupCode?: string } | null
|
||||
onClose: () => void
|
||||
}) {
|
||||
const [portalReady, setPortalReady] = useState(false)
|
||||
@ -1473,7 +1596,12 @@ function MonthlyScoreDetailModal({
|
||||
const closeButtonRef = useRef<HTMLButtonElement | null>(null)
|
||||
const detailPath = useMemo(() => {
|
||||
if (!request) return null
|
||||
const params = new URLSearchParams(request)
|
||||
const params = new URLSearchParams({
|
||||
month: request.month,
|
||||
employeeId: request.employeeId,
|
||||
templateCode: request.templateCode,
|
||||
})
|
||||
if (request.positionGroupCode) params.set('positionGroupCode', request.positionGroupCode)
|
||||
return `/dashboard/detail?${params.toString()}`
|
||||
}, [request])
|
||||
const detail = useApi<any>(detailPath, [detailPath])
|
||||
@ -2615,29 +2743,62 @@ function DepartmentFilterTree({
|
||||
)
|
||||
}
|
||||
|
||||
function ManagePanel({ currentEmployee }: { currentEmployee: Employee | null }) {
|
||||
const templates = useApi<Template[]>('/templates', [])
|
||||
function ManagePanel({
|
||||
currentEmployee,
|
||||
isSystemAdmin,
|
||||
canSelectAnyPosition,
|
||||
}: {
|
||||
currentEmployee: Employee | null
|
||||
isSystemAdmin: boolean
|
||||
canSelectAnyPosition: boolean
|
||||
}) {
|
||||
const departments = useApi<DepartmentOption[]>('/departments?purpose=evaluator', [])
|
||||
const surveys = useApi<any>('/surveys', [])
|
||||
const [message, setMessage] = useState<string | null>(null)
|
||||
const [workspace, setWorkspace] = useState<'launch' | 'positions' | 'templates'>('launch')
|
||||
|
||||
return (
|
||||
<div className="grid gap-4">
|
||||
<CreateSurveyForm
|
||||
templates={templates.data || []}
|
||||
departments={departments.data || []}
|
||||
currentEmployee={currentEmployee}
|
||||
onCreated={async () => {
|
||||
setMessage('已发布调研')
|
||||
await surveys.refresh()
|
||||
}}
|
||||
/>
|
||||
{isSystemAdmin && (
|
||||
<div className="flex h-10 w-fit items-center border border-[#e2e2e2] bg-white p-1">
|
||||
{([
|
||||
['launch', '发起调研'],
|
||||
['positions', '岗位配置'],
|
||||
['templates', '模板管理'],
|
||||
] as const).map(([id, label]) => (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
onClick={() => setWorkspace(id)}
|
||||
className={`h-8 px-4 text-[12px] font-bold ${workspace === id ? 'bg-[#1a1c1c] text-white' : 'text-[#5f5e5e] hover:bg-[#f7f7f7]'}`}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{workspace === 'launch' ? (
|
||||
<CreateSurveyForm
|
||||
departments={departments.data || []}
|
||||
currentEmployee={currentEmployee}
|
||||
canSelectAnyPosition={canSelectAnyPosition}
|
||||
onCreated={async () => {
|
||||
setMessage('已发布调研')
|
||||
await surveys.refresh()
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<PerformanceSurveyAdminConfig
|
||||
mode={workspace}
|
||||
request={apiRequest}
|
||||
/>
|
||||
)}
|
||||
{message && (
|
||||
<div className="border border-[#b3c5ff] bg-[#f8faff] px-4 py-3 text-sm font-semibold text-[#0050cb]">
|
||||
{message}
|
||||
</div>
|
||||
)}
|
||||
<section className="mt-4 border-t border-[#e2e2e2] pt-6" aria-labelledby="created-survey-list-title">
|
||||
{workspace === 'launch' && <section className="mt-4 border-t border-[#e2e2e2] pt-6" aria-labelledby="created-survey-list-title">
|
||||
<div className="mb-4 flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<h2 id="created-survey-list-title" className="text-[18px] font-bold text-[#1a1c1c]">我发起的</h2>
|
||||
@ -2660,7 +2821,7 @@ function ManagePanel({ currentEmployee }: { currentEmployee: Employee | null })
|
||||
resultBackHref="/performance-survey?tab=manage"
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
</section>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -2694,24 +2855,26 @@ function TemplateStatsPanel({ items }: { items: any[] }) {
|
||||
}
|
||||
|
||||
function CreateSurveyForm({
|
||||
templates,
|
||||
departments,
|
||||
currentEmployee,
|
||||
canSelectAnyPosition,
|
||||
onCreated,
|
||||
}: {
|
||||
templates: Template[]
|
||||
departments: DepartmentOption[]
|
||||
currentEmployee: Employee | null
|
||||
canSelectAnyPosition: boolean
|
||||
onCreated: () => Promise<void>
|
||||
}) {
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const prefillMonth = searchParams.get('prefillMonth') || ''
|
||||
const prefillTemplate = searchParams.get('prefillTemplate') || ''
|
||||
const prefillPositionGroup = searchParams.get('prefillPositionGroup') || ''
|
||||
const [title, setTitle] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
const [templateOptionKey, setTemplateOptionKey] = useState(prefillTemplate)
|
||||
const [assessmentMonth, setAssessmentMonth] = useState(prefillMonth || getCurrentMonthValue())
|
||||
const [positionGroupCode, setPositionGroupCode] = useState(prefillPositionGroup)
|
||||
const [deadlineAt, setDeadlineAt] = useState('')
|
||||
const openNow = true
|
||||
const [targetEmployees, setTargetEmployees] = useState<Employee[]>([])
|
||||
@ -2726,24 +2889,38 @@ function CreateSurveyForm({
|
||||
const [publishingLabel, setPublishingLabel] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const positionGroupsPath = `/position-groups?month=${encodeURIComponent(assessmentMonth || getCurrentMonthValue())}`
|
||||
const positionGroupsState = useApi<any>(positionGroupsPath, [positionGroupsPath])
|
||||
const availablePositionGroups = positionGroupsState.data?.groups || []
|
||||
const membershipStatus = positionGroupsState.data?.membership?.status as 'matched' | 'unmatched' | 'conflict' | undefined
|
||||
const selectedPositionGroupCode = positionGroupCode
|
||||
|| positionGroupsState.data?.membership?.groupCode
|
||||
|| ''
|
||||
const templatesPath = selectedPositionGroupCode
|
||||
? `/templates?month=${encodeURIComponent(assessmentMonth)}&positionGroupCode=${encodeURIComponent(selectedPositionGroupCode)}`
|
||||
: null
|
||||
const templatesState = useApi<Template[]>(templatesPath, [templatesPath])
|
||||
const templates = useMemo(() => templatesState.data || [], [templatesState.data])
|
||||
|
||||
useEffect(() => {
|
||||
if (prefillMonth && /^\d{4}-\d{2}$/.test(prefillMonth)) setAssessmentMonth(prefillMonth)
|
||||
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, prefillTemplate, templates])
|
||||
}, [prefillMonth, prefillPositionGroup, prefillTemplate, templates])
|
||||
|
||||
const selectedTemplate = templateOptionKey || templates[0]?.templateOptionKey || templates[0]?.code || ''
|
||||
const selectedTemplateInfo = templates.find((template) => (template.templateOptionKey || template.code) === selectedTemplate)
|
||||
const selectedTemplateCode = selectedTemplateInfo?.code || ''
|
||||
const surveyKind = selectedTemplateInfo?.surveyType || 'person_period'
|
||||
const visualTemplateSelected = isVisualTemplate(selectedTemplateInfo)
|
||||
const automaticWorkCooperationEvaluators = usesAutomaticWorkCooperationEvaluators(
|
||||
selectedTemplateCode,
|
||||
currentEmployee,
|
||||
)
|
||||
const workflowStages = selectedTemplateInfo?.workflow?.stages || []
|
||||
const requiresManualEvaluators = workflowStages.some((stage) => (
|
||||
stage.reviewers.some((reviewer) => reviewer.source === 'manual_selection')
|
||||
))
|
||||
const visualRequiredCount = Math.max(
|
||||
1,
|
||||
Number(selectedTemplateInfo?.requiredWorkItemCount || DEFAULT_VISUAL_CASE_COUNT),
|
||||
@ -2751,10 +2928,8 @@ function CreateSurveyForm({
|
||||
const effectiveTargetEmployees = useMemo(
|
||||
() => surveyKind === 'item_course'
|
||||
? []
|
||||
: visualTemplateSelected
|
||||
? (currentEmployee ? [currentEmployee] : [])
|
||||
: mergeEmployeesById(currentEmployee ? [currentEmployee] : [], targetEmployees),
|
||||
[currentEmployee, surveyKind, targetEmployees, visualTemplateSelected],
|
||||
[currentEmployee, surveyKind, targetEmployees],
|
||||
)
|
||||
const currentTargetSelected = Boolean(
|
||||
currentEmployee?.id && effectiveTargetEmployees.some((employee) => employee.id === currentEmployee.id),
|
||||
@ -2783,10 +2958,16 @@ function CreateSurveyForm({
|
||||
publishValidationIssues.push('确认考核对象')
|
||||
}
|
||||
if (
|
||||
!visualTemplateSelected
|
||||
&& !automaticWorkCooperationEvaluators
|
||||
requiresManualEvaluators
|
||||
&& evaluatorEmployees.length === 0
|
||||
) publishValidationIssues.push('至少选择 1 名评分人')
|
||||
if (!selectedPositionGroupCode) publishValidationIssues.push('选择考核岗位')
|
||||
if (!canSelectAnyPosition && membershipStatus === 'unmatched') {
|
||||
publishValidationIssues.push('联系管理员配置本人考核岗位')
|
||||
}
|
||||
if (!canSelectAnyPosition && membershipStatus === 'conflict') {
|
||||
publishValidationIssues.push('联系管理员处理本人岗位重复匹配')
|
||||
}
|
||||
if (visualTemplateSelected && currentTargetSelected) {
|
||||
const visibleVisualCases = visualCases.slice(0, visualRequiredCount)
|
||||
if (visibleVisualCases.length < visualRequiredCount) {
|
||||
@ -2835,7 +3016,7 @@ function CreateSurveyForm({
|
||||
if (surveyKind !== 'item_course' && effectiveTargetEmployees.length === 0) {
|
||||
throw new Error('请至少选择 1 个考核对象')
|
||||
}
|
||||
if (!visualTemplateSelected && !automaticWorkCooperationEvaluators && evaluatorEmployees.length === 0) {
|
||||
if (requiresManualEvaluators && evaluatorEmployees.length === 0) {
|
||||
throw new Error('请至少选择 1 名评分人')
|
||||
}
|
||||
const visualCasesToSubmit = visualCases.slice(0, visualRequiredCount)
|
||||
@ -2860,8 +3041,9 @@ function CreateSurveyForm({
|
||||
title: submitTitle,
|
||||
description,
|
||||
surveyKind,
|
||||
positionGroupCode: selectedPositionGroupCode,
|
||||
templateCode: selectedTemplateCode,
|
||||
templateVariant: selectedTemplateInfo?.templateVariant || null,
|
||||
templateVersionId: selectedTemplateInfo?.templateVersionId || null,
|
||||
assessmentMonth: selectedAssessmentMonth,
|
||||
dueAt: deadlineAt ? new Date(deadlineAt).toISOString() : null,
|
||||
openNow: visualTemplateSelected ? false : openNow,
|
||||
@ -2906,6 +3088,7 @@ function CreateSurveyForm({
|
||||
setTitle('')
|
||||
setDescription('')
|
||||
setTemplateOptionKey('')
|
||||
setPositionGroupCode('')
|
||||
setAssessmentMonth(getCurrentMonthValue())
|
||||
setDeadlineAt('')
|
||||
setTargetEmployees([])
|
||||
@ -2940,14 +3123,45 @@ function CreateSurveyForm({
|
||||
<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" />
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="text-[12px] font-semibold tracking-[0.05em] text-[#5f5e5e]">考核岗位</span>
|
||||
<select
|
||||
value={selectedPositionGroupCode}
|
||||
onChange={(event) => {
|
||||
setPositionGroupCode(event.target.value)
|
||||
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]"
|
||||
>
|
||||
<option value="">选择考核岗位</option>
|
||||
{availablePositionGroups.map((group: any) => (
|
||||
<option key={group.code} value={group.code} disabled={group.status !== 'ready'}>
|
||||
{group.name}{group.status === 'ready' ? ` · ${group.templateCount}项` : ' · 待配置'}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{!canSelectAnyPosition && positionGroupsState.data?.membership?.status === 'conflict' && (
|
||||
<div className="text-[12px] font-semibold text-[#b42318]">
|
||||
当前人员同时命中多个岗位:{(positionGroupsState.data.membership.conflictGroupNames || []).join('、')}
|
||||
</div>
|
||||
)}
|
||||
{!canSelectAnyPosition && positionGroupsState.data?.membership?.status === 'unmatched' && (
|
||||
<div className="text-[12px] font-semibold text-[#b42318]">
|
||||
当前人员尚未匹配考核岗位,请联系系统管理员完成岗位配置
|
||||
</div>
|
||||
)}
|
||||
</label>
|
||||
<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>
|
||||
<select
|
||||
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]"
|
||||
>
|
||||
{templates.length === 0 && <option value="">该岗位暂无可用考核项</option>}
|
||||
{templates.map((template) => (
|
||||
<option key={template.templateOptionKey || template.code} value={template.templateOptionKey || template.code}>
|
||||
{template.templateVariantName || getTemplateDisplayName(template)}
|
||||
@ -3001,19 +3215,15 @@ function CreateSurveyForm({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{visualTemplateSelected ? (
|
||||
<div className="border border-[#dce5f3] bg-[#f8faff] px-3 py-3 text-[12px] font-semibold leading-5 text-[#42526e]">
|
||||
视觉评分固定考核当前账户本人,不能添加其他被考核人。
|
||||
</div>
|
||||
) : (
|
||||
<EmployeePicker
|
||||
title="添加其他被考核人(可选)"
|
||||
purpose="target"
|
||||
selected={targetEmployees}
|
||||
excludedIds={currentEmployee?.id ? [currentEmployee.id] : []}
|
||||
onChange={setTargetEmployees}
|
||||
/>
|
||||
)}
|
||||
<EmployeePicker
|
||||
title="添加同岗位被考核人(可选)"
|
||||
purpose="target"
|
||||
positionGroupCode={selectedPositionGroupCode}
|
||||
assessmentMonth={assessmentMonth}
|
||||
selected={targetEmployees}
|
||||
excludedIds={currentEmployee?.id ? [currentEmployee.id] : []}
|
||||
onChange={setTargetEmployees}
|
||||
/>
|
||||
{delegatedTargetCount > 0 && (
|
||||
<div className="text-[12px] font-semibold text-[#0050cb]">
|
||||
将向 {delegatedTargetCount} 位被考核人发送钉钉确认
|
||||
@ -3032,24 +3242,23 @@ function CreateSurveyForm({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{visualTemplateSelected ? (
|
||||
{!requiresManualEvaluators ? (
|
||||
<div className="border border-[#dce5f3] bg-[#f8faff] px-4 py-4">
|
||||
<div className="text-[12px] font-semibold tracking-[0.05em] text-[#5f5e5e]">评分人员</div>
|
||||
<div className="mt-2 text-[14px] font-bold text-[#1a1c1c]">系统自动选择元泽和被考核人的直属主管</div>
|
||||
<p className="mt-2 text-[12px] leading-5 text-[#5f5e5e]">被考核人先完成自评,之后才会通知元泽和主管;最终评分以元泽提交的结果为准。</p>
|
||||
<div className="text-[12px] font-semibold tracking-[0.05em] text-[#5f5e5e]">评审流程</div>
|
||||
<div className="mt-2 grid gap-2">
|
||||
{workflowStages.map((stage) => (
|
||||
<div key={stage.key} className="text-[13px] font-semibold text-[#1a1c1c]">
|
||||
{stage.order + 1}. {stage.label} · {stage.reviewers.map((reviewer) => reviewer.employeeName || reviewer.label).join('、')}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className="mt-2 text-[12px] leading-5 text-[#5f5e5e]">评分人员按已发布模板解析,前一阶段完成后自动开放下一阶段。</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{automaticWorkCooperationEvaluators && (
|
||||
<div className="border border-[#dce5f3] bg-[#f8faff] px-4 py-4">
|
||||
<div className="text-[12px] font-semibold tracking-[0.05em] text-[#5f5e5e]">默认评分人员</div>
|
||||
<div className="mt-2 text-[14px] font-bold text-[#1a1c1c]">系统按被考核人职级自动选择</div>
|
||||
<p className="mt-2 text-[12px] leading-5 text-[#5f5e5e]">未手动选择时,P级人员由直属主管评分,M级人员由元泽评分;观世按M级人员处理。</p>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<EmployeePicker
|
||||
title={automaticWorkCooperationEvaluators ? '手动调整评分人员(可选)' : '评分人员'}
|
||||
title="评分人员"
|
||||
purpose="evaluator"
|
||||
selected={evaluatorEmployees}
|
||||
excludedIds={currentEmployee?.id ? [currentEmployee.id] : []}
|
||||
@ -3407,6 +3616,8 @@ function VisualCaseDraftEditor({
|
||||
function EmployeePicker({
|
||||
title,
|
||||
purpose,
|
||||
positionGroupCode,
|
||||
assessmentMonth,
|
||||
selected,
|
||||
excludedIds = [],
|
||||
onChange,
|
||||
@ -3415,6 +3626,8 @@ function EmployeePicker({
|
||||
}: {
|
||||
title: string
|
||||
purpose?: 'target' | 'evaluator'
|
||||
positionGroupCode?: string
|
||||
assessmentMonth?: string
|
||||
selected: Employee[]
|
||||
excludedIds?: string[]
|
||||
onChange: (employees: Employee[]) => void
|
||||
@ -3439,7 +3652,7 @@ function EmployeePicker({
|
||||
setOpen(false)
|
||||
return
|
||||
}
|
||||
const cacheKey = `${purpose || 'default'}:${trimmedKeyword}`
|
||||
const cacheKey = `${purpose || 'default'}:${positionGroupCode || 'all'}:${assessmentMonth || ''}:${trimmedKeyword}`
|
||||
const cached = cacheRef.current.get(cacheKey)
|
||||
if (cached) {
|
||||
setItems(cached)
|
||||
@ -3456,6 +3669,8 @@ function EmployeePicker({
|
||||
search: trimmedKeyword,
|
||||
limit: '50',
|
||||
...(purpose ? { purpose } : {}),
|
||||
...(positionGroupCode ? { positionGroupCode } : {}),
|
||||
...(assessmentMonth ? { month: assessmentMonth } : {}),
|
||||
})
|
||||
const data = await apiRequest<Employee[]>(`/employees?${params.toString()}`)
|
||||
cacheRef.current.set(cacheKey, data)
|
||||
@ -3469,7 +3684,7 @@ function EmployeePicker({
|
||||
}, 250)
|
||||
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [keyword, purpose])
|
||||
}, [keyword, purpose, positionGroupCode, assessmentMonth])
|
||||
|
||||
useEffect(() => {
|
||||
const closeWhenOutside = (event: MouseEvent) => {
|
||||
|
||||
@ -374,7 +374,7 @@ describe('performance survey notifications', () => {
|
||||
'',
|
||||
'**评价对象:** 视觉同事 ',
|
||||
'',
|
||||
'> 请先完成自评;提交后系统才会通知主管和元泽评分',
|
||||
'> 请先完成自评;提交后系统才会通知主管和终审人评分',
|
||||
].join('\n'),
|
||||
}),
|
||||
select: { id: true },
|
||||
|
||||
134
lib/__tests__/performance-survey-position-config.test.ts
Normal file
134
lib/__tests__/performance-survey-position-config.test.ts
Normal file
@ -0,0 +1,134 @@
|
||||
/** @jest-environment node */
|
||||
|
||||
import {
|
||||
PERFORMANCE_SURVEY_POSITION_GROUP_SEEDS,
|
||||
matchesPerformanceSurveyPositionRule,
|
||||
paginatePerformanceSurveyTemplates,
|
||||
resolvePerformanceSurveyPositionMembership,
|
||||
validatePerformanceSurveyTemplateDefinition,
|
||||
type PositionGroupRuntime,
|
||||
} from '@/lib/performance-survey-position-config'
|
||||
import { DEFAULT_PERFORMANCE_SURVEY_TEMPLATES } from '@/lib/performance-survey-templates'
|
||||
|
||||
function group(input: Partial<PositionGroupRuntime> & Pick<PositionGroupRuntime, 'id' | 'code' | 'name'>): PositionGroupRuntime {
|
||||
return {
|
||||
sortOrder: 0,
|
||||
isActive: true,
|
||||
status: 'ready',
|
||||
planId: 'plan-1',
|
||||
planVersion: 1,
|
||||
effectiveMonth: '2026-07',
|
||||
rules: [],
|
||||
templates: [],
|
||||
...input,
|
||||
}
|
||||
}
|
||||
|
||||
describe('performance survey position configuration', () => {
|
||||
test('预置八个岗位组且代码稳定唯一', () => {
|
||||
expect(PERFORMANCE_SURVEY_POSITION_GROUP_SEEDS).toHaveLength(8)
|
||||
expect(new Set(PERFORMANCE_SURVEY_POSITION_GROUP_SEEDS.map((item) => item.code)).size).toBe(8)
|
||||
})
|
||||
|
||||
test('单条规则内部门和职位按 AND 匹配,部门路径支持子部门', () => {
|
||||
const rule = { departmentPathPrefix: '集团/品牌中心', positionTitle: 'AI策划' }
|
||||
expect(matchesPerformanceSurveyPositionRule({
|
||||
departmentPath: '集团/品牌中心/品牌创意A部',
|
||||
positionTitle: 'AI策划',
|
||||
}, rule)).toBe(true)
|
||||
expect(matchesPerformanceSurveyPositionRule({
|
||||
departmentPath: '集团/综合中心',
|
||||
positionTitle: 'AI策划',
|
||||
}, rule)).toBe(false)
|
||||
expect(matchesPerformanceSurveyPositionRule({
|
||||
departmentPath: '集团/品牌中心/品牌创意A部',
|
||||
positionTitle: '品牌设计师',
|
||||
}, rule)).toBe(false)
|
||||
})
|
||||
|
||||
test('同组多条规则按 OR 匹配,跨组重复命中明确返回冲突', () => {
|
||||
const creative = group({
|
||||
id: 'creative',
|
||||
code: 'creative',
|
||||
name: '创意',
|
||||
rules: [
|
||||
{ departmentPathPrefix: '集团/创意一部', positionTitle: 'AI策划' },
|
||||
{ departmentPathPrefix: '集团/创意二部', positionTitle: 'AI策划' },
|
||||
],
|
||||
})
|
||||
const duplicate = group({
|
||||
id: 'duplicate',
|
||||
code: 'duplicate',
|
||||
name: '重复组',
|
||||
rules: [{ positionTitle: 'AI策划' }],
|
||||
})
|
||||
const employee = { departmentPath: '集团/创意二部', positionTitle: 'AI策划' }
|
||||
|
||||
expect(resolvePerformanceSurveyPositionMembership(employee, [creative])).toMatchObject({
|
||||
status: 'matched',
|
||||
group: { code: 'creative' },
|
||||
})
|
||||
expect(resolvePerformanceSurveyPositionMembership(employee, [creative, duplicate])).toMatchObject({
|
||||
status: 'conflict',
|
||||
group: null,
|
||||
})
|
||||
expect(resolvePerformanceSurveyPositionMembership({
|
||||
departmentPath: '集团/财务部',
|
||||
positionTitle: '会计',
|
||||
}, [creative])).toMatchObject({ status: 'unmatched', group: null })
|
||||
})
|
||||
|
||||
test('看板考核项固定每页最多四项并钳制越界页码', () => {
|
||||
const items = Array.from({ length: 9 }, (_, index) => `item-${index + 1}`)
|
||||
expect(paginatePerformanceSurveyTemplates(items, 1)).toEqual({
|
||||
items: ['item-1', 'item-2', 'item-3', 'item-4'],
|
||||
pager: { page: 1, pageSize: 4, totalPages: 3, totalItems: 9, start: 1, end: 4 },
|
||||
})
|
||||
expect(paginatePerformanceSurveyTemplates(items, 2)).toMatchObject({
|
||||
items: ['item-5', 'item-6', 'item-7', 'item-8'],
|
||||
pager: { page: 2, start: 5, end: 8 },
|
||||
})
|
||||
expect(paginatePerformanceSurveyTemplates(items, 99)).toMatchObject({
|
||||
items: ['item-9'],
|
||||
pager: { page: 3, start: 9, end: 9 },
|
||||
})
|
||||
expect(paginatePerformanceSurveyTemplates([], 3).pager).toEqual({
|
||||
page: 1,
|
||||
pageSize: 4,
|
||||
totalPages: 1,
|
||||
totalItems: 0,
|
||||
start: 0,
|
||||
end: 0,
|
||||
})
|
||||
})
|
||||
|
||||
test('一个完整考核项也允许发布,不要求凑满四项', () => {
|
||||
const template = structuredClone(DEFAULT_PERFORMANCE_SURVEY_TEMPLATES[0])
|
||||
template.questions = [template.questions[0]]
|
||||
expect(() => validatePerformanceSurveyTemplateDefinition(template)).not.toThrow()
|
||||
})
|
||||
|
||||
test('拒绝空题目、重复阶段顺序和不唯一的终审计分人', () => {
|
||||
const empty = structuredClone(DEFAULT_PERFORMANCE_SURVEY_TEMPLATES[0])
|
||||
empty.questions = []
|
||||
expect(() => validatePerformanceSurveyTemplateDefinition(empty)).toThrow('至少需要 1 个评分项')
|
||||
|
||||
const duplicateOrder = structuredClone(DEFAULT_PERFORMANCE_SURVEY_TEMPLATES[0])
|
||||
duplicateOrder.workflow!.stages.push({
|
||||
key: 'another',
|
||||
label: '第二阶段',
|
||||
order: duplicateOrder.workflow!.stages[0].order,
|
||||
reviewers: [{ source: 'self', label: '本人' }],
|
||||
})
|
||||
expect(() => validatePerformanceSurveyTemplateDefinition(duplicateOrder)).toThrow('评审阶段顺序重复')
|
||||
|
||||
const ambiguousFinal = structuredClone(DEFAULT_PERFORMANCE_SURVEY_TEMPLATES[3])
|
||||
ambiguousFinal.workflow!.stages[1].reviewers.push({
|
||||
source: 'fixed_employee',
|
||||
label: '另一位终审人',
|
||||
employeeId: 'employee-2',
|
||||
})
|
||||
ambiguousFinal.workflow!.stages[1].reviewers[1].employeeId = 'employee-1'
|
||||
expect(() => validatePerformanceSurveyTemplateDefinition(ambiguousFinal)).toThrow('终审计分人员必须唯一')
|
||||
})
|
||||
})
|
||||
@ -21,14 +21,20 @@ import {
|
||||
getPerformanceSurveyAccountProfileWhere,
|
||||
} from '@/lib/performance-survey-report-sync'
|
||||
import {
|
||||
DEFAULT_PERFORMANCE_SURVEY_TEMPLATES,
|
||||
getPerformanceSurveyTemplate,
|
||||
listPerformanceSurveyTemplates,
|
||||
} from '@/lib/performance-survey-templates'
|
||||
import {
|
||||
getPerformanceSurveyPositionGroupByCode,
|
||||
getPerformanceSurveyPositionGroupForEmployee,
|
||||
listPerformanceSurveyPositionGroups,
|
||||
} from '@/lib/performance-survey-position-config'
|
||||
import { queueSurveyCreatorNotification } from '@/lib/performance-survey-notifications'
|
||||
|
||||
jest.mock('@/lib/prisma', () => ({
|
||||
prisma: {
|
||||
user: { findUnique: jest.fn(), findMany: jest.fn() },
|
||||
user: { findUnique: jest.fn(), findFirst: jest.fn(), findMany: jest.fn() },
|
||||
performanceSurvey: {
|
||||
findUnique: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
@ -56,6 +62,16 @@ jest.mock('@/lib/performance-survey-templates', () => {
|
||||
}
|
||||
})
|
||||
|
||||
jest.mock('@/lib/performance-survey-position-config', () => {
|
||||
const actual = jest.requireActual('@/lib/performance-survey-position-config')
|
||||
return {
|
||||
...actual,
|
||||
getPerformanceSurveyPositionGroupByCode: jest.fn(),
|
||||
getPerformanceSurveyPositionGroupForEmployee: jest.fn(),
|
||||
listPerformanceSurveyPositionGroups: jest.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
jest.mock('@/lib/performance-survey-report-sync', () => ({
|
||||
ensurePerformanceSurveyDailyEmployeeSyncStarted: jest.fn(),
|
||||
ensurePerformanceSurveyEmployeeProfileForUser: jest.fn(),
|
||||
@ -112,6 +128,33 @@ const baseEmployee = {
|
||||
isLeadership: false,
|
||||
}
|
||||
|
||||
function buildConfiguredPositionGroup() {
|
||||
const templates = structuredClone(DEFAULT_PERFORMANCE_SURVEY_TEMPLATES).map((template, index) => ({
|
||||
...template,
|
||||
templateVersionId: `template-version-${index + 1}`,
|
||||
templateVersion: 1,
|
||||
templateVersionStatus: 'published' as const,
|
||||
effectiveMonth: '2026-07',
|
||||
}))
|
||||
const fixedReviewer = templates.find((template) => template.code === 'visual_brand_tone')
|
||||
?.workflow?.stages.flatMap((stage) => stage.reviewers)
|
||||
.find((reviewer) => reviewer.source === 'fixed_employee')
|
||||
if (fixedReviewer) fixedReviewer.employeeId = 'employee-yuanzhe'
|
||||
return {
|
||||
id: 'position-group-brand',
|
||||
code: 'brand_designer',
|
||||
name: '品牌设计师',
|
||||
sortOrder: 10,
|
||||
isActive: true,
|
||||
status: 'ready' as const,
|
||||
planId: 'position-plan-1',
|
||||
planVersion: 1,
|
||||
effectiveMonth: '2026-07',
|
||||
rules: [{ departmentPathPrefix: '集团A/品牌中心', positionTitle: null }],
|
||||
templates,
|
||||
}
|
||||
}
|
||||
|
||||
function buildSurvey(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'survey-1',
|
||||
@ -119,6 +162,10 @@ function buildSurvey(overrides: Record<string, unknown> = {}) {
|
||||
description: null,
|
||||
surveyKind: 'person_period',
|
||||
templateCode: 'course_share',
|
||||
templateVersionId: 'template-version-1',
|
||||
positionGroupId: 'position-group-brand',
|
||||
positionGroupCode: 'brand_designer',
|
||||
positionGroupSnapshot: { code: 'brand_designer', name: '品牌设计师' },
|
||||
templateSnapshot: {
|
||||
code: 'course_share',
|
||||
name: '课程分享月度考核',
|
||||
@ -180,7 +227,17 @@ describe('performance survey service policies', () => {
|
||||
;(prisma.performanceSurveyTarget.findMany as jest.Mock).mockResolvedValue([])
|
||||
;(prisma.user.findMany as jest.Mock).mockReset()
|
||||
;(prisma.user.findMany as jest.Mock).mockResolvedValue([])
|
||||
;(prisma.user.findFirst as jest.Mock).mockReset()
|
||||
;(prisma.user.findFirst as jest.Mock).mockResolvedValue(null)
|
||||
;(prisma.performanceSurvey.count as jest.Mock).mockResolvedValue(0)
|
||||
const configuredGroup = buildConfiguredPositionGroup()
|
||||
;(listPerformanceSurveyPositionGroups as jest.Mock).mockResolvedValue([configuredGroup])
|
||||
;(getPerformanceSurveyPositionGroupByCode as jest.Mock).mockResolvedValue(configuredGroup)
|
||||
;(getPerformanceSurveyPositionGroupForEmployee as jest.Mock).mockResolvedValue({
|
||||
status: 'matched',
|
||||
group: configuredGroup,
|
||||
matches: [configuredGroup],
|
||||
})
|
||||
;(getPerformanceSurveyTemplate as jest.Mock).mockReset()
|
||||
;(getPerformanceSurveyTemplate as jest.Mock).mockResolvedValue({
|
||||
code: 'course_share',
|
||||
@ -762,6 +819,7 @@ describe('performance survey service policies', () => {
|
||||
|
||||
await createPerformanceSurvey(session, {
|
||||
templateCode: 'course_share',
|
||||
positionGroupCode: 'brand_designer',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: ['employee-1'],
|
||||
evaluatorEmployeeIds: ['employee-2'],
|
||||
@ -785,6 +843,7 @@ describe('performance survey service policies', () => {
|
||||
test('发起人不能手动选择自己作为评分人员', async () => {
|
||||
await expect(createPerformanceSurvey(session, {
|
||||
templateCode: 'course_share',
|
||||
positionGroupCode: 'brand_designer',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: ['employee-1'],
|
||||
evaluatorEmployeeIds: ['employee-1'],
|
||||
@ -812,6 +871,7 @@ describe('performance survey service policies', () => {
|
||||
|
||||
await expect(createPerformanceSurvey(session, {
|
||||
templateCode: 'course_share',
|
||||
positionGroupCode: 'brand_designer',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: ['employee-outside'],
|
||||
evaluatorEmployeeIds: ['employee-2'],
|
||||
@ -835,7 +895,7 @@ describe('performance survey service policies', () => {
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('写入被考核人范围时不使用重名部门叶子回退', async () => {
|
||||
test('缺少完整组织路径时不使用重名部门叶子回退扩大被考核人范围', async () => {
|
||||
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockResolvedValue({
|
||||
...baseEmployee,
|
||||
departmentPath: null,
|
||||
@ -847,13 +907,14 @@ describe('performance survey service policies', () => {
|
||||
|
||||
await expect(createPerformanceSurvey(session, {
|
||||
templateCode: 'course_share',
|
||||
positionGroupCode: 'brand_designer',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: ['employee-outside'],
|
||||
evaluatorEmployeeIds: ['employee-2'],
|
||||
openNow: false,
|
||||
})).rejects.toThrow('只有系统管理员,或钉钉组织位于品牌中心、摄影中心、综合支持部的人员可以发起考核调研')
|
||||
})).rejects.toThrow('部分被考核人不在当前组织权限范围内')
|
||||
|
||||
expect(prisma.performanceSurveyEmployeeProfile.findMany).not.toHaveBeenCalled()
|
||||
expect(prisma.performanceSurveyEmployeeProfile.findMany).toHaveBeenCalled()
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@ -866,6 +927,7 @@ describe('performance survey service policies', () => {
|
||||
|
||||
await expect(createPerformanceSurvey(session, {
|
||||
templateCode: 'course_share',
|
||||
positionGroupCode: 'brand_designer',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: ['employee-1'],
|
||||
evaluatorEmployeeIds: ['employee-2'],
|
||||
@ -907,6 +969,7 @@ describe('performance survey service policies', () => {
|
||||
|
||||
const creation = createPerformanceSurvey(session, {
|
||||
templateCode: 'course_share',
|
||||
positionGroupCode: 'brand_designer',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: ['employee-target'],
|
||||
evaluatorEmployeeIds: ['employee-2'],
|
||||
@ -916,7 +979,7 @@ describe('performance survey service policies', () => {
|
||||
})
|
||||
|
||||
test.each(['商品企划部', '空间视觉部'])(
|
||||
'品牌中心%s不在普通人员发起范围内,canCreate 与创建接口保持一致',
|
||||
'%s不再由部门名称硬编码禁止发起,资格交给岗位匹配规则',
|
||||
async (departmentName) => {
|
||||
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockResolvedValue({
|
||||
...baseEmployee,
|
||||
@ -925,16 +988,8 @@ describe('performance survey service policies', () => {
|
||||
})
|
||||
|
||||
await expect(getPerformanceSurveyMe(session)).resolves.toEqual(expect.objectContaining({
|
||||
permissions: expect.objectContaining({ canCreate: false }),
|
||||
permissions: expect.objectContaining({ canCreate: true }),
|
||||
}))
|
||||
await expect(createPerformanceSurvey(session, {
|
||||
templateCode: 'course_share',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: ['employee-1'],
|
||||
evaluatorEmployeeIds: ['employee-2'],
|
||||
})).rejects.toEqual(new PerformanceSurveyApiError('只有系统管理员,或钉钉组织位于品牌中心、摄影中心、综合支持部的人员可以发起考核调研', 403))
|
||||
expect(prisma.performanceSurveyEmployeeProfile.findMany).not.toHaveBeenCalled()
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
@ -996,26 +1051,17 @@ describe('performance survey service policies', () => {
|
||||
scoreBands: [],
|
||||
})
|
||||
;(prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock).mockReset()
|
||||
;(prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock).mockImplementation(async ({ where }: any) => {
|
||||
const clauses = where?.AND || []
|
||||
const requestedIds = clauses.find((clause: any) => clause?.id?.in)?.id?.in
|
||||
if (requestedIds) return [creator, target]
|
||||
const evaluatorDingtalkUserId = clauses.find((clause: any) => clause?.dingtalkUserId)?.dingtalkUserId
|
||||
if (evaluatorDingtalkUserId === creatorManager.dingtalkUserId) return [creatorManager]
|
||||
if (evaluatorDingtalkUserId === creator.dingtalkUserId) return [creator]
|
||||
return []
|
||||
})
|
||||
;(prisma.user.findMany as jest.Mock).mockReset()
|
||||
;(prisma.user.findMany as jest.Mock).mockImplementation(async ({ where }: any) => {
|
||||
const dingtalkUserId = where?.dingtalkUserId
|
||||
if (dingtalkUserId === creatorManager.dingtalkUserId) {
|
||||
return [{ id: 'user-creator-manager', dingtalkUserId }]
|
||||
}
|
||||
return [{ id: baseUser.id, dingtalkUserId: baseUser.dingtalkUserId }]
|
||||
;(prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock)
|
||||
.mockResolvedValueOnce([creator, target])
|
||||
.mockResolvedValueOnce([creator])
|
||||
;(prisma.user.findFirst as jest.Mock).mockResolvedValue({
|
||||
id: baseUser.id,
|
||||
dingtalkUserId: baseUser.dingtalkUserId,
|
||||
})
|
||||
|
||||
await expect(createPerformanceSurvey(session, {
|
||||
templateCode: 'work_cooperation',
|
||||
positionGroupCode: 'brand_designer',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: [target.id],
|
||||
openNow: false,
|
||||
@ -1054,9 +1100,9 @@ describe('performance survey service policies', () => {
|
||||
managerDingtalkUserId: 'ding-other-manager',
|
||||
},
|
||||
evaluator: {
|
||||
id: 'employee-yuanzhe',
|
||||
displayName: '元泽',
|
||||
dingtalkUserId: '27102756692071120919',
|
||||
id: 'employee-other-manager',
|
||||
displayName: '直属主管',
|
||||
dingtalkUserId: 'ding-other-manager',
|
||||
},
|
||||
},
|
||||
{
|
||||
@ -1070,12 +1116,12 @@ describe('performance survey service policies', () => {
|
||||
managerDingtalkUserId: 'ding-other-manager',
|
||||
},
|
||||
evaluator: {
|
||||
id: 'employee-yuanzhe',
|
||||
displayName: '元泽',
|
||||
dingtalkUserId: '27102756692071120919',
|
||||
id: 'employee-other-manager',
|
||||
displayName: '直属主管',
|
||||
dingtalkUserId: 'ding-other-manager',
|
||||
},
|
||||
},
|
||||
])('$label发起工作配合度时由系统自动匹配正确评分人', async ({ employee, evaluator }) => {
|
||||
])('$label发起工作配合度时按模板读取人员档案中的直属主管', async ({ employee, evaluator }) => {
|
||||
const target = {
|
||||
...baseEmployee,
|
||||
...employee,
|
||||
@ -1123,28 +1169,22 @@ describe('performance survey service policies', () => {
|
||||
|
||||
await createPerformanceSurvey(session, {
|
||||
templateCode: 'work_cooperation',
|
||||
positionGroupCode: 'brand_designer',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: [target.id],
|
||||
openNow: false,
|
||||
})
|
||||
|
||||
const evaluatorQuery = (prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock).mock.calls[1][0]
|
||||
expect(evaluatorQuery).toEqual(expect.objectContaining({
|
||||
where: {
|
||||
AND: [
|
||||
{ id: { not: '__hidden__' } },
|
||||
{ dingtalkUserId: evaluator.dingtalkUserId },
|
||||
],
|
||||
},
|
||||
take: 2,
|
||||
}))
|
||||
expect(evaluatorQuery.where.AND[1].OR).toContainEqual({ dingtalkUserId: evaluator.dingtalkUserId })
|
||||
const assignmentRows = transactionClient.performanceSurveyAssignment.createMany.mock.calls[0][0].data
|
||||
expect(assignmentRows).toEqual([
|
||||
expect.objectContaining({
|
||||
evaluatorEmployeeId: evaluator.id,
|
||||
evaluatorDingtalkUserId: evaluator.dingtalkUserId,
|
||||
evaluatorName: evaluator.displayName,
|
||||
evaluatorSnapshot: expect.objectContaining({ performanceSurveyWorkflowRole: 'manager' }),
|
||||
workflowStageKey: 'manager_review',
|
||||
reviewerSource: 'direct_manager',
|
||||
}),
|
||||
])
|
||||
})
|
||||
@ -1152,7 +1192,7 @@ describe('performance survey service policies', () => {
|
||||
test.each([
|
||||
['指定人员', { evaluatorEmployeeIds: ['employee-manual-evaluator'] }],
|
||||
['指定部门', { evaluatorDepartmentNames: ['集团A/品牌中心/评审组'] }],
|
||||
])('工作配合度手动%s时覆盖P/M默认规则', async (_label, evaluatorInput) => {
|
||||
])('模板配置为发起时选择人员后支持%s评分人', async (_label, evaluatorInput) => {
|
||||
const target = {
|
||||
...baseEmployee,
|
||||
id: 'employee-target',
|
||||
@ -1170,6 +1210,23 @@ describe('performance survey service policies', () => {
|
||||
displayName: '手动评分人',
|
||||
dingtalkUserId: 'ding-manual-evaluator',
|
||||
}
|
||||
const manualGroup = buildConfiguredPositionGroup()
|
||||
const workTemplate = manualGroup.templates.find((template) => template.code === 'work_cooperation')!
|
||||
workTemplate.workflow = {
|
||||
stages: [{
|
||||
key: 'manual_review',
|
||||
label: '人工评价',
|
||||
order: 0,
|
||||
reviewers: [{ source: 'manual_selection', label: '发起时选择人员' }],
|
||||
}],
|
||||
scoring: { mode: 'average_reviewers', stageKeys: ['manual_review'] },
|
||||
}
|
||||
;(getPerformanceSurveyPositionGroupByCode as jest.Mock).mockResolvedValue(manualGroup)
|
||||
;(getPerformanceSurveyPositionGroupForEmployee as jest.Mock).mockResolvedValue({
|
||||
status: 'matched',
|
||||
group: manualGroup,
|
||||
matches: [manualGroup],
|
||||
})
|
||||
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockResolvedValue(target)
|
||||
;(getPerformanceSurveyTemplate as jest.Mock).mockResolvedValue({
|
||||
code: 'work_cooperation',
|
||||
@ -1206,6 +1263,7 @@ describe('performance survey service policies', () => {
|
||||
|
||||
await createPerformanceSurvey(session, {
|
||||
templateCode: 'work_cooperation',
|
||||
positionGroupCode: 'brand_designer',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: [target.id],
|
||||
...evaluatorInput,
|
||||
@ -1221,7 +1279,7 @@ describe('performance survey service policies', () => {
|
||||
])
|
||||
})
|
||||
|
||||
test('自动匹配工作配合度评分人时,P级档案缺少主管唯一值且组织内无唯一M级会明确拒绝创建', async () => {
|
||||
test('直属主管模板遇到人员档案缺少主管唯一值时明确拒绝创建', async () => {
|
||||
const target = {
|
||||
...baseEmployee,
|
||||
id: 'employee-target',
|
||||
@ -1247,16 +1305,17 @@ describe('performance survey service policies', () => {
|
||||
|
||||
await expect(createPerformanceSurvey(session, {
|
||||
templateCode: 'work_cooperation',
|
||||
positionGroupCode: 'brand_designer',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: [target.id],
|
||||
})).rejects.toEqual(new PerformanceSurveyApiError(
|
||||
'无法唯一确定缺主管人员所在组织的 M 级主管,请手动选择评分人',
|
||||
'无法确定缺主管人员的直属主管,请先校准人员档案',
|
||||
409,
|
||||
))
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('自动匹配工作配合度评分人时,P级档案缺少主管唯一值会使用同一完整组织内唯一M级主管', async () => {
|
||||
test('直属主管模板不按同部门 M 级人员猜测主管', async () => {
|
||||
const target = {
|
||||
...baseEmployee,
|
||||
id: 'employee-yijiang',
|
||||
@ -1311,24 +1370,20 @@ describe('performance survey service policies', () => {
|
||||
}],
|
||||
}))
|
||||
|
||||
await createPerformanceSurvey(session, {
|
||||
await expect(createPerformanceSurvey(session, {
|
||||
templateCode: 'work_cooperation',
|
||||
positionGroupCode: 'brand_designer',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: [target.id],
|
||||
openNow: false,
|
||||
})
|
||||
|
||||
const assignmentRows = transactionClient.performanceSurveyAssignment.createMany.mock.calls[0][0].data
|
||||
expect(assignmentRows).toEqual([
|
||||
expect.objectContaining({
|
||||
evaluatorEmployeeId: uniqueManager.id,
|
||||
evaluatorDingtalkUserId: uniqueManager.dingtalkUserId,
|
||||
evaluatorName: uniqueManager.displayName,
|
||||
}),
|
||||
])
|
||||
})).rejects.toEqual(new PerformanceSurveyApiError(
|
||||
'无法确定忆江的直属主管,请先校准人员档案',
|
||||
409,
|
||||
))
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('元泽本人发起工作配合度时要求手动选择其他评分人', async () => {
|
||||
test('人员姓名不再触发固定评分人规则,缺主管仍按档案错误处理', async () => {
|
||||
const yuanzhe = {
|
||||
...baseEmployee,
|
||||
id: 'employee-yuanzhe',
|
||||
@ -1354,16 +1409,17 @@ describe('performance survey service policies', () => {
|
||||
|
||||
await expect(createPerformanceSurvey(session, {
|
||||
templateCode: 'work_cooperation',
|
||||
positionGroupCode: 'brand_designer',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: [yuanzhe.id],
|
||||
})).rejects.toEqual(new PerformanceSurveyApiError(
|
||||
'元泽不能作为自己的评分人,请手动选择其他评分人',
|
||||
'无法确定元泽的直属主管,请先校准人员档案',
|
||||
409,
|
||||
))
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('元泽本人作为视觉评分对象时合并为自评即最终评分,流程不会互相等待', async () => {
|
||||
test('同一人员在不同阶段承担不同角色时保留独立任务并按阶段开放', async () => {
|
||||
const yuanzhe = {
|
||||
...baseEmployee,
|
||||
id: 'employee-yuanzhe',
|
||||
@ -1404,9 +1460,9 @@ describe('performance survey service policies', () => {
|
||||
;(prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock).mockReset()
|
||||
;(prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock)
|
||||
.mockResolvedValueOnce([yuanzhe])
|
||||
.mockResolvedValueOnce([yuanzhe])
|
||||
.mockResolvedValueOnce([manager])
|
||||
;(prisma.performanceSurveyEmployeeProfile.findFirst as jest.Mock).mockReset()
|
||||
;(prisma.performanceSurveyEmployeeProfile.findFirst as jest.Mock).mockResolvedValue(manager)
|
||||
;(prisma.performanceSurveyEmployeeProfile.findFirst as jest.Mock).mockResolvedValue(yuanzhe)
|
||||
;(prisma.user.findMany as jest.Mock).mockResolvedValue([
|
||||
{ id: 'user-1', dingtalkUserId: 'ding-yuanzhe' },
|
||||
{ id: 'user-manager', dingtalkUserId: 'ding-manager' },
|
||||
@ -1427,28 +1483,35 @@ describe('performance survey service policies', () => {
|
||||
|
||||
await createPerformanceSurvey(session, {
|
||||
templateCode: 'visual_brand_tone',
|
||||
templateVariant: 'without_copy',
|
||||
positionGroupCode: 'brand_designer',
|
||||
assessmentMonth: '2026-07',
|
||||
targetEmployeeIds: ['employee-yuanzhe', 'employee-other'],
|
||||
targetEmployeeIds: ['employee-yuanzhe'],
|
||||
openNow: true,
|
||||
})
|
||||
|
||||
const targetQuery = (prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock).mock.calls[0][0]
|
||||
expect(targetQuery.where.AND).toContainEqual({ id: { in: ['employee-yuanzhe'] } })
|
||||
const assignmentRows = transactionClient.performanceSurveyAssignment.createMany.mock.calls[0][0].data
|
||||
const templateSnapshot = transactionClient.performanceSurvey.create.mock.calls[0][0].data.templateSnapshot
|
||||
expect(templateSnapshot.questions).toHaveLength(4)
|
||||
expect(templateSnapshot.questions.map((question: { id: string }) => question.id)).not.toContain('copyExpression')
|
||||
expect(templateSnapshot.questions.every((question: { maxScore: number }) => question.maxScore === 10)).toBe(true)
|
||||
expect(assignmentRows).toHaveLength(2)
|
||||
expect(transactionClient.performanceSurvey.create.mock.calls[0][0].data.templateVersionId).toBe('template-version-4')
|
||||
expect(assignmentRows).toHaveLength(3)
|
||||
expect(assignmentRows).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
evaluatorEmployeeId: 'employee-yuanzhe',
|
||||
evaluatorSnapshot: expect.objectContaining({ performanceSurveyWorkflowRole: 'self_visual_final' }),
|
||||
workflowStageKey: 'self_review',
|
||||
reviewerSource: 'self',
|
||||
releasedAt: expect.any(Date),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
evaluatorEmployeeId: 'employee-manager',
|
||||
evaluatorSnapshot: expect.objectContaining({ performanceSurveyWorkflowRole: 'manager' }),
|
||||
workflowStageKey: 'final_review',
|
||||
reviewerSource: 'direct_manager',
|
||||
releasedAt: null,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
evaluatorEmployeeId: 'employee-yuanzhe',
|
||||
workflowStageKey: 'final_review',
|
||||
reviewerSource: 'fixed_employee',
|
||||
releasedAt: null,
|
||||
}),
|
||||
]))
|
||||
})
|
||||
@ -1457,14 +1520,20 @@ describe('performance survey service policies', () => {
|
||||
['无邪', '09061817188066'],
|
||||
['伯言', '09061617282237'],
|
||||
['清云', '09053022115891'],
|
||||
])('%s的视觉评分直属主管按钉钉唯一值固定为元泽', async (displayName, dingtalkUserId) => {
|
||||
])('%s的视觉评分按人员档案取直属主管,并按模板取固定终审人', async (displayName, dingtalkUserId) => {
|
||||
const target = {
|
||||
...baseEmployee,
|
||||
id: `employee-${displayName}`,
|
||||
displayName,
|
||||
flowerName: displayName,
|
||||
dingtalkUserId,
|
||||
managerDingtalkUserId: 'stale-manager',
|
||||
managerDingtalkUserId: 'ding-declared-manager',
|
||||
}
|
||||
const manager = {
|
||||
...baseEmployee,
|
||||
id: 'employee-declared-manager',
|
||||
displayName: '档案直属主管',
|
||||
dingtalkUserId: 'ding-declared-manager',
|
||||
}
|
||||
const yuanzhe = {
|
||||
...baseEmployee,
|
||||
@ -1485,7 +1554,7 @@ describe('performance survey service policies', () => {
|
||||
})
|
||||
;(prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock)
|
||||
.mockResolvedValueOnce([target])
|
||||
.mockResolvedValueOnce([yuanzhe])
|
||||
.mockResolvedValueOnce([manager])
|
||||
;(prisma.performanceSurveyEmployeeProfile.findFirst as jest.Mock).mockResolvedValue(yuanzhe)
|
||||
;(prisma.user.findMany as jest.Mock).mockResolvedValue([
|
||||
{ id: 'user-target', dingtalkUserId },
|
||||
@ -1507,6 +1576,7 @@ describe('performance survey service policies', () => {
|
||||
|
||||
await createPerformanceSurvey(session, {
|
||||
templateCode: 'visual_brand_tone',
|
||||
positionGroupCode: 'brand_designer',
|
||||
assessmentMonth: '2026-07',
|
||||
openNow: false,
|
||||
})
|
||||
@ -1515,7 +1585,7 @@ describe('performance survey service policies', () => {
|
||||
where: {
|
||||
AND: [
|
||||
{ id: { not: '__hidden__' } },
|
||||
{ dingtalkUserId: '27102756692071120919' },
|
||||
{ id: 'employee-yuanzhe' },
|
||||
],
|
||||
},
|
||||
})
|
||||
@ -1523,16 +1593,21 @@ describe('performance survey service policies', () => {
|
||||
expect(assignmentRows).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
evaluatorEmployeeId: 'employee-yuanzhe',
|
||||
evaluatorSnapshot: expect.objectContaining({ performanceSurveyWorkflowRole: 'visual_final' }),
|
||||
workflowStageKey: 'final_review',
|
||||
reviewerSource: 'fixed_employee',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
evaluatorEmployeeId: 'employee-declared-manager',
|
||||
workflowStageKey: 'final_review',
|
||||
reviewerSource: 'direct_manager',
|
||||
}),
|
||||
]))
|
||||
expect(assignmentRows.some((row: any) => row.evaluatorSnapshot?.performanceSurveyWorkflowRole === 'manager')).toBe(false)
|
||||
})
|
||||
|
||||
test.each([
|
||||
'集团A/摄影中心/摄影一部',
|
||||
'摄影中心/摄影一部',
|
||||
])('摄影中心人员的视觉评分直属主管按完整路径段固定为观世:%s', async (departmentPath) => {
|
||||
])('部门路径不再覆盖视觉评分的档案直属主管:%s', async (departmentPath) => {
|
||||
const target = {
|
||||
...baseEmployee,
|
||||
id: 'employee-photographer',
|
||||
@ -1540,7 +1615,7 @@ describe('performance survey service policies', () => {
|
||||
dingtalkUserId: 'ding-photographer',
|
||||
departmentName: '摄影一部',
|
||||
departmentPath,
|
||||
managerDingtalkUserId: 'stale-manager',
|
||||
managerDingtalkUserId: '17642061233583361',
|
||||
}
|
||||
const yuanzhe = {
|
||||
...baseEmployee,
|
||||
@ -1566,8 +1641,8 @@ describe('performance survey service policies', () => {
|
||||
})
|
||||
;(prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock)
|
||||
.mockResolvedValueOnce([target])
|
||||
.mockResolvedValueOnce([yuanzhe])
|
||||
;(prisma.performanceSurveyEmployeeProfile.findFirst as jest.Mock).mockResolvedValue(guanshi)
|
||||
.mockResolvedValueOnce([guanshi])
|
||||
;(prisma.performanceSurveyEmployeeProfile.findFirst as jest.Mock).mockResolvedValue(yuanzhe)
|
||||
;(prisma.user.findMany as jest.Mock).mockResolvedValue([
|
||||
{ id: 'user-target', dingtalkUserId: 'ding-photographer' },
|
||||
{ id: 'user-yuanzhe', dingtalkUserId: '27102756692071120919' },
|
||||
@ -1589,23 +1664,24 @@ describe('performance survey service policies', () => {
|
||||
|
||||
await createPerformanceSurvey(session, {
|
||||
templateCode: 'visual_brand_tone',
|
||||
positionGroupCode: 'brand_designer',
|
||||
assessmentMonth: '2026-07',
|
||||
openNow: false,
|
||||
})
|
||||
|
||||
expect(prisma.performanceSurveyEmployeeProfile.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
AND: [
|
||||
{ id: { not: '__hidden__' } },
|
||||
{ dingtalkUserId: '17642061233583361' },
|
||||
],
|
||||
},
|
||||
})
|
||||
const managerQuery = (prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock).mock.calls[1][0]
|
||||
expect(managerQuery.where.AND[1].OR).toContainEqual({ dingtalkUserId: '17642061233583361' })
|
||||
const assignmentRows = transactionClient.performanceSurveyAssignment.createMany.mock.calls[0][0].data
|
||||
expect(assignmentRows).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
evaluatorEmployeeId: 'employee-guanshi',
|
||||
evaluatorSnapshot: expect.objectContaining({ performanceSurveyWorkflowRole: 'manager' }),
|
||||
workflowStageKey: 'final_review',
|
||||
reviewerSource: 'direct_manager',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
evaluatorEmployeeId: 'employee-yuanzhe',
|
||||
workflowStageKey: 'final_review',
|
||||
reviewerSource: 'fixed_employee',
|
||||
}),
|
||||
]))
|
||||
})
|
||||
|
||||
@ -255,15 +255,21 @@ export async function queueSurveyAssignmentNotifications(surveyId: string) {
|
||||
const ids: string[] = []
|
||||
for (const assignment of survey.assignments) {
|
||||
if (assignment.status !== 'pending') continue
|
||||
const workflowStageKey = clean(assignment.workflowStageKey)
|
||||
const isConfiguredWorkflow = Boolean(workflowStageKey && workflowStageKey !== 'legacy')
|
||||
if (isConfiguredWorkflow && !assignment.releasedAt) continue
|
||||
const snapshot = assignment.evaluatorSnapshot as Record<string, unknown> | null
|
||||
const workflowRole = snapshot?.performanceSurveyWorkflowRole
|
||||
if (
|
||||
!isConfiguredWorkflow &&
|
||||
survey.templateCode === 'visual_brand_tone' &&
|
||||
!['self', 'self_visual_final'].includes(String(workflowRole || '')) &&
|
||||
!selfCompletedTargetIds.has(assignment.targetId)
|
||||
) continue
|
||||
const isVisualSelfAssignment = survey.templateCode === 'visual_brand_tone'
|
||||
&& ['self', 'self_visual_final'].includes(String(workflowRole || ''))
|
||||
const isVisualSelfAssignment = isConfiguredWorkflow
|
||||
? assignment.reviewerSource === 'self'
|
||||
: survey.templateCode === 'visual_brand_tone'
|
||||
&& ['self', 'self_visual_final'].includes(String(workflowRole || ''))
|
||||
const targetName = assignment.target.targetName
|
||||
ids.push(
|
||||
await queuePerformanceSurveyNotification({
|
||||
@ -286,7 +292,9 @@ export async function queueSurveyAssignmentNotifications(surveyId: string) {
|
||||
{ label: '截止时间', value: formatDateTime(survey.dueAt) },
|
||||
],
|
||||
note: isVisualSelfAssignment
|
||||
? '请先完成自评;提交后系统才会通知主管和元泽评分'
|
||||
? isConfiguredWorkflow
|
||||
? '请先完成当前阶段;提交后系统会自动开放后续评审'
|
||||
: '请先完成自评;提交后系统才会通知主管和终审人评分'
|
||||
: '请在截止时间前完成评分',
|
||||
}),
|
||||
actionUrl: getSurveyUrl(`/performance-survey/survey/${survey.id}?targetId=${assignment.targetId}`),
|
||||
@ -310,21 +318,36 @@ export async function recoverMissingSurveyAssignmentNotifications(limit = 20) {
|
||||
none: { eventType: 'survey.assignment.created' },
|
||||
},
|
||||
OR: [
|
||||
{ survey: { templateCode: { not: 'visual_brand_tone' } } },
|
||||
{ evaluatorSnapshot: { path: ['performanceSurveyWorkflowRole'], equals: 'self' } },
|
||||
{ evaluatorSnapshot: { path: ['performanceSurveyWorkflowRole'], equals: 'self_visual_final' } },
|
||||
{
|
||||
target: {
|
||||
assignments: {
|
||||
some: {
|
||||
status: 'submitted',
|
||||
OR: [
|
||||
{ evaluatorSnapshot: { path: ['performanceSurveyWorkflowRole'], equals: 'self' } },
|
||||
{ evaluatorSnapshot: { path: ['performanceSurveyWorkflowRole'], equals: 'self_visual_final' } },
|
||||
],
|
||||
},
|
||||
AND: [
|
||||
{ workflowStageKey: { not: 'legacy' } },
|
||||
{ releasedAt: { not: null } },
|
||||
],
|
||||
},
|
||||
{
|
||||
AND: [
|
||||
{ workflowStageKey: 'legacy' },
|
||||
{
|
||||
OR: [
|
||||
{ survey: { templateCode: { not: 'visual_brand_tone' } } },
|
||||
{ evaluatorSnapshot: { path: ['performanceSurveyWorkflowRole'], equals: 'self' } },
|
||||
{ evaluatorSnapshot: { path: ['performanceSurveyWorkflowRole'], equals: 'self_visual_final' } },
|
||||
{
|
||||
target: {
|
||||
assignments: {
|
||||
some: {
|
||||
status: 'submitted',
|
||||
OR: [
|
||||
{ evaluatorSnapshot: { path: ['performanceSurveyWorkflowRole'], equals: 'self' } },
|
||||
{ evaluatorSnapshot: { path: ['performanceSurveyWorkflowRole'], equals: 'self_visual_final' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
} as any,
|
||||
@ -365,8 +388,9 @@ export async function queueSurveyTargetConfirmationNotifications(surveyId: strin
|
||||
})
|
||||
const creatorDingtalkUserId = clean(creator?.dingtalkUserId)
|
||||
const creatorEmail = clean(creator?.email)?.toLowerCase() || null
|
||||
const isVisualSurvey = survey.templateCode === 'visual_brand_tone'
|
||||
const visualTemplate = survey.templateSnapshot as { requiredWorkItemCount?: number } | null
|
||||
const visualTemplate = survey.templateSnapshot as { surveyType?: string; requiredWorkItemCount?: number } | null
|
||||
const isVisualSurvey = visualTemplate?.surveyType === 'visual_case'
|
||||
|| (!survey.positionGroupId && !survey.templateVersionId && survey.templateCode === 'visual_brand_tone')
|
||||
const requiredWorkItemCount = Math.max(1, Number(visualTemplate?.requiredWorkItemCount || 3))
|
||||
const ids: string[] = []
|
||||
|
||||
@ -508,7 +532,10 @@ export async function queueDuePerformanceSurveyReminders() {
|
||||
},
|
||||
include: {
|
||||
assignments: {
|
||||
where: { status: 'pending' },
|
||||
where: {
|
||||
status: 'pending',
|
||||
OR: [{ workflowStageKey: 'legacy' }, { releasedAt: { not: null } }],
|
||||
},
|
||||
include: { target: true },
|
||||
},
|
||||
},
|
||||
|
||||
989
lib/performance-survey-position-config.ts
Normal file
989
lib/performance-survey-position-config.ts
Normal file
@ -0,0 +1,989 @@
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { getPerformanceSurveyAccountProfileWhere } from '@/lib/performance-survey-report-sync'
|
||||
import {
|
||||
DEFAULT_PERFORMANCE_SURVEY_TEMPLATES,
|
||||
PERFORMANCE_SURVEY_VISUAL_TEMPLATE_VARIANTS,
|
||||
ensurePerformanceSurveyTemplates,
|
||||
getPerformanceSurveyTemplateVariant,
|
||||
type PerformanceSurveyTemplateShape,
|
||||
type PerformanceSurveyWorkflowDefinition,
|
||||
type PerformanceSurveyWorkflowReviewer,
|
||||
} from '@/lib/performance-survey-templates'
|
||||
|
||||
export const PERFORMANCE_SURVEY_TEMPLATE_PAGE_SIZE = 4
|
||||
|
||||
export function paginatePerformanceSurveyTemplates<T>(items: T[], requestedPage: unknown) {
|
||||
const parsedPage = Number.parseInt(String(requestedPage ?? '1'), 10)
|
||||
const pageCount = Math.max(1, Math.ceil(items.length / PERFORMANCE_SURVEY_TEMPLATE_PAGE_SIZE))
|
||||
const page = Math.min(Math.max(Number.isFinite(parsedPage) ? parsedPage : 1, 1), pageCount)
|
||||
const startIndex = (page - 1) * PERFORMANCE_SURVEY_TEMPLATE_PAGE_SIZE
|
||||
return {
|
||||
items: items.slice(startIndex, startIndex + PERFORMANCE_SURVEY_TEMPLATE_PAGE_SIZE),
|
||||
pager: {
|
||||
page,
|
||||
pageSize: PERFORMANCE_SURVEY_TEMPLATE_PAGE_SIZE,
|
||||
totalPages: pageCount,
|
||||
totalItems: items.length,
|
||||
start: items.length === 0 ? 0 : startIndex + 1,
|
||||
end: Math.min(startIndex + PERFORMANCE_SURVEY_TEMPLATE_PAGE_SIZE, items.length),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export const PERFORMANCE_SURVEY_POSITION_GROUP_SEEDS = [
|
||||
{ id: 'pspg-ai-planning-creative', code: 'ai_planning_creative', name: 'AI策划-创意部', sortOrder: 10 },
|
||||
{ id: 'pspg-ai-planning-general', code: 'ai_planning_general', name: 'AI策划-综合部', sortOrder: 20 },
|
||||
{ id: 'pspg-ai-technical-designer', code: 'ai_technical_designer', name: 'AI技术设计师', sortOrder: 30 },
|
||||
{ id: 'pspg-brand-designer', code: 'brand_designer', name: '品牌设计师', sortOrder: 40 },
|
||||
{ id: 'pspg-director', code: 'director', name: '编导', sortOrder: 50 },
|
||||
{ id: 'pspg-camera', code: 'camera', name: '摄像', sortOrder: 60 },
|
||||
{ id: 'pspg-editing', code: 'editing', name: '剪辑', sortOrder: 70 },
|
||||
{ id: 'pspg-retouching', code: 'retouching', name: '修图', sortOrder: 80 },
|
||||
] as const
|
||||
|
||||
export type PerformanceSurveyPositionRuleInput = {
|
||||
departmentPathPrefix?: string | null
|
||||
positionTitle?: string | null
|
||||
}
|
||||
|
||||
export type PerformanceSurveyPositionMembership = {
|
||||
status: 'matched' | 'unmatched' | 'conflict'
|
||||
group: PositionGroupRuntime | null
|
||||
matches: PositionGroupRuntime[]
|
||||
}
|
||||
|
||||
export type PositionGroupRuntime = {
|
||||
id: string
|
||||
code: string
|
||||
name: string
|
||||
sortOrder: number
|
||||
isActive: boolean
|
||||
status: 'ready' | 'pending' | 'disabled'
|
||||
planId: string | null
|
||||
planVersion: number | null
|
||||
effectiveMonth: string | null
|
||||
rules: PerformanceSurveyPositionRuleInput[]
|
||||
templates: PerformanceSurveyTemplateShape[]
|
||||
}
|
||||
|
||||
export class PerformanceSurveyPositionConfigError extends Error {
|
||||
status: number
|
||||
|
||||
constructor(message: string, status = 400) {
|
||||
super(message)
|
||||
this.name = 'PerformanceSurveyPositionConfigError'
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
function clean(value: unknown) {
|
||||
const text = String(value ?? '').trim()
|
||||
return text || null
|
||||
}
|
||||
|
||||
function normalizeMatchText(value: unknown) {
|
||||
return String(value ?? '').trim().toLocaleLowerCase('zh-CN')
|
||||
}
|
||||
|
||||
function normalizeDepartmentPath(value: unknown) {
|
||||
return normalizeMatchText(value)
|
||||
.replace(/[\\>||]+/g, '/')
|
||||
.split('/')
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean)
|
||||
.join('/')
|
||||
}
|
||||
|
||||
export function normalizePerformanceSurveyAssessmentMonth(value: unknown) {
|
||||
const month = String(value ?? '').trim()
|
||||
return /^\d{4}-(0[1-9]|1[0-2])$/.test(month) ? month : null
|
||||
}
|
||||
|
||||
function getCurrentAssessmentMonth() {
|
||||
const now = new Date()
|
||||
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
export function matchesPerformanceSurveyPositionRule(
|
||||
employee: { departmentPath?: string | null; departmentName?: string | null; positionTitle?: string | null },
|
||||
rule: PerformanceSurveyPositionRuleInput,
|
||||
) {
|
||||
const departmentPrefix = normalizeDepartmentPath(rule.departmentPathPrefix)
|
||||
const positionTitle = normalizeMatchText(rule.positionTitle)
|
||||
if (!departmentPrefix && !positionTitle) return false
|
||||
|
||||
const employeeDepartmentPath = normalizeDepartmentPath(employee.departmentPath || employee.departmentName)
|
||||
const employeePositionTitle = normalizeMatchText(employee.positionTitle)
|
||||
const departmentMatches = !departmentPrefix
|
||||
|| employeeDepartmentPath === departmentPrefix
|
||||
|| employeeDepartmentPath.startsWith(`${departmentPrefix}/`)
|
||||
const positionMatches = !positionTitle || employeePositionTitle === positionTitle
|
||||
return departmentMatches && positionMatches
|
||||
}
|
||||
|
||||
export function resolvePerformanceSurveyPositionMembership(
|
||||
employee: { departmentPath?: string | null; departmentName?: string | null; positionTitle?: string | null },
|
||||
groups: PositionGroupRuntime[],
|
||||
): PerformanceSurveyPositionMembership {
|
||||
const matches = groups.filter((group) => (
|
||||
group.isActive
|
||||
&& group.rules.length > 0
|
||||
&& group.rules.some((rule) => matchesPerformanceSurveyPositionRule(employee, rule))
|
||||
))
|
||||
return {
|
||||
status: matches.length === 1 ? 'matched' : matches.length === 0 ? 'unmatched' : 'conflict',
|
||||
group: matches.length === 1 ? matches[0] : null,
|
||||
matches,
|
||||
}
|
||||
}
|
||||
|
||||
function readRules(value: unknown): PerformanceSurveyPositionRuleInput[] {
|
||||
if (!Array.isArray(value)) return []
|
||||
return value
|
||||
.map((item) => {
|
||||
const record = item && typeof item === 'object' && !Array.isArray(item)
|
||||
? item as Record<string, unknown>
|
||||
: {}
|
||||
return {
|
||||
departmentPathPrefix: clean(record.departmentPathPrefix),
|
||||
positionTitle: clean(record.positionTitle),
|
||||
}
|
||||
})
|
||||
.filter((rule) => Boolean(rule.departmentPathPrefix || rule.positionTitle))
|
||||
}
|
||||
|
||||
function readTemplateDefinition(value: unknown): PerformanceSurveyTemplateShape {
|
||||
return value as PerformanceSurveyTemplateShape
|
||||
}
|
||||
|
||||
function validateWorkflow(workflow: PerformanceSurveyWorkflowDefinition | undefined) {
|
||||
if (!workflow || !Array.isArray(workflow.stages) || workflow.stages.length === 0) {
|
||||
throw new PerformanceSurveyPositionConfigError('模板至少需要 1 个评审阶段')
|
||||
}
|
||||
const stageKeys = new Set<string>()
|
||||
const stageOrders = new Set<number>()
|
||||
for (const stage of workflow.stages) {
|
||||
const key = clean(stage.key)
|
||||
if (!key) throw new PerformanceSurveyPositionConfigError('评审阶段缺少标识')
|
||||
if (stageKeys.has(key)) throw new PerformanceSurveyPositionConfigError(`评审阶段标识重复:${key}`)
|
||||
stageKeys.add(key)
|
||||
if (!Number.isInteger(stage.order) || stage.order < 0) {
|
||||
throw new PerformanceSurveyPositionConfigError(`评审阶段「${stage.label || key}」顺序无效`)
|
||||
}
|
||||
if (stageOrders.has(stage.order)) throw new PerformanceSurveyPositionConfigError(`评审阶段顺序重复:${stage.order}`)
|
||||
stageOrders.add(stage.order)
|
||||
if (!clean(stage.label)) throw new PerformanceSurveyPositionConfigError(`评审阶段 ${key} 缺少名称`)
|
||||
if (!Array.isArray(stage.reviewers) || stage.reviewers.length === 0) {
|
||||
throw new PerformanceSurveyPositionConfigError(`评审阶段「${stage.label}」至少需要 1 类评分人`)
|
||||
}
|
||||
for (const reviewer of stage.reviewers) {
|
||||
if (!['self', 'direct_manager', 'fixed_employee', 'manual_selection'].includes(reviewer.source)) {
|
||||
throw new PerformanceSurveyPositionConfigError(`评审阶段「${stage.label}」包含无效评分人来源`)
|
||||
}
|
||||
if (reviewer.source === 'fixed_employee' && !clean(reviewer.employeeId)) {
|
||||
throw new PerformanceSurveyPositionConfigError(`评审阶段「${stage.label}」的固定评分人尚未选择`)
|
||||
}
|
||||
}
|
||||
}
|
||||
const scoring = workflow.scoring
|
||||
if (!scoring || !['final_reviewer', 'average_reviewers'].includes(scoring.mode)) {
|
||||
throw new PerformanceSurveyPositionConfigError('模板缺少有效计分规则')
|
||||
}
|
||||
if (scoring.mode === 'final_reviewer') {
|
||||
const stage = workflow.stages.find((item) => item.key === scoring.stageKey)
|
||||
if (!stage) throw new PerformanceSurveyPositionConfigError('终审计分阶段不存在')
|
||||
const scoringReviewers = stage.reviewers.filter((reviewer) => reviewer.source === scoring.reviewerSource)
|
||||
if (scoringReviewers.length === 0) {
|
||||
throw new PerformanceSurveyPositionConfigError('终审计分人员不属于所选阶段')
|
||||
}
|
||||
if (scoringReviewers.length > 1) throw new PerformanceSurveyPositionConfigError('终审计分人员必须唯一')
|
||||
} else {
|
||||
const invalidStage = (scoring.stageKeys || []).find((key) => !stageKeys.has(key))
|
||||
if (invalidStage) throw new PerformanceSurveyPositionConfigError(`平均计分阶段不存在:${invalidStage}`)
|
||||
}
|
||||
}
|
||||
|
||||
export function validatePerformanceSurveyTemplateDefinition(definition: PerformanceSurveyTemplateShape) {
|
||||
if (!clean(definition.code)) throw new PerformanceSurveyPositionConfigError('模板代码不能为空')
|
||||
if (!clean(definition.name)) throw new PerformanceSurveyPositionConfigError('模板名称不能为空')
|
||||
if (!['person_period', 'visual_case', 'item_course'].includes(definition.surveyType)) {
|
||||
throw new PerformanceSurveyPositionConfigError('模板类型无效')
|
||||
}
|
||||
if (!Array.isArray(definition.questions) || definition.questions.length === 0) {
|
||||
throw new PerformanceSurveyPositionConfigError('模板至少需要 1 个评分项')
|
||||
}
|
||||
const questionIds = new Set<string>()
|
||||
for (const question of definition.questions) {
|
||||
const id = clean(question.id)
|
||||
if (!id || !clean(question.title)) throw new PerformanceSurveyPositionConfigError('评分项缺少名称或标识')
|
||||
if (questionIds.has(id)) throw new PerformanceSurveyPositionConfigError(`评分项标识重复:${id}`)
|
||||
questionIds.add(id)
|
||||
const maxScore = Number(question.maxScore ?? definition.questionMaxScore ?? 20)
|
||||
if (!Number.isFinite(maxScore) || maxScore <= 0) throw new PerformanceSurveyPositionConfigError(`评分项「${question.title}」满分无效`)
|
||||
}
|
||||
if (definition.surveyType === 'visual_case') {
|
||||
const requiredCount = Number(definition.requiredWorkItemCount || 0)
|
||||
if (!Number.isInteger(requiredCount) || requiredCount < 1) {
|
||||
throw new PerformanceSurveyPositionConfigError('视觉案例模板必须配置作品数量')
|
||||
}
|
||||
}
|
||||
validateWorkflow(definition.workflow)
|
||||
}
|
||||
|
||||
function withResolvedFixedReviewers(
|
||||
definition: PerformanceSurveyTemplateShape,
|
||||
fixedEmployee: { id: string; displayName: string } | null,
|
||||
) {
|
||||
if (!definition.workflow) return definition
|
||||
return {
|
||||
...definition,
|
||||
workflow: {
|
||||
...definition.workflow,
|
||||
stages: definition.workflow.stages.map((stage) => ({
|
||||
...stage,
|
||||
reviewers: stage.reviewers.map((reviewer) => (
|
||||
reviewer.source === 'fixed_employee' && fixedEmployee
|
||||
? { ...reviewer, employeeId: fixedEmployee.id, employeeName: fixedEmployee.displayName }
|
||||
: reviewer
|
||||
)),
|
||||
})),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function buildPlaceholderDefinition(code: string, name: string): PerformanceSurveyTemplateShape {
|
||||
return {
|
||||
code,
|
||||
name,
|
||||
shortName: name,
|
||||
description: '待管理员补充评分项、评审流程和计分规则。',
|
||||
surveyType: 'person_period',
|
||||
weight: 1,
|
||||
maxTotal: 120,
|
||||
questions: [],
|
||||
scoreBands: [],
|
||||
workflow: {
|
||||
stages: [{
|
||||
key: 'review',
|
||||
label: '评价',
|
||||
order: 0,
|
||||
reviewers: [{ source: 'manual_selection', label: '评价人' }],
|
||||
}],
|
||||
scoring: { mode: 'average_reviewers', stageKeys: ['review'] },
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureTemplateVersionSeed(input: {
|
||||
definition: PerformanceSurveyTemplateShape
|
||||
status: 'draft' | 'published'
|
||||
effectiveMonth: string | null
|
||||
}) {
|
||||
const definition = input.definition
|
||||
const template = await prisma.performanceSurveyTemplate.upsert({
|
||||
where: { code: definition.code },
|
||||
update: {},
|
||||
create: {
|
||||
code: definition.code,
|
||||
name: definition.name,
|
||||
description: definition.description || '',
|
||||
surveyType: definition.surveyType,
|
||||
weight: Number(definition.weight || 1),
|
||||
questions: definition.questions as any,
|
||||
scoreBands: definition.scoreBands as any,
|
||||
isActive: true,
|
||||
},
|
||||
})
|
||||
return prisma.performanceSurveyTemplateVersion.upsert({
|
||||
where: { templateId_version: { templateId: template.id, version: 1 } },
|
||||
update: {},
|
||||
create: {
|
||||
templateId: template.id,
|
||||
version: 1,
|
||||
status: input.status,
|
||||
effectiveMonth: input.status === 'published' ? input.effectiveMonth : null,
|
||||
definition: definition as any,
|
||||
publishedAt: input.status === 'published' ? new Date() : null,
|
||||
createdByName: '系统初始化',
|
||||
},
|
||||
include: { template: true },
|
||||
})
|
||||
}
|
||||
|
||||
async function ensurePositionPlanSeed(input: {
|
||||
groupCode: string
|
||||
templateVersionIds: string[]
|
||||
status: 'draft' | 'published'
|
||||
effectiveMonth: string
|
||||
}) {
|
||||
const group = await prisma.performanceSurveyPositionGroup.findUnique({ where: { code: input.groupCode } })
|
||||
if (!group) return
|
||||
const existing = await prisma.performanceSurveyPositionPlan.findUnique({
|
||||
where: { positionGroupId_version: { positionGroupId: group.id, version: 1 } },
|
||||
})
|
||||
if (existing) return
|
||||
await prisma.performanceSurveyPositionPlan.create({
|
||||
data: {
|
||||
positionGroupId: group.id,
|
||||
version: 1,
|
||||
status: input.status,
|
||||
effectiveMonth: input.status === 'published' ? input.effectiveMonth : null,
|
||||
matchRules: [],
|
||||
publishedAt: input.status === 'published' ? new Date() : null,
|
||||
createdByName: '系统初始化',
|
||||
items: {
|
||||
create: input.templateVersionIds.map((templateVersionId, index) => ({
|
||||
templateVersionId,
|
||||
sortOrder: index,
|
||||
isEnabled: true,
|
||||
})),
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function seedPerformanceSurveyPositionConfiguration() {
|
||||
await ensurePerformanceSurveyTemplates()
|
||||
for (const seed of PERFORMANCE_SURVEY_POSITION_GROUP_SEEDS) {
|
||||
await prisma.performanceSurveyPositionGroup.upsert({
|
||||
where: { code: seed.code },
|
||||
update: {},
|
||||
create: { ...seed, isActive: true },
|
||||
})
|
||||
}
|
||||
|
||||
const fixedEmployees = await prisma.performanceSurveyEmployeeProfile.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ displayName: '元泽' },
|
||||
{ flowerName: '元泽' },
|
||||
{ realName: '元泽' },
|
||||
],
|
||||
},
|
||||
select: { id: true, displayName: true },
|
||||
take: 2,
|
||||
})
|
||||
const fixedEmployee = fixedEmployees.length === 1 ? fixedEmployees[0] : null
|
||||
const initialMonth = getCurrentAssessmentMonth()
|
||||
const defaults = new Map(DEFAULT_PERFORMANCE_SURVEY_TEMPLATES.map((item) => [item.code, item]))
|
||||
const versionByCode = new Map<string, { id: string; status: string }>()
|
||||
|
||||
for (const template of DEFAULT_PERFORMANCE_SURVEY_TEMPLATES) {
|
||||
const resolved = withResolvedFixedReviewers(template, fixedEmployee)
|
||||
const hasUnresolvedFixedReviewer = resolved.workflow?.stages.some((stage) => (
|
||||
stage.reviewers.some((reviewer) => reviewer.source === 'fixed_employee' && !reviewer.employeeId)
|
||||
))
|
||||
const version = await ensureTemplateVersionSeed({
|
||||
definition: resolved,
|
||||
status: hasUnresolvedFixedReviewer ? 'draft' : 'published',
|
||||
effectiveMonth: initialMonth,
|
||||
})
|
||||
versionByCode.set(template.code, version)
|
||||
}
|
||||
|
||||
const visual = defaults.get('visual_brand_tone')
|
||||
if (visual) {
|
||||
const withoutCopy = withResolvedFixedReviewers({
|
||||
...getPerformanceSurveyTemplateVariant(visual, PERFORMANCE_SURVEY_VISUAL_TEMPLATE_VARIANTS.WITHOUT_COPY),
|
||||
code: 'visual_brand_tone_without_copy',
|
||||
name: '品牌调性视觉评分(不含文案)',
|
||||
shortName: '视觉评分(无文案)',
|
||||
templateOptionKey: 'visual_brand_tone_without_copy',
|
||||
templateVariant: undefined,
|
||||
templateVariantName: undefined,
|
||||
}, fixedEmployee)
|
||||
const hasUnresolvedFixedReviewer = withoutCopy.workflow?.stages.some((stage) => (
|
||||
stage.reviewers.some((reviewer) => reviewer.source === 'fixed_employee' && !reviewer.employeeId)
|
||||
))
|
||||
const version = await ensureTemplateVersionSeed({
|
||||
definition: withoutCopy,
|
||||
status: hasUnresolvedFixedReviewer ? 'draft' : 'published',
|
||||
effectiveMonth: initialMonth,
|
||||
})
|
||||
versionByCode.set(withoutCopy.code, version)
|
||||
}
|
||||
|
||||
for (const placeholder of [
|
||||
buildPlaceholderDefinition('ai_work_review', 'AI作品评审'),
|
||||
buildPlaceholderDefinition('project_result_validation', '项目成果验证'),
|
||||
]) {
|
||||
const version = await ensureTemplateVersionSeed({ definition: placeholder, status: 'draft', effectiveMonth: null })
|
||||
versionByCode.set(placeholder.code, version)
|
||||
}
|
||||
|
||||
const ids = (codes: string[]) => codes
|
||||
.map((code) => versionByCode.get(code)?.id)
|
||||
.filter((id): id is string => Boolean(id))
|
||||
const statuses = (codes: string[]) => codes.map((code) => versionByCode.get(code)?.status)
|
||||
const knownPlans = [
|
||||
{
|
||||
groupCode: 'ai_planning_creative',
|
||||
codes: ['visual_brand_tone', 'cross_department', 'work_cooperation', 'course_share'],
|
||||
},
|
||||
{
|
||||
groupCode: 'ai_planning_general',
|
||||
codes: ['visual_brand_tone_without_copy', 'cross_department', 'work_cooperation', 'course_share'],
|
||||
},
|
||||
{
|
||||
groupCode: 'brand_designer',
|
||||
codes: ['visual_brand_tone', 'cross_department', 'work_cooperation', 'course_share'],
|
||||
},
|
||||
]
|
||||
for (const plan of knownPlans) {
|
||||
const allPublished = statuses(plan.codes).every((status) => status === 'published')
|
||||
await ensurePositionPlanSeed({
|
||||
groupCode: plan.groupCode,
|
||||
templateVersionIds: ids(plan.codes),
|
||||
status: allPublished ? 'published' : 'draft',
|
||||
effectiveMonth: initialMonth,
|
||||
})
|
||||
}
|
||||
await ensurePositionPlanSeed({
|
||||
groupCode: 'ai_technical_designer',
|
||||
templateVersionIds: ids(['ai_work_review', 'project_result_validation', 'work_cooperation', 'course_share']),
|
||||
status: 'draft',
|
||||
effectiveMonth: initialMonth,
|
||||
})
|
||||
}
|
||||
|
||||
function chooseEffectivePlan<T extends { status: string; effectiveMonth: string | null; version: number }>(
|
||||
plans: T[],
|
||||
month: string,
|
||||
) {
|
||||
return plans
|
||||
.filter((plan) => plan.status === 'published' && plan.effectiveMonth && plan.effectiveMonth <= month)
|
||||
.sort((left, right) => (
|
||||
String(right.effectiveMonth).localeCompare(String(left.effectiveMonth)) || right.version - left.version
|
||||
))[0] || null
|
||||
}
|
||||
|
||||
export async function listPerformanceSurveyPositionGroups(monthInput?: string | null): Promise<PositionGroupRuntime[]> {
|
||||
const month = normalizePerformanceSurveyAssessmentMonth(monthInput) || getCurrentAssessmentMonth()
|
||||
const groups = await prisma.performanceSurveyPositionGroup.findMany({
|
||||
orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }],
|
||||
include: {
|
||||
plans: {
|
||||
include: {
|
||||
items: {
|
||||
where: { isEnabled: true },
|
||||
orderBy: { sortOrder: 'asc' },
|
||||
include: { templateVersion: { include: { template: true } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
return groups.map((group) => {
|
||||
const plan = chooseEffectivePlan(group.plans, month)
|
||||
const templates = (plan?.items || []).map((item) => ({
|
||||
...readTemplateDefinition(item.templateVersion.definition),
|
||||
templateVersionId: item.templateVersion.id,
|
||||
templateVersion: item.templateVersion.version,
|
||||
templateVersionStatus: item.templateVersion.status as 'draft' | 'published' | 'archived',
|
||||
effectiveMonth: item.templateVersion.effectiveMonth,
|
||||
}))
|
||||
const rules = readRules(plan?.matchRules)
|
||||
const ready = Boolean(plan && rules.length > 0 && templates.length > 0)
|
||||
return {
|
||||
id: group.id,
|
||||
code: group.code,
|
||||
name: group.name,
|
||||
sortOrder: group.sortOrder,
|
||||
isActive: group.isActive,
|
||||
status: !group.isActive ? 'disabled' : ready ? 'ready' : 'pending',
|
||||
planId: plan?.id || null,
|
||||
planVersion: plan?.version || null,
|
||||
effectiveMonth: plan?.effectiveMonth || null,
|
||||
rules,
|
||||
templates,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export async function getPerformanceSurveyPositionGroupForEmployee(
|
||||
employee: { departmentPath?: string | null; departmentName?: string | null; positionTitle?: string | null },
|
||||
month?: string | null,
|
||||
) {
|
||||
const groups = await listPerformanceSurveyPositionGroups(month)
|
||||
return resolvePerformanceSurveyPositionMembership(employee, groups)
|
||||
}
|
||||
|
||||
export async function getPerformanceSurveyPositionGroupByCode(code: string, month?: string | null) {
|
||||
const groups = await listPerformanceSurveyPositionGroups(month)
|
||||
const group = groups.find((item) => item.code === code)
|
||||
if (!group) throw new PerformanceSurveyPositionConfigError('考核岗位组不存在', 404)
|
||||
return group
|
||||
}
|
||||
|
||||
export async function getPerformanceSurveyPositionAdminConfig(monthInput?: string | null) {
|
||||
const month = normalizePerformanceSurveyAssessmentMonth(monthInput) || getCurrentAssessmentMonth()
|
||||
const [runtimeGroups, groups, templates, employees] = await Promise.all([
|
||||
listPerformanceSurveyPositionGroups(month),
|
||||
prisma.performanceSurveyPositionGroup.findMany({
|
||||
orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }],
|
||||
include: {
|
||||
rules: { orderBy: { sortOrder: 'asc' } },
|
||||
plans: {
|
||||
orderBy: { version: 'desc' },
|
||||
include: {
|
||||
items: {
|
||||
orderBy: { sortOrder: 'asc' },
|
||||
include: { templateVersion: { include: { template: true } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
prisma.performanceSurveyTemplate.findMany({
|
||||
orderBy: [{ createdAt: 'asc' }],
|
||||
include: { versions: { orderBy: { version: 'desc' } } },
|
||||
}),
|
||||
prisma.performanceSurveyEmployeeProfile.findMany({
|
||||
where: await getPerformanceSurveyAccountProfileWhere(),
|
||||
orderBy: [{ departmentName: 'asc' }, { displayName: 'asc' }],
|
||||
}),
|
||||
])
|
||||
const runtimeById = new Map(runtimeGroups.map((group) => [group.id, group]))
|
||||
const previewGroups: PositionGroupRuntime[] = groups.map((group) => {
|
||||
const runtime = runtimeById.get(group.id)!
|
||||
return { ...runtime, rules: group.rules.filter((rule) => rule.isActive).map((rule) => ({
|
||||
departmentPathPrefix: rule.departmentPathPrefix,
|
||||
positionTitle: rule.positionTitle,
|
||||
})) }
|
||||
})
|
||||
const memberships = employees.map((employee) => ({
|
||||
employee,
|
||||
membership: resolvePerformanceSurveyPositionMembership(employee, previewGroups),
|
||||
}))
|
||||
const memberCountByGroup = new Map<string, number>()
|
||||
for (const item of memberships) {
|
||||
if (item.membership.group) {
|
||||
memberCountByGroup.set(item.membership.group.id, (memberCountByGroup.get(item.membership.group.id) || 0) + 1)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
month,
|
||||
groups: groups.map((group) => {
|
||||
const runtime = runtimeById.get(group.id)!
|
||||
const draft = group.plans.find((plan) => plan.status === 'draft') || null
|
||||
return {
|
||||
id: group.id,
|
||||
code: group.code,
|
||||
name: group.name,
|
||||
sortOrder: group.sortOrder,
|
||||
isActive: group.isActive,
|
||||
status: runtime.status,
|
||||
memberCount: memberCountByGroup.get(group.id) || 0,
|
||||
rules: group.rules.map((rule) => ({
|
||||
id: rule.id,
|
||||
departmentPathPrefix: rule.departmentPathPrefix,
|
||||
positionTitle: rule.positionTitle,
|
||||
isActive: rule.isActive,
|
||||
sortOrder: rule.sortOrder,
|
||||
})),
|
||||
effectivePlan: runtime.planId ? {
|
||||
id: runtime.planId,
|
||||
version: runtime.planVersion,
|
||||
effectiveMonth: runtime.effectiveMonth,
|
||||
templateVersionIds: runtime.templates.map((template) => template.templateVersionId),
|
||||
} : null,
|
||||
draftPlan: draft ? {
|
||||
id: draft.id,
|
||||
version: draft.version,
|
||||
templateVersionIds: draft.items.filter((item) => item.isEnabled).map((item) => item.templateVersionId),
|
||||
} : null,
|
||||
}
|
||||
}),
|
||||
templates: templates.map((template) => ({
|
||||
id: template.id,
|
||||
code: template.code,
|
||||
name: template.name,
|
||||
description: template.description || '',
|
||||
surveyType: template.surveyType,
|
||||
isActive: template.isActive,
|
||||
versions: template.versions.map((version) => ({
|
||||
id: version.id,
|
||||
version: version.version,
|
||||
status: version.status,
|
||||
effectiveMonth: version.effectiveMonth,
|
||||
definition: version.definition,
|
||||
publishedAt: version.publishedAt,
|
||||
})),
|
||||
})),
|
||||
issues: {
|
||||
unmatched: memberships
|
||||
.filter((item) => item.membership.status === 'unmatched')
|
||||
.map((item) => serializePositionEmployee(item.employee)),
|
||||
conflicts: memberships
|
||||
.filter((item) => item.membership.status === 'conflict')
|
||||
.map((item) => ({
|
||||
...serializePositionEmployee(item.employee),
|
||||
groupNames: item.membership.matches.map((group) => group.name),
|
||||
})),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function serializePositionEmployee(employee: any) {
|
||||
return {
|
||||
id: employee.id,
|
||||
displayName: employee.displayName,
|
||||
departmentName: employee.departmentName,
|
||||
departmentPath: employee.departmentPath,
|
||||
positionTitle: employee.positionTitle,
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeRuleInputs(value: unknown): PerformanceSurveyPositionRuleInput[] {
|
||||
const rules = readRules(value)
|
||||
const keys = new Set<string>()
|
||||
for (const rule of rules) {
|
||||
const key = `${normalizeDepartmentPath(rule.departmentPathPrefix)}|${normalizeMatchText(rule.positionTitle)}`
|
||||
if (keys.has(key)) throw new PerformanceSurveyPositionConfigError('岗位匹配规则不能重复')
|
||||
keys.add(key)
|
||||
}
|
||||
return rules
|
||||
}
|
||||
|
||||
export async function savePerformanceSurveyPositionGroupDraft(input: {
|
||||
groupId: string
|
||||
name?: string
|
||||
sortOrder?: number
|
||||
isActive?: boolean
|
||||
rules?: unknown
|
||||
templateVersionIds?: unknown
|
||||
actorUserId: string
|
||||
actorName: string
|
||||
}) {
|
||||
const group = await prisma.performanceSurveyPositionGroup.findUnique({
|
||||
where: { id: input.groupId },
|
||||
include: { rules: { where: { isActive: true }, orderBy: { sortOrder: 'asc' } } },
|
||||
})
|
||||
if (!group) throw new PerformanceSurveyPositionConfigError('考核岗位组不存在', 404)
|
||||
const rulesProvided = input.rules !== undefined
|
||||
const templateVersionIdsProvided = input.templateVersionIds !== undefined
|
||||
const rules = rulesProvided ? normalizeRuleInputs(input.rules) : null
|
||||
const rawTemplateVersionIds = input.templateVersionIds
|
||||
if (templateVersionIdsProvided && !Array.isArray(rawTemplateVersionIds)) {
|
||||
throw new PerformanceSurveyPositionConfigError('岗位方案考核项格式无效')
|
||||
}
|
||||
const templateVersionIds: string[] | null = Array.isArray(rawTemplateVersionIds)
|
||||
? Array.from(new Set(rawTemplateVersionIds.map((id: unknown) => clean(id)).filter((id): id is string => Boolean(id))))
|
||||
: null
|
||||
const versions = templateVersionIds && templateVersionIds.length > 0
|
||||
? await prisma.performanceSurveyTemplateVersion.findMany({ where: { id: { in: templateVersionIds } } })
|
||||
: []
|
||||
if (templateVersionIds && versions.length !== templateVersionIds.length) {
|
||||
throw new PerformanceSurveyPositionConfigError('岗位方案包含不存在的模板版本')
|
||||
}
|
||||
|
||||
return prisma.$transaction(async (tx) => {
|
||||
await tx.performanceSurveyPositionGroup.update({
|
||||
where: { id: group.id },
|
||||
data: {
|
||||
...(clean(input.name) ? { name: clean(input.name)! } : {}),
|
||||
...(Number.isFinite(Number(input.sortOrder)) ? { sortOrder: Number(input.sortOrder) } : {}),
|
||||
...(typeof input.isActive === 'boolean' ? { isActive: input.isActive } : {}),
|
||||
},
|
||||
})
|
||||
if (rules) {
|
||||
await tx.performanceSurveyPositionRule.deleteMany({ where: { positionGroupId: group.id } })
|
||||
}
|
||||
if (rules && rules.length > 0) {
|
||||
await tx.performanceSurveyPositionRule.createMany({
|
||||
data: rules.map((rule, index) => ({
|
||||
positionGroupId: group.id,
|
||||
departmentPathPrefix: rule.departmentPathPrefix,
|
||||
positionTitle: rule.positionTitle,
|
||||
sortOrder: index,
|
||||
isActive: true,
|
||||
})),
|
||||
})
|
||||
}
|
||||
if (!rulesProvided && !templateVersionIdsProvided) {
|
||||
return { groupId: group.id, draftPlanId: null, version: null }
|
||||
}
|
||||
let draft = await tx.performanceSurveyPositionPlan.findFirst({
|
||||
where: { positionGroupId: group.id, status: 'draft' },
|
||||
orderBy: { version: 'desc' },
|
||||
})
|
||||
if (!draft) {
|
||||
const [latest, effectivePlan] = await Promise.all([
|
||||
tx.performanceSurveyPositionPlan.findFirst({
|
||||
where: { positionGroupId: group.id },
|
||||
orderBy: { version: 'desc' },
|
||||
select: { version: true },
|
||||
}),
|
||||
tx.performanceSurveyPositionPlan.findFirst({
|
||||
where: { positionGroupId: group.id, status: 'published' },
|
||||
orderBy: [{ effectiveMonth: 'desc' }, { version: 'desc' }],
|
||||
include: { items: { where: { isEnabled: true }, orderBy: { sortOrder: 'asc' } } },
|
||||
}),
|
||||
])
|
||||
const inheritedTemplateVersionIds = templateVersionIds
|
||||
?? effectivePlan?.items.map((item) => item.templateVersionId)
|
||||
?? []
|
||||
draft = await tx.performanceSurveyPositionPlan.create({
|
||||
data: {
|
||||
positionGroupId: group.id,
|
||||
version: Number(latest?.version || 0) + 1,
|
||||
status: 'draft',
|
||||
matchRules: (rules ?? group.rules.map((rule) => ({
|
||||
departmentPathPrefix: rule.departmentPathPrefix,
|
||||
positionTitle: rule.positionTitle,
|
||||
}))) as any,
|
||||
createdByUserId: input.actorUserId,
|
||||
createdByName: input.actorName,
|
||||
items: inheritedTemplateVersionIds.length > 0 ? {
|
||||
create: inheritedTemplateVersionIds.map((templateVersionId, index) => ({
|
||||
templateVersionId,
|
||||
sortOrder: index,
|
||||
isEnabled: true,
|
||||
})),
|
||||
} : undefined,
|
||||
},
|
||||
})
|
||||
} else if (rulesProvided) {
|
||||
draft = await tx.performanceSurveyPositionPlan.update({
|
||||
where: { id: draft.id },
|
||||
data: {
|
||||
matchRules: rules as any,
|
||||
createdByUserId: input.actorUserId,
|
||||
createdByName: input.actorName,
|
||||
},
|
||||
})
|
||||
}
|
||||
if (templateVersionIds) {
|
||||
await tx.performanceSurveyPositionPlanItem.deleteMany({ where: { positionPlanId: draft.id } })
|
||||
if (templateVersionIds.length > 0) {
|
||||
await tx.performanceSurveyPositionPlanItem.createMany({
|
||||
data: templateVersionIds.map((templateVersionId, index) => ({
|
||||
positionPlanId: draft!.id,
|
||||
templateVersionId,
|
||||
sortOrder: index,
|
||||
isEnabled: true,
|
||||
})),
|
||||
})
|
||||
}
|
||||
}
|
||||
return { groupId: group.id, draftPlanId: draft.id, version: draft.version }
|
||||
})
|
||||
}
|
||||
|
||||
async function assertPositionPlanHasNoConflicts(positionGroupId: string, month: string, rules: PerformanceSurveyPositionRuleInput[]) {
|
||||
const [groups, employees] = await Promise.all([
|
||||
listPerformanceSurveyPositionGroups(month),
|
||||
prisma.performanceSurveyEmployeeProfile.findMany({
|
||||
where: await getPerformanceSurveyAccountProfileWhere(),
|
||||
}),
|
||||
])
|
||||
const candidateGroups = groups.map((group) => (
|
||||
group.id === positionGroupId ? { ...group, rules, status: 'ready' as const } : group
|
||||
))
|
||||
const conflicts = employees
|
||||
.map((employee) => ({ employee, membership: resolvePerformanceSurveyPositionMembership(employee, candidateGroups) }))
|
||||
.filter((item) => item.membership.status === 'conflict')
|
||||
if (conflicts.length > 0) {
|
||||
throw new PerformanceSurveyPositionConfigError(
|
||||
`岗位规则存在 ${conflicts.length} 名重复匹配人员:${conflicts.slice(0, 5).map((item) => item.employee.displayName).join('、')}`,
|
||||
409,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function publishPerformanceSurveyPositionPlan(input: {
|
||||
groupId: string
|
||||
effectiveMonth: string
|
||||
actorUserId: string
|
||||
actorName: string
|
||||
}) {
|
||||
const effectiveMonth = normalizePerformanceSurveyAssessmentMonth(input.effectiveMonth)
|
||||
if (!effectiveMonth) throw new PerformanceSurveyPositionConfigError('生效月份格式无效')
|
||||
const draft = await prisma.performanceSurveyPositionPlan.findFirst({
|
||||
where: { positionGroupId: input.groupId, status: 'draft' },
|
||||
orderBy: { version: 'desc' },
|
||||
include: { items: { where: { isEnabled: true }, include: { templateVersion: true } } },
|
||||
})
|
||||
if (!draft) throw new PerformanceSurveyPositionConfigError('没有可发布的岗位方案草稿', 404)
|
||||
const rules = readRules(draft.matchRules)
|
||||
if (rules.length === 0) throw new PerformanceSurveyPositionConfigError('请先配置至少 1 条岗位匹配规则')
|
||||
if (draft.items.length === 0) throw new PerformanceSurveyPositionConfigError('岗位方案至少需要 1 个考核项')
|
||||
const invalidTemplate = draft.items.find((item) => item.templateVersion.status !== 'published')
|
||||
if (invalidTemplate) throw new PerformanceSurveyPositionConfigError('岗位方案包含尚未发布的模板')
|
||||
await assertPositionPlanHasNoConflicts(input.groupId, effectiveMonth, rules)
|
||||
|
||||
return prisma.$transaction(async (tx) => {
|
||||
await tx.performanceSurveyPositionPlan.updateMany({
|
||||
where: {
|
||||
positionGroupId: input.groupId,
|
||||
status: 'published',
|
||||
effectiveMonth,
|
||||
},
|
||||
data: { status: 'archived' },
|
||||
})
|
||||
return tx.performanceSurveyPositionPlan.update({
|
||||
where: { id: draft.id },
|
||||
data: {
|
||||
status: 'published',
|
||||
effectiveMonth,
|
||||
publishedAt: new Date(),
|
||||
createdByUserId: input.actorUserId,
|
||||
createdByName: input.actorName,
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function normalizeTemplateDefinitionInput(value: unknown): PerformanceSurveyTemplateShape {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new PerformanceSurveyPositionConfigError('模板定义格式无效')
|
||||
}
|
||||
const definition = value as PerformanceSurveyTemplateShape
|
||||
return {
|
||||
...definition,
|
||||
code: String(definition.code || '').trim().toLowerCase().replace(/[^a-z0-9_]+/g, '_'),
|
||||
name: String(definition.name || '').trim(),
|
||||
shortName: String(definition.shortName || definition.name || '').trim(),
|
||||
description: String(definition.description || '').trim(),
|
||||
surveyType: String(definition.surveyType || 'person_period').trim(),
|
||||
weight: Number(definition.weight || 1),
|
||||
questions: Array.isArray(definition.questions) ? definition.questions : [],
|
||||
scoreBands: Array.isArray(definition.scoreBands) ? definition.scoreBands : [],
|
||||
}
|
||||
}
|
||||
|
||||
export async function savePerformanceSurveyTemplateDraft(input: {
|
||||
versionId?: string | null
|
||||
definition: unknown
|
||||
actorUserId: string
|
||||
actorName: string
|
||||
}) {
|
||||
const definition = normalizeTemplateDefinitionInput(input.definition)
|
||||
if (!definition.code || !definition.name) throw new PerformanceSurveyPositionConfigError('模板代码和名称不能为空')
|
||||
const existingVersion = input.versionId
|
||||
? await prisma.performanceSurveyTemplateVersion.findUnique({
|
||||
where: { id: input.versionId },
|
||||
include: { template: true },
|
||||
})
|
||||
: null
|
||||
if (existingVersion && existingVersion.status !== 'draft') {
|
||||
throw new PerformanceSurveyPositionConfigError('已发布模板不可直接修改,请创建新草稿', 409)
|
||||
}
|
||||
|
||||
return prisma.$transaction(async (tx) => {
|
||||
const template = existingVersion?.template || await tx.performanceSurveyTemplate.upsert({
|
||||
where: { code: definition.code },
|
||||
update: {
|
||||
name: definition.name,
|
||||
description: definition.description,
|
||||
surveyType: definition.surveyType,
|
||||
isActive: true,
|
||||
},
|
||||
create: {
|
||||
code: definition.code,
|
||||
name: definition.name,
|
||||
description: definition.description,
|
||||
surveyType: definition.surveyType,
|
||||
weight: definition.weight,
|
||||
questions: definition.questions as any,
|
||||
scoreBands: definition.scoreBands as any,
|
||||
isActive: true,
|
||||
},
|
||||
})
|
||||
if (existingVersion) {
|
||||
return tx.performanceSurveyTemplateVersion.update({
|
||||
where: { id: existingVersion.id },
|
||||
data: { definition: definition as any, createdByUserId: input.actorUserId, createdByName: input.actorName },
|
||||
})
|
||||
}
|
||||
const latest = await tx.performanceSurveyTemplateVersion.findFirst({
|
||||
where: { templateId: template.id },
|
||||
orderBy: { version: 'desc' },
|
||||
select: { version: true },
|
||||
})
|
||||
return tx.performanceSurveyTemplateVersion.create({
|
||||
data: {
|
||||
templateId: template.id,
|
||||
version: Number(latest?.version || 0) + 1,
|
||||
status: 'draft',
|
||||
definition: definition as any,
|
||||
createdByUserId: input.actorUserId,
|
||||
createdByName: input.actorName,
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export async function createPerformanceSurveyTemplateDraftFromVersion(input: {
|
||||
versionId: string
|
||||
actorUserId: string
|
||||
actorName: string
|
||||
}) {
|
||||
const source = await prisma.performanceSurveyTemplateVersion.findUnique({ where: { id: input.versionId } })
|
||||
if (!source) throw new PerformanceSurveyPositionConfigError('模板版本不存在', 404)
|
||||
const existingDraft = await prisma.performanceSurveyTemplateVersion.findFirst({
|
||||
where: { templateId: source.templateId, status: 'draft' },
|
||||
orderBy: { version: 'desc' },
|
||||
})
|
||||
if (existingDraft) return existingDraft
|
||||
const latest = await prisma.performanceSurveyTemplateVersion.findFirst({
|
||||
where: { templateId: source.templateId },
|
||||
orderBy: { version: 'desc' },
|
||||
select: { version: true },
|
||||
})
|
||||
return prisma.performanceSurveyTemplateVersion.create({
|
||||
data: {
|
||||
templateId: source.templateId,
|
||||
version: Number(latest?.version || 0) + 1,
|
||||
status: 'draft',
|
||||
definition: source.definition as any,
|
||||
createdByUserId: input.actorUserId,
|
||||
createdByName: input.actorName,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function publishPerformanceSurveyTemplateVersion(input: {
|
||||
versionId: string
|
||||
effectiveMonth: string
|
||||
actorUserId: string
|
||||
actorName: string
|
||||
}) {
|
||||
const effectiveMonth = normalizePerformanceSurveyAssessmentMonth(input.effectiveMonth)
|
||||
if (!effectiveMonth) throw new PerformanceSurveyPositionConfigError('生效月份格式无效')
|
||||
const version = await prisma.performanceSurveyTemplateVersion.findUnique({ where: { id: input.versionId } })
|
||||
if (!version) throw new PerformanceSurveyPositionConfigError('模板版本不存在', 404)
|
||||
if (version.status !== 'draft') throw new PerformanceSurveyPositionConfigError('只有草稿模板可以发布', 409)
|
||||
validatePerformanceSurveyTemplateDefinition(readTemplateDefinition(version.definition))
|
||||
return prisma.performanceSurveyTemplateVersion.update({
|
||||
where: { id: version.id },
|
||||
data: {
|
||||
status: 'published',
|
||||
effectiveMonth,
|
||||
publishedAt: new Date(),
|
||||
createdByUserId: input.actorUserId,
|
||||
createdByName: input.actorName,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function getManualReviewerStages(template: PerformanceSurveyTemplateShape) {
|
||||
return (template.workflow?.stages || []).filter((stage) => (
|
||||
stage.reviewers.some((reviewer) => reviewer.source === 'manual_selection')
|
||||
))
|
||||
}
|
||||
|
||||
export function getReviewerSources(template: PerformanceSurveyTemplateShape) {
|
||||
return (template.workflow?.stages || []).flatMap((stage) => stage.reviewers)
|
||||
}
|
||||
|
||||
export function findWorkflowReviewer(
|
||||
template: PerformanceSurveyTemplateShape,
|
||||
stageKey: string,
|
||||
source: string,
|
||||
): PerformanceSurveyWorkflowReviewer | null {
|
||||
return template.workflow?.stages
|
||||
.find((stage) => stage.key === stageKey)
|
||||
?.reviewers.find((reviewer) => reviewer.source === source) || null
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -25,7 +25,47 @@ export type PerformanceSurveyScoreBand = {
|
||||
|
||||
export type PerformanceSurveyAggregationStrategy = 'trim_extremes' | 'direct_average'
|
||||
|
||||
export type PerformanceSurveyReviewerSource =
|
||||
| 'self'
|
||||
| 'direct_manager'
|
||||
| 'fixed_employee'
|
||||
| 'manual_selection'
|
||||
|
||||
export type PerformanceSurveyWorkflowReviewer = {
|
||||
source: PerformanceSurveyReviewerSource
|
||||
label: string
|
||||
employeeId?: string
|
||||
employeeName?: string
|
||||
}
|
||||
|
||||
export type PerformanceSurveyWorkflowStage = {
|
||||
key: string
|
||||
label: string
|
||||
order: number
|
||||
reviewers: PerformanceSurveyWorkflowReviewer[]
|
||||
}
|
||||
|
||||
export type PerformanceSurveyWorkflowScoring =
|
||||
| {
|
||||
mode: 'final_reviewer'
|
||||
stageKey: string
|
||||
reviewerSource: PerformanceSurveyReviewerSource
|
||||
}
|
||||
| {
|
||||
mode: 'average_reviewers'
|
||||
stageKeys?: string[]
|
||||
}
|
||||
|
||||
export type PerformanceSurveyWorkflowDefinition = {
|
||||
stages: PerformanceSurveyWorkflowStage[]
|
||||
scoring: PerformanceSurveyWorkflowScoring
|
||||
}
|
||||
|
||||
export type PerformanceSurveyTemplateShape = {
|
||||
templateVersionId?: string
|
||||
templateVersion?: number
|
||||
templateVersionStatus?: 'draft' | 'published' | 'archived'
|
||||
effectiveMonth?: string | null
|
||||
code: string
|
||||
templateVariant?: PerformanceSurveyTemplateVariant
|
||||
templateVariantName?: string
|
||||
@ -60,6 +100,7 @@ export type PerformanceSurveyTemplateShape = {
|
||||
belowBand?: string
|
||||
questions: PerformanceSurveyQuestion[]
|
||||
scoreBands: PerformanceSurveyScoreBand[]
|
||||
workflow?: PerformanceSurveyWorkflowDefinition
|
||||
}
|
||||
|
||||
export const PERFORMANCE_SURVEY_VISUAL_TEMPLATE_VARIANTS = {
|
||||
@ -109,6 +150,15 @@ export const DEFAULT_PERFORMANCE_SURVEY_TEMPLATES: PerformanceSurveyTemplateShap
|
||||
{ min: 81, max: 88, outMin: 70, outMax: 84, label: '满意度 88%-81%,对应 84-70 分' },
|
||||
{ min: 77, max: 80, outMin: 60, outMax: 69, label: '满意度 80%-77%,对应 69-60 分' },
|
||||
],
|
||||
workflow: {
|
||||
stages: [{
|
||||
key: 'review',
|
||||
label: '学员评价',
|
||||
order: 0,
|
||||
reviewers: [{ source: 'manual_selection', label: '评价人' }],
|
||||
}],
|
||||
scoring: { mode: 'average_reviewers', stageKeys: ['review'] },
|
||||
},
|
||||
},
|
||||
{
|
||||
code: 'cross_department',
|
||||
@ -149,6 +199,15 @@ export const DEFAULT_PERFORMANCE_SURVEY_TEMPLATES: PerformanceSurveyTemplateShap
|
||||
{ min: 70, max: 84.9, outMin: 70, outMax: 84, label: '评价尚可,还有进步空间,对应 84-70 分' },
|
||||
{ min: 60, max: 69.9, outMin: 60, outMax: 69, label: '评价一般,有较大进步空间,对应 69-60 分' },
|
||||
],
|
||||
workflow: {
|
||||
stages: [{
|
||||
key: 'review',
|
||||
label: '协同评价',
|
||||
order: 0,
|
||||
reviewers: [{ source: 'manual_selection', label: '评价人' }],
|
||||
}],
|
||||
scoring: { mode: 'average_reviewers', stageKeys: ['review'] },
|
||||
},
|
||||
},
|
||||
{
|
||||
code: 'work_cooperation',
|
||||
@ -189,6 +248,15 @@ export const DEFAULT_PERFORMANCE_SURVEY_TEMPLATES: PerformanceSurveyTemplateShap
|
||||
{ min: 70, max: 84.9, outMin: 70, outMax: 84, label: '评价尚可,还有进步空间,对应 84-70 分' },
|
||||
{ min: 60, max: 69.9, outMin: 60, outMax: 69, label: '评价一般,有较大进步空间,对应 69-60 分' },
|
||||
],
|
||||
workflow: {
|
||||
stages: [{
|
||||
key: 'manager_review',
|
||||
label: '主管评价',
|
||||
order: 0,
|
||||
reviewers: [{ source: 'direct_manager', label: '直属主管' }],
|
||||
}],
|
||||
scoring: { mode: 'final_reviewer', stageKey: 'manager_review', reviewerSource: 'direct_manager' },
|
||||
},
|
||||
},
|
||||
{
|
||||
code: 'visual_brand_tone',
|
||||
@ -232,6 +300,26 @@ export const DEFAULT_PERFORMANCE_SURVEY_TEMPLATES: PerformanceSurveyTemplateShap
|
||||
{ min: 70, max: 84.9, outMin: 70, outMax: 84, label: '评价尚可,还有进步空间' },
|
||||
{ min: 60, max: 69.9, outMin: 60, outMax: 69, label: '评价一般,有较大进步空间' },
|
||||
],
|
||||
workflow: {
|
||||
stages: [
|
||||
{
|
||||
key: 'self_review',
|
||||
label: '本人自评',
|
||||
order: 0,
|
||||
reviewers: [{ source: 'self', label: '本人' }],
|
||||
},
|
||||
{
|
||||
key: 'final_review',
|
||||
label: '终评',
|
||||
order: 1,
|
||||
reviewers: [
|
||||
{ source: 'direct_manager', label: '直属主管' },
|
||||
{ source: 'fixed_employee', label: '终审人', employeeName: '元泽' },
|
||||
],
|
||||
},
|
||||
],
|
||||
scoring: { mode: 'final_reviewer', stageKey: 'final_review', reviewerSource: 'fixed_employee' },
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
@ -289,15 +377,7 @@ export async function ensurePerformanceSurveyTemplates() {
|
||||
for (const template of DEFAULT_PERFORMANCE_SURVEY_TEMPLATES) {
|
||||
await prisma.performanceSurveyTemplate.upsert({
|
||||
where: { code: template.code },
|
||||
update: {
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
surveyType: template.surveyType,
|
||||
weight: template.weight,
|
||||
questions: template.questions,
|
||||
scoreBands: template.scoreBands,
|
||||
isActive: true,
|
||||
},
|
||||
update: {},
|
||||
create: {
|
||||
code: template.code,
|
||||
name: template.name,
|
||||
|
||||
@ -12,6 +12,9 @@
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"test:coverage": "jest --coverage",
|
||||
"performance-survey:test-data:audit": "tsx scripts/performance-survey-test-data.ts --mode=audit",
|
||||
"performance-survey:test-data:clear": "tsx scripts/performance-survey-test-data.ts --mode=clear",
|
||||
"performance-survey:position-config:seed": "tsx scripts/seed-performance-survey-position-config.ts",
|
||||
"history:scan": "tsx scripts/scan-history-materials.ts",
|
||||
"history:import": "tsx scripts/import-history-materials.ts",
|
||||
"prisma:generate": "prisma generate",
|
||||
|
||||
@ -0,0 +1,149 @@
|
||||
CREATE TABLE IF NOT EXISTS "performance_survey_position_groups" (
|
||||
"id" TEXT PRIMARY KEY,
|
||||
"code" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"sort_order" INTEGER NOT NULL DEFAULT 0,
|
||||
"is_active" BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "performance_survey_position_groups_code_key"
|
||||
ON "performance_survey_position_groups" ("code");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_position_group_active_sort_idx"
|
||||
ON "performance_survey_position_groups" ("is_active", "sort_order");
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "performance_survey_position_rules" (
|
||||
"id" TEXT PRIMARY KEY,
|
||||
"position_group_id" TEXT NOT NULL,
|
||||
"department_path_prefix" TEXT,
|
||||
"position_title" TEXT,
|
||||
"sort_order" INTEGER NOT NULL DEFAULT 0,
|
||||
"is_active" BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "performance_survey_position_rules_group_fkey"
|
||||
FOREIGN KEY ("position_group_id") REFERENCES "performance_survey_position_groups"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_position_rule_group_idx"
|
||||
ON "performance_survey_position_rules" ("position_group_id", "is_active", "sort_order");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_position_rule_title_idx"
|
||||
ON "performance_survey_position_rules" ("position_title");
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "performance_survey_template_versions" (
|
||||
"id" TEXT PRIMARY KEY,
|
||||
"template_id" TEXT NOT NULL,
|
||||
"version" INTEGER NOT NULL,
|
||||
"status" TEXT NOT NULL DEFAULT 'draft',
|
||||
"effective_month" TEXT,
|
||||
"definition" JSONB NOT NULL,
|
||||
"published_at" TIMESTAMP(3),
|
||||
"created_by_user_id" TEXT,
|
||||
"created_by_name" TEXT,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "performance_survey_template_versions_template_fkey"
|
||||
FOREIGN KEY ("template_id") REFERENCES "performance_survey_templates"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "performance_survey_template_version_unique"
|
||||
ON "performance_survey_template_versions" ("template_id", "version");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_template_version_status_month_idx"
|
||||
ON "performance_survey_template_versions" ("status", "effective_month");
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "performance_survey_position_plans" (
|
||||
"id" TEXT PRIMARY KEY,
|
||||
"position_group_id" TEXT NOT NULL,
|
||||
"version" INTEGER NOT NULL,
|
||||
"status" TEXT NOT NULL DEFAULT 'draft',
|
||||
"effective_month" TEXT,
|
||||
"match_rules" JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
"published_at" TIMESTAMP(3),
|
||||
"created_by_user_id" TEXT,
|
||||
"created_by_name" TEXT,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "performance_survey_position_plans_group_fkey"
|
||||
FOREIGN KEY ("position_group_id") REFERENCES "performance_survey_position_groups"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "performance_survey_position_plan_version_unique"
|
||||
ON "performance_survey_position_plans" ("position_group_id", "version");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_position_plan_group_status_month_idx"
|
||||
ON "performance_survey_position_plans" ("position_group_id", "status", "effective_month");
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "performance_survey_position_plan_items" (
|
||||
"id" TEXT PRIMARY KEY,
|
||||
"position_plan_id" TEXT NOT NULL,
|
||||
"template_version_id" TEXT NOT NULL,
|
||||
"sort_order" INTEGER NOT NULL DEFAULT 0,
|
||||
"is_enabled" BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "performance_survey_position_plan_items_plan_fkey"
|
||||
FOREIGN KEY ("position_plan_id") REFERENCES "performance_survey_position_plans"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT "performance_survey_position_plan_items_template_version_fkey"
|
||||
FOREIGN KEY ("template_version_id") REFERENCES "performance_survey_template_versions"("id")
|
||||
ON DELETE RESTRICT ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "performance_survey_position_plan_item_unique"
|
||||
ON "performance_survey_position_plan_items" ("position_plan_id", "template_version_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_position_plan_item_sort_idx"
|
||||
ON "performance_survey_position_plan_items" ("position_plan_id", "is_enabled", "sort_order");
|
||||
|
||||
ALTER TABLE "performance_surveys"
|
||||
ADD COLUMN IF NOT EXISTS "template_version_id" TEXT,
|
||||
ADD COLUMN IF NOT EXISTS "position_group_id" TEXT,
|
||||
ADD COLUMN IF NOT EXISTS "position_group_code" TEXT,
|
||||
ADD COLUMN IF NOT EXISTS "position_group_snapshot" JSONB;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'performance_surveys_template_version_id_fkey') THEN
|
||||
ALTER TABLE "performance_surveys" ADD CONSTRAINT "performance_surveys_template_version_id_fkey"
|
||||
FOREIGN KEY ("template_version_id") REFERENCES "performance_survey_template_versions"("id")
|
||||
ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'performance_surveys_position_group_id_fkey') THEN
|
||||
ALTER TABLE "performance_surveys" ADD CONSTRAINT "performance_surveys_position_group_id_fkey"
|
||||
FOREIGN KEY ("position_group_id") REFERENCES "performance_survey_position_groups"("id")
|
||||
ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "performance_surveys_template_version_id_idx"
|
||||
ON "performance_surveys" ("template_version_id");
|
||||
CREATE INDEX IF NOT EXISTS "performance_surveys_position_group_month_idx"
|
||||
ON "performance_surveys" ("position_group_id", "assessment_month");
|
||||
CREATE INDEX IF NOT EXISTS "performance_surveys_position_group_code_month_idx"
|
||||
ON "performance_surveys" ("position_group_code", "assessment_month");
|
||||
|
||||
ALTER TABLE "performance_survey_assignments"
|
||||
ADD COLUMN IF NOT EXISTS "workflow_stage_key" TEXT NOT NULL DEFAULT 'legacy',
|
||||
ADD COLUMN IF NOT EXISTS "workflow_stage_order" INTEGER NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS "reviewer_source" TEXT NOT NULL DEFAULT 'manual_selection',
|
||||
ADD COLUMN IF NOT EXISTS "released_at" TIMESTAMP(3);
|
||||
|
||||
DROP INDEX IF EXISTS "performance_survey_assignment_target_evaluator_key";
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "performance_survey_assignment_target_evaluator_stage_key"
|
||||
ON "performance_survey_assignments" ("target_id", "evaluator_key", "workflow_stage_key");
|
||||
CREATE INDEX IF NOT EXISTS "performance_survey_assignment_stage_idx"
|
||||
ON "performance_survey_assignments" ("survey_id", "target_id", "workflow_stage_order");
|
||||
|
||||
INSERT INTO "performance_survey_position_groups"
|
||||
("id", "code", "name", "sort_order", "is_active", "created_at", "updated_at")
|
||||
VALUES
|
||||
('pspg-ai-planning-creative', 'ai_planning_creative', 'AI策划-创意部', 10, TRUE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
|
||||
('pspg-ai-planning-general', 'ai_planning_general', 'AI策划-综合部', 20, TRUE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
|
||||
('pspg-ai-technical-designer', 'ai_technical_designer', 'AI技术设计师', 30, TRUE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
|
||||
('pspg-brand-designer', 'brand_designer', '品牌设计师', 40, TRUE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
|
||||
('pspg-director', 'director', '编导', 50, TRUE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
|
||||
('pspg-camera', 'camera', '摄像', 60, TRUE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
|
||||
('pspg-editing', 'editing', '剪辑', 70, TRUE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
|
||||
('pspg-retouching', 'retouching', '修图', 80, TRUE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT ("code") DO NOTHING;
|
||||
@ -545,23 +545,112 @@ model PerformanceSurveyDepartmentProfile {
|
||||
}
|
||||
|
||||
model PerformanceSurveyTemplate {
|
||||
id String @id @default(uuid())
|
||||
code String @unique
|
||||
id String @id @default(uuid())
|
||||
code String @unique
|
||||
name String
|
||||
description String?
|
||||
surveyType String @default("person_period") @map("survey_type")
|
||||
weight Float @default(1)
|
||||
surveyType String @default("person_period") @map("survey_type")
|
||||
weight Float @default(1)
|
||||
questions Json
|
||||
scoreBands Json @map("score_bands")
|
||||
isActive Boolean @default(true) @map("is_active")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
scoreBands Json @map("score_bands")
|
||||
isActive Boolean @default(true) @map("is_active")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
versions PerformanceSurveyTemplateVersion[]
|
||||
|
||||
@@index([surveyType])
|
||||
@@index([isActive])
|
||||
@@map("performance_survey_templates")
|
||||
}
|
||||
|
||||
model PerformanceSurveyTemplateVersion {
|
||||
id String @id @default(uuid())
|
||||
templateId String @map("template_id")
|
||||
version Int
|
||||
status String @default("draft")
|
||||
effectiveMonth String? @map("effective_month")
|
||||
definition Json
|
||||
publishedAt DateTime? @map("published_at")
|
||||
createdByUserId String? @map("created_by_user_id")
|
||||
createdByName String? @map("created_by_name")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
template PerformanceSurveyTemplate @relation(fields: [templateId], references: [id], onDelete: Cascade)
|
||||
positionPlanItems PerformanceSurveyPositionPlanItem[]
|
||||
surveys PerformanceSurvey[]
|
||||
|
||||
@@unique([templateId, version], map: "performance_survey_template_version_unique")
|
||||
@@index([status, effectiveMonth], map: "performance_survey_template_version_status_month_idx")
|
||||
@@map("performance_survey_template_versions")
|
||||
}
|
||||
|
||||
model PerformanceSurveyPositionGroup {
|
||||
id String @id @default(uuid())
|
||||
code String @unique
|
||||
name String
|
||||
sortOrder Int @default(0) @map("sort_order")
|
||||
isActive Boolean @default(true) @map("is_active")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
rules PerformanceSurveyPositionRule[]
|
||||
plans PerformanceSurveyPositionPlan[]
|
||||
surveys PerformanceSurvey[]
|
||||
|
||||
@@index([isActive, sortOrder], map: "performance_survey_position_group_active_sort_idx")
|
||||
@@map("performance_survey_position_groups")
|
||||
}
|
||||
|
||||
model PerformanceSurveyPositionRule {
|
||||
id String @id @default(uuid())
|
||||
positionGroupId String @map("position_group_id")
|
||||
departmentPathPrefix String? @map("department_path_prefix")
|
||||
positionTitle String? @map("position_title")
|
||||
sortOrder Int @default(0) @map("sort_order")
|
||||
isActive Boolean @default(true) @map("is_active")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
positionGroup PerformanceSurveyPositionGroup @relation(fields: [positionGroupId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([positionGroupId, isActive, sortOrder], map: "performance_survey_position_rule_group_idx")
|
||||
@@index([positionTitle], map: "performance_survey_position_rule_title_idx")
|
||||
@@map("performance_survey_position_rules")
|
||||
}
|
||||
|
||||
model PerformanceSurveyPositionPlan {
|
||||
id String @id @default(uuid())
|
||||
positionGroupId String @map("position_group_id")
|
||||
version Int
|
||||
status String @default("draft")
|
||||
effectiveMonth String? @map("effective_month")
|
||||
matchRules Json @default("[]") @map("match_rules")
|
||||
publishedAt DateTime? @map("published_at")
|
||||
createdByUserId String? @map("created_by_user_id")
|
||||
createdByName String? @map("created_by_name")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
positionGroup PerformanceSurveyPositionGroup @relation(fields: [positionGroupId], references: [id], onDelete: Cascade)
|
||||
items PerformanceSurveyPositionPlanItem[]
|
||||
|
||||
@@unique([positionGroupId, version], map: "performance_survey_position_plan_version_unique")
|
||||
@@index([positionGroupId, status, effectiveMonth], map: "performance_survey_position_plan_group_status_month_idx")
|
||||
@@map("performance_survey_position_plans")
|
||||
}
|
||||
|
||||
model PerformanceSurveyPositionPlanItem {
|
||||
id String @id @default(uuid())
|
||||
positionPlanId String @map("position_plan_id")
|
||||
templateVersionId String @map("template_version_id")
|
||||
sortOrder Int @default(0) @map("sort_order")
|
||||
isEnabled Boolean @default(true) @map("is_enabled")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
positionPlan PerformanceSurveyPositionPlan @relation(fields: [positionPlanId], references: [id], onDelete: Cascade)
|
||||
templateVersion PerformanceSurveyTemplateVersion @relation(fields: [templateVersionId], references: [id], onDelete: Restrict)
|
||||
|
||||
@@unique([positionPlanId, templateVersionId], map: "performance_survey_position_plan_item_unique")
|
||||
@@index([positionPlanId, isEnabled, sortOrder], map: "performance_survey_position_plan_item_sort_idx")
|
||||
@@map("performance_survey_position_plan_items")
|
||||
}
|
||||
|
||||
model PerformanceSurvey {
|
||||
id String @id @default(uuid())
|
||||
title String
|
||||
@ -569,6 +658,10 @@ model PerformanceSurvey {
|
||||
surveyKind String @default("person_period") @map("survey_kind")
|
||||
templateCode String @map("template_code")
|
||||
templateSnapshot Json @map("template_snapshot")
|
||||
templateVersionId String? @map("template_version_id")
|
||||
positionGroupId String? @map("position_group_id")
|
||||
positionGroupCode String? @map("position_group_code")
|
||||
positionGroupSnapshot Json? @map("position_group_snapshot")
|
||||
status String @default("draft")
|
||||
creatorUserId String @map("creator_user_id")
|
||||
creatorName String @map("creator_name")
|
||||
@ -590,10 +683,15 @@ model PerformanceSurvey {
|
||||
workItems PerformanceSurveyWorkItem[]
|
||||
workItemScores PerformanceSurveyWorkItemScore[]
|
||||
notifications PerformanceSurveyNotification[]
|
||||
templateVersion PerformanceSurveyTemplateVersion? @relation(fields: [templateVersionId], references: [id], onDelete: SetNull)
|
||||
positionGroup PerformanceSurveyPositionGroup? @relation(fields: [positionGroupId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([status])
|
||||
@@index([surveyKind])
|
||||
@@index([templateCode])
|
||||
@@index([templateVersionId])
|
||||
@@index([positionGroupId, assessmentMonth], map: "performance_surveys_position_group_month_idx")
|
||||
@@index([positionGroupCode, assessmentMonth], map: "performance_surveys_position_group_code_month_idx")
|
||||
@@index([templateCode, assessmentMonth], map: "performance_surveys_template_month_idx")
|
||||
@@index([creatorUserId])
|
||||
@@index([departmentName])
|
||||
@ -636,6 +734,10 @@ model PerformanceSurveyAssignment {
|
||||
evaluatorKey String @map("evaluator_key")
|
||||
evaluatorName String @map("evaluator_name")
|
||||
evaluatorSnapshot Json @map("evaluator_snapshot")
|
||||
workflowStageKey String @default("legacy") @map("workflow_stage_key")
|
||||
workflowStageOrder Int @default(0) @map("workflow_stage_order")
|
||||
reviewerSource String @default("manual_selection") @map("reviewer_source")
|
||||
releasedAt DateTime? @map("released_at")
|
||||
status String @default("pending")
|
||||
submittedAt DateTime? @map("submitted_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
@ -647,13 +749,14 @@ model PerformanceSurveyAssignment {
|
||||
workItemScores PerformanceSurveyWorkItemScore[]
|
||||
notifications PerformanceSurveyNotification[]
|
||||
|
||||
@@unique([targetId, evaluatorKey], map: "performance_survey_assignment_target_evaluator_key")
|
||||
@@unique([targetId, evaluatorKey, workflowStageKey], map: "performance_survey_assignment_target_evaluator_stage_key")
|
||||
@@index([surveyId])
|
||||
@@index([targetId])
|
||||
@@index([evaluatorEmployeeId])
|
||||
@@index([evaluatorUserId])
|
||||
@@index([evaluatorDingtalkUserId])
|
||||
@@index([evaluatorKey])
|
||||
@@index([surveyId, targetId, workflowStageOrder], map: "performance_survey_assignment_stage_idx")
|
||||
@@index([status])
|
||||
@@map("performance_survey_assignments")
|
||||
}
|
||||
|
||||
152
scripts/performance-survey-test-data.ts
Normal file
152
scripts/performance-survey-test-data.ts
Normal file
@ -0,0 +1,152 @@
|
||||
import { createHash } from 'crypto'
|
||||
import { mkdir, readFile, writeFile } from 'fs/promises'
|
||||
import path from 'path'
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
|
||||
const prisma = new PrismaClient()
|
||||
const mode = readArg('mode') || 'audit'
|
||||
const outputPath = readArg('output') || path.join(
|
||||
'.performance-survey-audits',
|
||||
`test-surveys-${new Date().toISOString().replace(/[:.]/g, '-')}.json`,
|
||||
)
|
||||
const planPath = readArg('plan')
|
||||
const confirmed = process.argv.includes('--confirm-all-current-surveys-are-test-data')
|
||||
const expectedSurveyCount = Number(readArg('expected-survey-count'))
|
||||
|
||||
function readArg(name: string) {
|
||||
const prefix = `--${name}=`
|
||||
const inline = process.argv.find((item) => item.startsWith(prefix))
|
||||
if (inline) return inline.slice(prefix.length)
|
||||
const index = process.argv.indexOf(`--${name}`)
|
||||
return index >= 0 ? process.argv[index + 1] || '' : ''
|
||||
}
|
||||
|
||||
function hashIds(ids: string[]) {
|
||||
return createHash('sha256').update([...ids].sort().join('\n')).digest('hex')
|
||||
}
|
||||
|
||||
function getDatabaseIdentity() {
|
||||
const raw = process.env.DATABASE_URL
|
||||
if (!raw) throw new Error('缺少 DATABASE_URL')
|
||||
const url = new URL(raw)
|
||||
return {
|
||||
provider: url.protocol.replace(':', ''),
|
||||
host: url.hostname,
|
||||
port: url.port || '5432',
|
||||
database: url.pathname.replace(/^\//, ''),
|
||||
schema: url.searchParams.get('schema') || 'public',
|
||||
}
|
||||
}
|
||||
|
||||
async function collectSnapshot() {
|
||||
const surveys = await prisma.performanceSurvey.findMany({
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
templateCode: true,
|
||||
status: true,
|
||||
createdAt: true,
|
||||
_count: {
|
||||
select: {
|
||||
targets: true,
|
||||
assignments: true,
|
||||
responses: true,
|
||||
workItems: true,
|
||||
workItemScores: true,
|
||||
notifications: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
const surveyIds = surveys.map((survey) => survey.id)
|
||||
const totals = surveys.reduce((result, survey) => {
|
||||
result.targets += survey._count.targets
|
||||
result.assignments += survey._count.assignments
|
||||
result.responses += survey._count.responses
|
||||
result.workItems += survey._count.workItems
|
||||
result.workItemScores += survey._count.workItemScores
|
||||
result.notifications += survey._count.notifications
|
||||
return result
|
||||
}, { targets: 0, assignments: 0, responses: 0, workItems: 0, workItemScores: 0, notifications: 0 })
|
||||
return {
|
||||
database: getDatabaseIdentity(),
|
||||
surveyIds,
|
||||
surveyIdsHash: hashIds(surveyIds),
|
||||
counts: { surveys: surveys.length, ...totals },
|
||||
surveys: surveys.map((survey) => ({
|
||||
id: survey.id,
|
||||
title: survey.title,
|
||||
templateCode: survey.templateCode,
|
||||
status: survey.status,
|
||||
createdAt: survey.createdAt.toISOString(),
|
||||
counts: survey._count,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
async function audit() {
|
||||
const snapshot = await collectSnapshot()
|
||||
const manifest = {
|
||||
manifestVersion: 1,
|
||||
purpose: 'performance-survey-test-data-clearance',
|
||||
createdAt: new Date().toISOString(),
|
||||
...snapshot,
|
||||
}
|
||||
const absoluteOutput = path.resolve(outputPath)
|
||||
await mkdir(path.dirname(absoluteOutput), { recursive: true })
|
||||
await writeFile(absoluteOutput, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8')
|
||||
console.log(JSON.stringify({ output: absoluteOutput, database: manifest.database, counts: manifest.counts }, null, 2))
|
||||
}
|
||||
|
||||
async function clear() {
|
||||
if (!planPath) throw new Error('清理模式必须传入 --plan <审计清单>')
|
||||
if (!confirmed) throw new Error('清理模式必须显式传入 --confirm-all-current-surveys-are-test-data')
|
||||
if (!Number.isInteger(expectedSurveyCount) || expectedSurveyCount < 0) {
|
||||
throw new Error('清理模式必须传入 --expected-survey-count <审计确认的调研数量>')
|
||||
}
|
||||
const manifest = JSON.parse(await readFile(path.resolve(planPath), 'utf8')) as {
|
||||
manifestVersion: number
|
||||
purpose: string
|
||||
database: ReturnType<typeof getDatabaseIdentity>
|
||||
surveyIds: string[]
|
||||
surveyIdsHash: string
|
||||
counts: { surveys: number }
|
||||
}
|
||||
if (manifest.manifestVersion !== 1 || manifest.purpose !== 'performance-survey-test-data-clearance') {
|
||||
throw new Error('审计清单类型或版本无效')
|
||||
}
|
||||
if (JSON.stringify(manifest.database) !== JSON.stringify(getDatabaseIdentity())) {
|
||||
throw new Error('审计清单数据库身份与当前连接不一致,已拒绝清理')
|
||||
}
|
||||
if (hashIds(manifest.surveyIds) !== manifest.surveyIdsHash) throw new Error('审计清单校验失败')
|
||||
if (manifest.counts.surveys !== expectedSurveyCount) {
|
||||
throw new Error(`审计清单包含 ${manifest.counts.surveys} 条调研,与明确确认数量 ${expectedSurveyCount} 不一致`)
|
||||
}
|
||||
|
||||
const current = await collectSnapshot()
|
||||
if (current.surveyIdsHash !== manifest.surveyIdsHash || current.counts.surveys !== manifest.counts.surveys) {
|
||||
throw new Error('审计后调研数据已经变化,请重新生成审计清单')
|
||||
}
|
||||
const result = await prisma.performanceSurvey.deleteMany({ where: { id: { in: manifest.surveyIds } } })
|
||||
const remaining = await prisma.performanceSurvey.count()
|
||||
if (result.count !== manifest.surveyIds.length || remaining !== 0) {
|
||||
throw new Error(`清理结果不一致:计划 ${manifest.surveyIds.length},已删除 ${result.count},剩余 ${remaining}`)
|
||||
}
|
||||
console.log(JSON.stringify({ deletedSurveys: result.count, remainingSurveys: remaining }, null, 2))
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (mode === 'audit') return audit()
|
||||
if (mode === 'clear') return clear()
|
||||
throw new Error(`未知模式:${mode}`)
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((error) => {
|
||||
console.error(error instanceof Error ? error.message : error)
|
||||
process.exitCode = 1
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect()
|
||||
})
|
||||
21
scripts/seed-performance-survey-position-config.ts
Normal file
21
scripts/seed-performance-survey-position-config.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { prisma } from '../lib/prisma'
|
||||
import { seedPerformanceSurveyPositionConfiguration } from '../lib/performance-survey-position-config'
|
||||
|
||||
async function main() {
|
||||
await seedPerformanceSurveyPositionConfiguration()
|
||||
const [positionGroupCount, templateVersionCount, positionPlanCount] = await Promise.all([
|
||||
prisma.performanceSurveyPositionGroup.count(),
|
||||
prisma.performanceSurveyTemplateVersion.count(),
|
||||
prisma.performanceSurveyPositionPlan.count(),
|
||||
])
|
||||
console.log(JSON.stringify({ positionGroupCount, templateVersionCount, positionPlanCount }, null, 2))
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((error) => {
|
||||
console.error(error instanceof Error ? error.message : error)
|
||||
process.exitCode = 1
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect()
|
||||
})
|
||||
Loading…
x
Reference in New Issue
Block a user