refactor: 考核模板改为单配置模式
This commit is contained in:
parent
30947f013f
commit
18835e4a6b
@ -101,6 +101,7 @@ COPY --from=builder --chown=nextjs:nodejs /app/node_modules/@smithy ./node_modul
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/prisma/schema.prisma ./prisma/schema.prisma
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/lib ./lib
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/scripts/public-traffic-rollup-from-nginx.py ./scripts/public-traffic-rollup-from-nginx.py
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/scripts/collapse-performance-survey-template-versions.mjs ./scripts/collapse-performance-survey-template-versions.mjs
|
||||
|
||||
# 创建必要目录并设置权限
|
||||
RUN mkdir -p /app/public /app/uploads && \
|
||||
|
||||
@ -36,7 +36,6 @@ import {
|
||||
savePerformanceSurveyAdminPositionGroup,
|
||||
publishPerformanceSurveyAdminPositionGroup,
|
||||
savePerformanceSurveyAdminTemplate,
|
||||
clonePerformanceSurveyAdminTemplateVersion,
|
||||
copyPerformanceSurveyAdminTemplateVersion,
|
||||
publishPerformanceSurveyAdminTemplateVersion,
|
||||
archivePerformanceSurveyAdminPositionAssignment,
|
||||
@ -295,10 +294,6 @@ export async function POST(request: Request, context: RouteContext) {
|
||||
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] === 'copy') {
|
||||
return ok(await copyPerformanceSurveyAdminTemplateVersion(session, path[2]), { status: 201 })
|
||||
}
|
||||
|
||||
@ -142,10 +142,12 @@ function createRequest(configuration = config) {
|
||||
if (path === '/admin/templates/template-1' && options?.method === 'DELETE') {
|
||||
return { id: 'template-1', action: 'deleted' }
|
||||
}
|
||||
if (path === '/admin/templates/version-1' && options?.method === 'PATCH') {
|
||||
return { id: 'version-1' }
|
||||
}
|
||||
if (path.endsWith('/copy')) {
|
||||
return { id: 'copied-version-1', templateId: 'copied-template-1', name: '视觉案例评分(副本)' }
|
||||
}
|
||||
if (path.endsWith('/clone')) return { id: 'draft-version-2' }
|
||||
return {}
|
||||
})
|
||||
}
|
||||
@ -356,15 +358,11 @@ describe('PerformanceSurveyAdminConfig', () => {
|
||||
...template,
|
||||
versions: [{
|
||||
...template.versions[0],
|
||||
id: 'version-draft-2',
|
||||
version: 2,
|
||||
status: 'draft',
|
||||
effectiveMonth: null,
|
||||
definition: {
|
||||
...template.versions[0].definition,
|
||||
name: '品牌创意部门',
|
||||
},
|
||||
}, template.versions[0]],
|
||||
}],
|
||||
}
|
||||
: template),
|
||||
}
|
||||
@ -375,9 +373,9 @@ describe('PerformanceSurveyAdminConfig', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: '修改岗位' }))
|
||||
fireEvent.change(screen.getByLabelText('添加考核项'), { target: { value: '品牌创意部门' } })
|
||||
|
||||
const option = screen.getByRole('button', { name: /品牌创意部门.*v1/ })
|
||||
const option = screen.getByRole('button', { name: /品牌创意部门.*已发布/ })
|
||||
expect(option).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: /视觉案例评分.*v1/ })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: /视觉案例评分.*已发布/ })).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.click(option)
|
||||
expect(screen.getByText('品牌创意部门')).toBeInTheDocument()
|
||||
@ -425,22 +423,34 @@ describe('PerformanceSurveyAdminConfig', () => {
|
||||
})
|
||||
})
|
||||
|
||||
test('已发布模板通过修改按钮生成草稿,并使用统一的删除入口', async () => {
|
||||
test('已发布模板通过修改按钮直接更新原版本,并使用统一的删除入口', async () => {
|
||||
const request = createRequest()
|
||||
render(<PerformanceSurveyAdminConfig mode="templates" request={request} />)
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: /视觉案例评分.*可用/ })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: '修改模板' }))
|
||||
await waitFor(() => expect(request).toHaveBeenCalledWith('/admin/templates/version-1/clone', expect.objectContaining({ method: 'POST' })))
|
||||
|
||||
fireEvent.change(screen.getByLabelText('模板名称'), { target: { value: '新视觉评分' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: '发布模板' }))
|
||||
expect(await screen.findByText('请先保存模板草稿,再执行发布')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: '保存修改' }))
|
||||
await waitFor(() => expect(request).toHaveBeenCalledWith(
|
||||
'/admin/templates/version-1',
|
||||
expect.objectContaining({ method: 'PATCH' }),
|
||||
))
|
||||
expect(request.mock.calls.some(([path]) => path === '/admin/templates/version-1/clone')).toBe(false)
|
||||
expect(screen.getByRole('button', { name: '删除模板' })).toBeInTheDocument()
|
||||
expect(screen.queryByText('使用场景')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('已发布模板可通过修改按钮左侧的复制按钮创建独立草稿', async () => {
|
||||
test('新增模板按钮位于删除模板左侧', async () => {
|
||||
const request = createRequest()
|
||||
render(<PerformanceSurveyAdminConfig mode="templates" request={request} />)
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: /视觉案例评分.*可用/ })).toBeInTheDocument())
|
||||
|
||||
const createButton = screen.getByRole('button', { name: '新增模板' })
|
||||
const deleteButton = screen.getByRole('button', { name: '删除模板' })
|
||||
expect(createButton.nextElementSibling).toBe(deleteButton)
|
||||
})
|
||||
|
||||
test('已发布模板可通过修改按钮左侧的复制按钮创建独立模板草稿', async () => {
|
||||
const request = createRequest()
|
||||
render(<PerformanceSurveyAdminConfig mode="templates" request={request} />)
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: /视觉案例评分.*可用/ })).toBeInTheDocument())
|
||||
@ -457,7 +467,7 @@ describe('PerformanceSurveyAdminConfig', () => {
|
||||
))
|
||||
})
|
||||
|
||||
test('模板列表将所有已发布版本视为立即可用', async () => {
|
||||
test('模板列表只展示单一当前配置状态', async () => {
|
||||
const configuration = {
|
||||
...config,
|
||||
templates: [{
|
||||
@ -511,8 +521,8 @@ describe('PerformanceSurveyAdminConfig', () => {
|
||||
const request = createRequest(configuration)
|
||||
render(<PerformanceSurveyAdminConfig mode="templates" request={request} />)
|
||||
|
||||
const changedTemplate = await screen.findByRole('button', { name: /视觉案例评分.*有待发布修改/ })
|
||||
expect(within(changedTemplate).getByRole('img', { name: '有待发布修改' })).toHaveAttribute('data-status-dot', 'warning')
|
||||
const changedTemplate = await screen.findByRole('button', { name: /视觉案例评分.*可用/ })
|
||||
expect(within(changedTemplate).getByRole('img', { name: '可用' })).toHaveAttribute('data-status-dot', 'success')
|
||||
const publishedTemplate = screen.getByRole('button', { name: /课程分享.*可用/ })
|
||||
expect(within(publishedTemplate).getByRole('img', { name: '可用' })).toHaveAttribute('data-status-dot', 'success')
|
||||
const draftTemplate = screen.getByRole('button', { name: /草稿模板.*待发布/ })
|
||||
|
||||
@ -284,7 +284,11 @@ function getTemplateAvailability(template: TemplateRecord, _month: string) {
|
||||
const publishedVersions = template.versions.filter((version) => version.status === 'published')
|
||||
const availableVersion = publishedVersions
|
||||
.sort((left, right) => right.version - left.version)[0] || null
|
||||
const draftVersion = template.versions.find((version) => version.status === 'draft') || null
|
||||
const draftVersion = availableVersion
|
||||
? null
|
||||
: template.versions
|
||||
.filter((version) => version.status === 'draft')
|
||||
.sort((left, right) => right.version - left.version)[0] || null
|
||||
return {
|
||||
isAvailable: template.isActive && Boolean(availableVersion),
|
||||
availableVersion,
|
||||
@ -293,7 +297,9 @@ function getTemplateAvailability(template: TemplateRecord, _month: string) {
|
||||
}
|
||||
|
||||
function getTemplateDisplayName(template: TemplateRecord) {
|
||||
return template.versions[0]?.definition.name?.trim() || template.name
|
||||
const current = getTemplateAvailability(template, '').availableVersion
|
||||
|| getTemplateAvailability(template, '').draftVersion
|
||||
return current?.definition.name?.trim() || template.name
|
||||
}
|
||||
|
||||
function getTemplateListState(template: TemplateRecord, month: string): {
|
||||
@ -307,16 +313,16 @@ function getTemplateListState(template: TemplateRecord, month: string): {
|
||||
}
|
||||
if (availability.draftVersion) {
|
||||
return {
|
||||
label: availability.availableVersion ? '有待发布修改' : '待发布',
|
||||
label: '待发布',
|
||||
tone: 'warning',
|
||||
meta: `v${availability.draftVersion.version} · 草稿`,
|
||||
meta: '草稿',
|
||||
}
|
||||
}
|
||||
if (availability.availableVersion) {
|
||||
return {
|
||||
label: '可用',
|
||||
tone: 'success',
|
||||
meta: `v${availability.availableVersion.version} · 已发布`,
|
||||
meta: '已发布',
|
||||
}
|
||||
}
|
||||
return { label: '不可用', tone: 'neutral', meta: '' }
|
||||
@ -658,7 +664,7 @@ function AdminOverviewWorkspace({
|
||||
status: templatesReady ? (draftTemplates > 0 ? 'attention' : 'done') : 'blocked',
|
||||
summary: templatesReady
|
||||
? `${availablePublishedTemplates} 个已发布模板可用${draftTemplates > 0 ? `,${draftTemplates} 个草稿待确认` : ''}`
|
||||
: `还没有可用的已发布模板${publishedTemplates > 0 ? `(另有 ${publishedTemplates} 个不可用版本)` : ''}`,
|
||||
: `还没有可用的已发布模板${publishedTemplates > 0 ? `(另有 ${publishedTemplates} 个模板尚不可用)` : ''}`,
|
||||
action: '管理模板',
|
||||
target: 'templates' as const,
|
||||
},
|
||||
@ -1144,7 +1150,7 @@ function PositionConfigWorkspace({
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate text-[13px] font-bold text-[#1a1c1c]">{getTemplateDisplayName(template)}</span>
|
||||
</span>
|
||||
<span className="shrink-0 text-[11px] text-[#5f5e5e]">v{version.version}</span>
|
||||
<span className="shrink-0 text-[11px] text-[#5f5e5e]">已发布</span>
|
||||
</button>
|
||||
))}
|
||||
{searchResults.length === 0 && (
|
||||
@ -1161,7 +1167,7 @@ function PositionConfigWorkspace({
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-[13px] font-bold text-[#1a1c1c]">{item ? getTemplateDisplayName(item.template) : '历史模板'}</div>
|
||||
<div className="mt-0.5 text-[11px] text-[#727687]">
|
||||
第 {index + 1} 项{item ? ` · v${item.version.version}` : ''}
|
||||
第 {index + 1} 项
|
||||
</div>
|
||||
</div>
|
||||
{editing && (
|
||||
@ -1246,13 +1252,16 @@ function TemplateConfigWorkspace({
|
||||
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 selectedVersion = selectedTemplate
|
||||
? getTemplateAvailability(selectedTemplate, month).availableVersion
|
||||
|| getTemplateAvailability(selectedTemplate, month).draftVersion
|
||||
|| null
|
||||
: null
|
||||
const [versionId, setVersionId] = useState<string | null>(selectedVersion?.id || null)
|
||||
const [definition, setDefinition] = useState<TemplateDefinition>(() => clone(selectedVersion?.definition || newTemplateDefinition()))
|
||||
const [editorStep, setEditorStep] = useState<TemplateEditorStep>('basics')
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [editingPublishedVersion, setEditingPublishedVersion] = useState(false)
|
||||
const [readinessOpen, setReadinessOpen] = useState(false)
|
||||
const [operationFeedback, setOperationFeedback] = useState<{
|
||||
state: 'idle' | 'saving' | 'saved' | 'publishing' | 'published' | 'error'
|
||||
@ -1261,19 +1270,21 @@ function TemplateConfigWorkspace({
|
||||
const editorRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const nextVersion = selectedTemplate?.versions.find((version) => version.status === 'draft')
|
||||
|| selectedTemplate?.versions[0]
|
||||
|| null
|
||||
const availability = selectedTemplate ? getTemplateAvailability(selectedTemplate, month) : null
|
||||
const nextVersion = availability?.availableVersion || availability?.draftVersion || null
|
||||
const nextDefinition = clone(nextVersion?.definition || newTemplateDefinition())
|
||||
setVersionId(nextVersion?.id || null)
|
||||
setDefinition(nextDefinition)
|
||||
setEditorStep('basics')
|
||||
setEditingPublishedVersion(false)
|
||||
setReadinessOpen(false)
|
||||
onDirtyChange(false)
|
||||
}, [onDirtyChange, selectedTemplate])
|
||||
}, [month, onDirtyChange, selectedTemplate])
|
||||
|
||||
const version = selectedTemplate?.versions.find((item) => item.id === versionId) || null
|
||||
const editable = !version || version.status === 'draft'
|
||||
const editable = !version
|
||||
|| version.status === 'draft'
|
||||
|| (version.status === 'published' && editingPublishedVersion)
|
||||
const readinessItems = getTemplateReadiness(definition)
|
||||
const readinessCompleted = readinessItems.filter((item) => item.status === 'done').length
|
||||
const templateDefinitionReady = readinessCompleted === readinessItems.length
|
||||
@ -1285,9 +1296,13 @@ function TemplateConfigWorkspace({
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
const updatingPublishedVersion = version?.status === 'published'
|
||||
setSaving(true)
|
||||
onError(null)
|
||||
setOperationFeedback({ state: 'saving', message: '正在保存模板草稿…' })
|
||||
setOperationFeedback({
|
||||
state: 'saving',
|
||||
message: updatingPublishedVersion ? '正在保存模板修改…' : '正在保存模板草稿…',
|
||||
})
|
||||
try {
|
||||
const saved = versionId
|
||||
? await request<{ id: string }>(`/admin/templates/${versionId}`, {
|
||||
@ -1298,19 +1313,25 @@ function TemplateConfigWorkspace({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ definition }),
|
||||
})
|
||||
const next = await onChanged('模板草稿已保存')
|
||||
const next = await onChanged(updatingPublishedVersion ? '模板修改已保存' : '模板草稿已保存')
|
||||
const nextTemplate = next?.templates.find((template) => template.versions.some((item) => item.id === saved.id))
|
||||
if (nextTemplate) setSelectedTemplateId(nextTemplate.id)
|
||||
setVersionId(saved.id)
|
||||
setEditingPublishedVersion(false)
|
||||
onDirtyChange(false)
|
||||
const savedTime = new Intl.DateTimeFormat('zh-CN', {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
}).format(new Date())
|
||||
setOperationFeedback({ state: 'saved', message: `草稿已保存 · ${savedTime}` })
|
||||
setOperationFeedback({
|
||||
state: 'saved',
|
||||
message: `${updatingPublishedVersion ? '修改' : '草稿'}已保存 · ${savedTime}`,
|
||||
})
|
||||
} catch (actionError) {
|
||||
const message = actionError instanceof Error ? actionError.message : '模板草稿保存失败'
|
||||
const message = actionError instanceof Error
|
||||
? actionError.message
|
||||
: updatingPublishedVersion ? '模板修改保存失败' : '模板草稿保存失败'
|
||||
onError(message)
|
||||
setOperationFeedback({ state: 'error', message: `保存失败:${message}` })
|
||||
} finally {
|
||||
@ -1318,27 +1339,6 @@ function TemplateConfigWorkspace({
|
||||
}
|
||||
}
|
||||
|
||||
const cloneVersion = async () => {
|
||||
if (!versionId || !await confirmDiscard()) return
|
||||
setSaving(true)
|
||||
onError(null)
|
||||
setOperationFeedback({ state: 'saving', message: '正在创建可编辑草稿…' })
|
||||
try {
|
||||
const draft = await request<{ id: string }>(`/admin/templates/${versionId}/clone`, { method: 'POST', body: '{}' })
|
||||
const next = await onChanged('已创建新的模板草稿')
|
||||
const nextTemplate = next?.templates.find((template) => template.versions.some((item) => item.id === draft.id))
|
||||
if (nextTemplate) setSelectedTemplateId(nextTemplate.id)
|
||||
setVersionId(draft.id)
|
||||
setOperationFeedback({ state: 'saved', message: '新的可编辑草稿已创建' })
|
||||
} catch (actionError) {
|
||||
const message = actionError instanceof Error ? actionError.message : '模板草稿创建失败'
|
||||
onError(message)
|
||||
setOperationFeedback({ state: 'error', message: `创建草稿失败:${message}` })
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const copyTemplate = async () => {
|
||||
if (!versionId || !selectedTemplate || !await confirmDiscard()) return
|
||||
setSaving(true)
|
||||
@ -1388,7 +1388,7 @@ function TemplateConfigWorkspace({
|
||||
{surveyTypeLabel(definition.surveyType)} · {definition.questions.length} 个评分项 ·
|
||||
{' '}{definition.workflow.stages.length} 个评分阶段 · 总分 {Number(definition.maxTotal || 0)}
|
||||
</p>
|
||||
<p>发布后的版本不可直接修改;后续调整需要创建新的草稿版本。</p>
|
||||
<p>发布后仍可通过“修改模板”更新当前模板;已经发起的调研会保留原始模板快照。</p>
|
||||
</div>
|
||||
),
|
||||
confirmLabel: '确认发布',
|
||||
@ -1459,14 +1459,12 @@ function TemplateConfigWorkspace({
|
||||
}
|
||||
}
|
||||
|
||||
const selectVersion = async (nextVersion: TemplateVersion) => {
|
||||
if (nextVersion.id === versionId) return
|
||||
if (!await confirmDiscard('切换版本会放弃当前未保存修改,确定继续吗?')) return
|
||||
const cancelPublishedEdit = async () => {
|
||||
if (dirty && !await confirmDiscard('取消修改会放弃当前未保存内容,确定继续吗?')) return
|
||||
if (version) setDefinition(clone(version.definition))
|
||||
setEditingPublishedVersion(false)
|
||||
onDirtyChange(false)
|
||||
setOperationFeedback({ state: 'idle', message: '' })
|
||||
setVersionId(nextVersion.id)
|
||||
setDefinition(clone(nextVersion.definition))
|
||||
setEditorStep('basics')
|
||||
}
|
||||
|
||||
const selectedTemplateName = selectedTemplate
|
||||
@ -1479,7 +1477,7 @@ function TemplateConfigWorkspace({
|
||||
? operationFeedback.message || '处理中'
|
||||
: dirty
|
||||
? '未保存'
|
||||
: operationFeedback.message || (editable ? '已保存' : '只读')
|
||||
: operationFeedback.message || (editingPublishedVersion ? '可修改' : editable ? '已保存' : '只读')
|
||||
const feedbackTone: StatusTone = operationFeedback.state === 'error'
|
||||
? 'danger'
|
||||
: dirty || saving
|
||||
@ -1516,15 +1514,6 @@ function TemplateConfigWorkspace({
|
||||
</div>
|
||||
</div>
|
||||
<div className="hidden md:block">
|
||||
<div className="border-b border-[#c2c6d8] p-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void selectTemplate('new')}
|
||||
className="min-h-11 w-full rounded bg-[#1a1c1c] px-4 text-center text-[13px] font-bold text-white hover:bg-black"
|
||||
>
|
||||
新建模板
|
||||
</button>
|
||||
</div>
|
||||
{data.templates.map((template) => {
|
||||
const state = getTemplateListState(template, month)
|
||||
const templateName = getTemplateDisplayName(template)
|
||||
@ -1552,22 +1541,19 @@ function TemplateConfigWorkspace({
|
||||
<div ref={editorRef} className="min-w-0 scroll-mt-4 p-4 sm:p-5">
|
||||
{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={() => void selectVersion(item)}
|
||||
className={`min-h-10 rounded border px-3 text-left text-[12px] font-bold ${versionId === item.id ? 'border-[#0050cb] bg-[#f1f4ff] text-[#0050cb]' : 'border-[#e2e2e2] text-[#5f5e5e]'}`}
|
||||
>
|
||||
<span className="block">v{item.version} · {item.status === 'draft' ? '草稿' : item.status === 'published' ? '已发布' : '已归档'}</span>
|
||||
{item.effectiveMonth && <span className="mt-0.5 block text-[10px] font-semibold opacity-80">{item.effectiveMonth} 起</span>}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
disabled={saving}
|
||||
onClick={() => void selectTemplate('new')}
|
||||
className="ml-auto min-h-10 rounded border border-[#1a1c1c] px-3 text-[12px] font-bold text-[#1a1c1c] hover:bg-[#f4f4f4] disabled:opacity-50"
|
||||
>
|
||||
新增模板
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={saving}
|
||||
onClick={() => void removeTemplate()}
|
||||
className="ml-auto min-h-10 rounded border border-[#f0b8b8] px-3 text-[12px] font-bold text-[#b42318] hover:bg-[#fff5f5] disabled:opacity-50"
|
||||
className="min-h-10 rounded border border-[#f0b8b8] px-3 text-[12px] font-bold text-[#b42318] hover:bg-[#fff5f5] disabled:opacity-50"
|
||||
>
|
||||
删除模板
|
||||
</button>
|
||||
@ -1739,7 +1725,10 @@ function TemplateConfigWorkspace({
|
||||
<button
|
||||
type="button"
|
||||
disabled={saving}
|
||||
onClick={() => void cloneVersion()}
|
||||
onClick={() => {
|
||||
setEditingPublishedVersion(true)
|
||||
setOperationFeedback({ state: 'idle', message: '可修改' })
|
||||
}}
|
||||
className="min-h-11 rounded bg-[#0050cb] px-4 text-[13px] font-bold text-white hover:bg-[#0042a8] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{saving ? '处理中…' : '修改模板'}
|
||||
@ -1747,16 +1736,30 @@ function TemplateConfigWorkspace({
|
||||
</>
|
||||
)}
|
||||
{editable && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={saving}
|
||||
onClick={() => void save()}
|
||||
className="min-h-11 rounded border border-[#1a1c1c] px-4 text-[13px] font-bold text-[#1a1c1c] hover:bg-[#f4f4f4] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{saving && operationFeedback.state === 'saving' ? '保存中…' : '保存草稿'}
|
||||
</button>
|
||||
<>
|
||||
{version?.status === 'published' && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={saving}
|
||||
onClick={() => void cancelPublishedEdit()}
|
||||
className="min-h-11 rounded border border-[#c2c6d8] px-4 text-[13px] font-bold text-[#5f5e5e] hover:bg-[#f4f4f4] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
取消修改
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
disabled={saving || (version?.status === 'published' && !dirty)}
|
||||
onClick={() => void save()}
|
||||
className="min-h-11 rounded border border-[#1a1c1c] px-4 text-[13px] font-bold text-[#1a1c1c] hover:bg-[#f4f4f4] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{saving && operationFeedback.state === 'saving'
|
||||
? '保存中…'
|
||||
: version?.status === 'published' ? '保存修改' : '保存草稿'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{editable && versionId && (
|
||||
{editable && versionId && version?.status === 'draft' && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={saving || !templateDefinitionReady}
|
||||
|
||||
@ -10,6 +10,7 @@ import {
|
||||
listPerformanceSurveyPositionGroups,
|
||||
removePerformanceSurveyTemplate,
|
||||
savePerformanceSurveyPositionGroupDraft,
|
||||
savePerformanceSurveyTemplateDraft,
|
||||
} from '@/lib/performance-survey-position-config'
|
||||
import { DEFAULT_PERFORMANCE_SURVEY_TEMPLATES } from '@/lib/performance-survey-templates'
|
||||
|
||||
@ -360,6 +361,81 @@ describe('performance survey position admin', () => {
|
||||
})
|
||||
})
|
||||
|
||||
test('修改已发布模板直接更新原记录并同步模板资料', async () => {
|
||||
const definition = {
|
||||
...structuredClone(DEFAULT_PERFORMANCE_SURVEY_TEMPLATES[0]),
|
||||
name: '更新后的模板名称',
|
||||
shortName: '更新后的模板名称',
|
||||
}
|
||||
const existing = {
|
||||
id: 'version-1',
|
||||
templateId: 'template-1',
|
||||
version: 2,
|
||||
status: 'published',
|
||||
definition: structuredClone(DEFAULT_PERFORMANCE_SURVEY_TEMPLATES[0]),
|
||||
updatedAt: new Date('2026-07-29T08:00:00.000Z'),
|
||||
template: {
|
||||
id: 'template-1',
|
||||
code: definition.code,
|
||||
name: '原模板名称',
|
||||
archivedAt: null,
|
||||
},
|
||||
}
|
||||
const saved = {
|
||||
...existing,
|
||||
definition,
|
||||
updatedAt: new Date('2026-07-29T09:00:00.000Z'),
|
||||
}
|
||||
const tx = {
|
||||
performanceSurveyTemplateVersion: {
|
||||
findUnique: jest.fn()
|
||||
.mockResolvedValueOnce(existing)
|
||||
.mockResolvedValueOnce(saved),
|
||||
updateMany: jest.fn().mockResolvedValue({ count: 1 }),
|
||||
},
|
||||
performanceSurveyTemplate: {
|
||||
update: jest.fn().mockResolvedValue({ id: 'template-1' }),
|
||||
},
|
||||
performanceSurveyConfigAuditLog: {
|
||||
create: jest.fn().mockResolvedValue({ id: 'audit-update' }),
|
||||
},
|
||||
$queryRawUnsafe: jest.fn().mockResolvedValue([{ locked: '1' }]),
|
||||
}
|
||||
;(prisma.performanceSurveyTemplateVersion.findUnique as jest.Mock).mockResolvedValue(existing)
|
||||
;(prisma.$transaction as jest.Mock).mockImplementation(async (callback) => callback(tx))
|
||||
|
||||
await expect(savePerformanceSurveyTemplateDraft({
|
||||
versionId: existing.id,
|
||||
definition,
|
||||
actorUserId: 'admin-1',
|
||||
actorName: '管理员',
|
||||
})).resolves.toMatchObject({
|
||||
id: existing.id,
|
||||
status: 'published',
|
||||
definition: expect.objectContaining({ name: '更新后的模板名称' }),
|
||||
})
|
||||
|
||||
expect(tx.performanceSurveyTemplateVersion.updateMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: existing.id,
|
||||
status: 'published',
|
||||
updatedAt: existing.updatedAt,
|
||||
},
|
||||
data: {
|
||||
definition,
|
||||
createdByUserId: 'admin-1',
|
||||
createdByName: '管理员',
|
||||
},
|
||||
})
|
||||
expect(tx.performanceSurveyTemplate.update).toHaveBeenCalledWith({
|
||||
where: { id: 'template-1' },
|
||||
data: expect.objectContaining({ name: '更新后的模板名称' }),
|
||||
})
|
||||
expect(tx.performanceSurveyConfigAuditLog.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ action: 'template.version_updated' }),
|
||||
})
|
||||
})
|
||||
|
||||
test('当前或未来岗位方案仍在使用模板时拒绝删除', async () => {
|
||||
;(prisma.performanceSurveyTemplate.findUnique as jest.Mock).mockResolvedValue({
|
||||
id: 'template-1',
|
||||
|
||||
@ -1615,8 +1615,8 @@ export async function savePerformanceSurveyTemplateDraft(input: {
|
||||
include: { template: true },
|
||||
})
|
||||
: null
|
||||
if (existingVersion && existingVersion.status !== 'draft') {
|
||||
throw new PerformanceSurveyPositionConfigError('已发布模板不可直接修改,请创建新草稿', 409)
|
||||
if (existingVersion?.status === 'archived') {
|
||||
throw new PerformanceSurveyPositionConfigError('已归档模板版本不能修改', 409)
|
||||
}
|
||||
if (existingVersion && existingVersion.template.code !== definition.code) {
|
||||
throw new PerformanceSurveyPositionConfigError('模板代码创建后不可在版本草稿中修改', 409)
|
||||
@ -1637,8 +1637,8 @@ export async function savePerformanceSurveyTemplateDraft(input: {
|
||||
include: { template: true },
|
||||
})
|
||||
if (!currentVersion) throw new PerformanceSurveyPositionConfigError('模板版本不存在', 404)
|
||||
if (currentVersion.status !== 'draft') {
|
||||
throw new PerformanceSurveyPositionConfigError('已发布模板不可直接修改,请创建新草稿', 409)
|
||||
if (currentVersion.status === 'archived') {
|
||||
throw new PerformanceSurveyPositionConfigError('已归档模板版本不能修改', 409)
|
||||
}
|
||||
if (currentVersion.template.code !== definition.code) {
|
||||
throw new PerformanceSurveyPositionConfigError('模板代码创建后不可在版本草稿中修改', 409)
|
||||
@ -1646,6 +1646,9 @@ export async function savePerformanceSurveyTemplateDraft(input: {
|
||||
if (currentVersion.template.archivedAt) {
|
||||
throw new PerformanceSurveyPositionConfigError('已归档模板不能继续编辑', 409)
|
||||
}
|
||||
if (currentVersion.status === 'published') {
|
||||
validatePerformanceSurveyTemplateDefinition(definition)
|
||||
}
|
||||
}
|
||||
let template = currentVersion?.template || await tx.performanceSurveyTemplate.findUnique({
|
||||
where: { code: definition.code },
|
||||
@ -1666,20 +1669,28 @@ export async function savePerformanceSurveyTemplateDraft(input: {
|
||||
isActive: true,
|
||||
},
|
||||
})
|
||||
} else if (!currentVersion) {
|
||||
const existingTemplateVersion = await tx.performanceSurveyTemplateVersion.findFirst({
|
||||
where: { templateId: template.id },
|
||||
select: { id: true },
|
||||
})
|
||||
if (existingTemplateVersion) {
|
||||
throw new PerformanceSurveyPositionConfigError('模板已存在,请直接修改当前模板', 409)
|
||||
}
|
||||
}
|
||||
let saved
|
||||
if (currentVersion) {
|
||||
const updateResult = await tx.performanceSurveyTemplateVersion.updateMany({
|
||||
where: {
|
||||
id: currentVersion.id,
|
||||
status: 'draft',
|
||||
status: currentVersion.status,
|
||||
updatedAt: currentVersion.updatedAt,
|
||||
},
|
||||
data: { definition: definition as any, createdByUserId: input.actorUserId, createdByName: input.actorName },
|
||||
})
|
||||
if (updateResult.count !== 1) {
|
||||
throw new PerformanceSurveyPositionConfigError(
|
||||
'模板草稿已发生变化,请重新加载后再保存',
|
||||
'模板已发生变化,请重新加载后再保存',
|
||||
409,
|
||||
)
|
||||
}
|
||||
@ -1687,16 +1698,25 @@ export async function savePerformanceSurveyTemplateDraft(input: {
|
||||
where: { id: currentVersion.id },
|
||||
})
|
||||
if (!saved) throw new PerformanceSurveyPositionConfigError('模板草稿保存失败', 409)
|
||||
if (currentVersion.status === 'published') {
|
||||
await tx.performanceSurveyTemplate.update({
|
||||
where: { id: template.id },
|
||||
data: {
|
||||
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,
|
||||
},
|
||||
})
|
||||
}
|
||||
} else {
|
||||
const latest = await tx.performanceSurveyTemplateVersion.findFirst({
|
||||
where: { templateId: template.id },
|
||||
orderBy: { version: 'desc' },
|
||||
select: { version: true },
|
||||
})
|
||||
saved = await tx.performanceSurveyTemplateVersion.create({
|
||||
data: {
|
||||
templateId: template.id,
|
||||
version: Number(latest?.version || 0) + 1,
|
||||
version: 1,
|
||||
status: 'draft',
|
||||
definition: definition as any,
|
||||
createdByUserId: input.actorUserId,
|
||||
@ -1705,7 +1725,9 @@ export async function savePerformanceSurveyTemplateDraft(input: {
|
||||
})
|
||||
}
|
||||
await writePerformanceSurveyConfigAuditLog(tx, {
|
||||
action: 'template.draft_saved',
|
||||
action: currentVersion?.status === 'published'
|
||||
? 'template.version_updated'
|
||||
: 'template.draft_saved',
|
||||
targetType: 'template',
|
||||
targetId: template.id,
|
||||
actorUserId: input.actorUserId,
|
||||
@ -1713,60 +1735,12 @@ export async function savePerformanceSurveyTemplateDraft(input: {
|
||||
reason: input.reason,
|
||||
beforeSnapshot: currentVersion,
|
||||
afterSnapshot: saved,
|
||||
metadata: { versionId: saved.id },
|
||||
metadata: { versionId: saved.id, status: currentVersion?.status || 'draft' },
|
||||
})
|
||||
return saved
|
||||
})
|
||||
}
|
||||
|
||||
export async function createPerformanceSurveyTemplateDraftFromVersion(input: {
|
||||
versionId: string
|
||||
actorUserId: string
|
||||
actorName: string
|
||||
reason?: string | null
|
||||
}) {
|
||||
const source = await prisma.performanceSurveyTemplateVersion.findUnique({
|
||||
where: { id: input.versionId },
|
||||
include: { template: true },
|
||||
})
|
||||
if (!source) throw new PerformanceSurveyPositionConfigError('模板版本不存在', 404)
|
||||
if (source.template.archivedAt) throw new PerformanceSurveyPositionConfigError('已归档模板不能复制草稿', 409)
|
||||
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.$transaction(async (tx) => {
|
||||
const created = await tx.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,
|
||||
},
|
||||
})
|
||||
await writePerformanceSurveyConfigAuditLog(tx, {
|
||||
action: 'template.version_cloned',
|
||||
targetType: 'template',
|
||||
targetId: source.templateId,
|
||||
actorUserId: input.actorUserId,
|
||||
actorName: input.actorName,
|
||||
reason: input.reason,
|
||||
beforeSnapshot: source,
|
||||
afterSnapshot: created,
|
||||
metadata: { sourceVersionId: source.id },
|
||||
})
|
||||
return created
|
||||
})
|
||||
}
|
||||
|
||||
export async function copyPerformanceSurveyTemplateVersion(input: {
|
||||
versionId: string
|
||||
actorUserId: string
|
||||
|
||||
@ -28,7 +28,6 @@ import {
|
||||
copyPerformanceSurveyPositionGroup,
|
||||
createPerformanceSurveyManualPositionAssignments,
|
||||
createPerformanceSurveyPositionGroup,
|
||||
createPerformanceSurveyTemplateDraftFromVersion,
|
||||
copyPerformanceSurveyTemplateVersion,
|
||||
getAvailablePerformanceSurveyPositionTemplates,
|
||||
getManualReviewerStages,
|
||||
@ -1264,24 +1263,6 @@ export async function savePerformanceSurveyAdminTemplate(session: Session | null
|
||||
}
|
||||
}
|
||||
|
||||
export async function clonePerformanceSurveyAdminTemplateVersion(
|
||||
session: Session | null,
|
||||
versionId: string,
|
||||
) {
|
||||
const ctx = await getPerformanceSurveyContext(session)
|
||||
ensureSystemAdministrator(ctx)
|
||||
try {
|
||||
return await createPerformanceSurveyTemplateDraftFromVersion({
|
||||
versionId,
|
||||
reason: null,
|
||||
actorUserId: ctx.user.id,
|
||||
actorName: getDisplayName(ctx.user),
|
||||
})
|
||||
} catch (error) {
|
||||
return rethrowPositionConfigError(error)
|
||||
}
|
||||
}
|
||||
|
||||
export async function copyPerformanceSurveyAdminTemplateVersion(
|
||||
session: Session | null,
|
||||
versionId: string,
|
||||
|
||||
@ -15,6 +15,7 @@
|
||||
"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",
|
||||
"performance-survey:templates:collapse": "node scripts/collapse-performance-survey-template-versions.mjs",
|
||||
"history:scan": "tsx scripts/scan-history-materials.ts",
|
||||
"history:import": "tsx scripts/import-history-materials.ts",
|
||||
"prisma:generate": "prisma generate",
|
||||
|
||||
186
scripts/collapse-performance-survey-template-versions.mjs
Normal file
186
scripts/collapse-performance-survey-template-versions.mjs
Normal file
@ -0,0 +1,186 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
|
||||
const prisma = new PrismaClient()
|
||||
const applyChanges = process.argv.includes('--apply')
|
||||
const actorUserId = 'system-template-consolidation'
|
||||
const actorName = '系统模板归并'
|
||||
|
||||
function chooseRetainedVersion(versions) {
|
||||
const byNewest = [...versions].sort((left, right) => (
|
||||
Number(right.version || 0) - Number(left.version || 0)
|
||||
|| new Date(right.updatedAt).getTime() - new Date(left.updatedAt).getTime()
|
||||
))
|
||||
return byNewest.find((version) => version.status === 'published')
|
||||
|| byNewest.find((version) => version.status === 'draft')
|
||||
|| byNewest[0]
|
||||
|| null
|
||||
}
|
||||
|
||||
function readDefinition(value) {
|
||||
return value && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
||||
}
|
||||
|
||||
async function buildPlan() {
|
||||
const templates = await prisma.performanceSurveyTemplate.findMany({
|
||||
include: {
|
||||
versions: {
|
||||
orderBy: [{ version: 'desc' }, { updatedAt: 'desc' }],
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
})
|
||||
|
||||
return templates.map((template) => {
|
||||
const retained = chooseRetainedVersion(template.versions)
|
||||
const removed = retained
|
||||
? template.versions.filter((version) => version.id !== retained.id)
|
||||
: []
|
||||
return {
|
||||
template,
|
||||
retained,
|
||||
removed,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function applyPlan(plan) {
|
||||
return prisma.$transaction(async (tx) => {
|
||||
const summary = {
|
||||
templates: 0,
|
||||
retainedVersions: 0,
|
||||
removedVersions: 0,
|
||||
reassignedPlanItems: 0,
|
||||
deduplicatedPlanItems: 0,
|
||||
}
|
||||
|
||||
for (const item of plan) {
|
||||
const { template, retained, removed } = item
|
||||
if (!retained) continue
|
||||
summary.templates += 1
|
||||
summary.retainedVersions += 1
|
||||
|
||||
const allVersionIds = template.versions.map((version) => version.id)
|
||||
const planItems = await tx.performanceSurveyPositionPlanItem.findMany({
|
||||
where: { templateVersionId: { in: allVersionIds } },
|
||||
orderBy: [{ positionPlanId: 'asc' }, { sortOrder: 'asc' }, { createdAt: 'asc' }],
|
||||
})
|
||||
const itemsByPlan = new Map()
|
||||
for (const planItem of planItems) {
|
||||
const current = itemsByPlan.get(planItem.positionPlanId) || []
|
||||
current.push(planItem)
|
||||
itemsByPlan.set(planItem.positionPlanId, current)
|
||||
}
|
||||
|
||||
for (const groupedItems of itemsByPlan.values()) {
|
||||
const retainedItem = groupedItems.find((planItem) => planItem.templateVersionId === retained.id)
|
||||
const primary = retainedItem || groupedItems[0]
|
||||
const redundantIds = groupedItems
|
||||
.filter((planItem) => planItem.id !== primary.id)
|
||||
.map((planItem) => planItem.id)
|
||||
if (redundantIds.length > 0) {
|
||||
await tx.performanceSurveyPositionPlanItem.deleteMany({
|
||||
where: { id: { in: redundantIds } },
|
||||
})
|
||||
summary.deduplicatedPlanItems += redundantIds.length
|
||||
}
|
||||
|
||||
const nextSortOrder = Math.min(...groupedItems.map((planItem) => planItem.sortOrder))
|
||||
const nextEnabled = groupedItems.some((planItem) => planItem.isEnabled)
|
||||
if (
|
||||
primary.templateVersionId !== retained.id
|
||||
|| primary.sortOrder !== nextSortOrder
|
||||
|| primary.isEnabled !== nextEnabled
|
||||
) {
|
||||
await tx.performanceSurveyPositionPlanItem.update({
|
||||
where: { id: primary.id },
|
||||
data: {
|
||||
templateVersionId: retained.id,
|
||||
sortOrder: nextSortOrder,
|
||||
isEnabled: nextEnabled,
|
||||
},
|
||||
})
|
||||
summary.reassignedPlanItems += 1
|
||||
}
|
||||
}
|
||||
|
||||
if (removed.length > 0) {
|
||||
await tx.performanceSurveyTemplateVersion.deleteMany({
|
||||
where: { id: { in: removed.map((version) => version.id) } },
|
||||
})
|
||||
summary.removedVersions += removed.length
|
||||
}
|
||||
if (retained.version !== 1) {
|
||||
await tx.performanceSurveyTemplateVersion.update({
|
||||
where: { id: retained.id },
|
||||
data: { version: 1 },
|
||||
})
|
||||
}
|
||||
|
||||
const definition = readDefinition(retained.definition)
|
||||
await tx.performanceSurveyTemplate.update({
|
||||
where: { id: template.id },
|
||||
data: {
|
||||
name: String(definition.name || template.name),
|
||||
description: String(definition.description || ''),
|
||||
surveyType: String(definition.surveyType || template.surveyType),
|
||||
weight: Number(definition.weight || template.weight || 1),
|
||||
questions: Array.isArray(definition.questions) ? definition.questions : [],
|
||||
scoreBands: Array.isArray(definition.scoreBands) ? definition.scoreBands : [],
|
||||
},
|
||||
})
|
||||
await tx.performanceSurveyConfigAuditLog.create({
|
||||
data: {
|
||||
action: 'template.versions_collapsed',
|
||||
targetType: 'template',
|
||||
targetId: template.id,
|
||||
actorUserId,
|
||||
actorName,
|
||||
reason: '模板改为单配置模式',
|
||||
beforeSnapshot: {
|
||||
versionIds: template.versions.map((version) => version.id),
|
||||
versions: template.versions.map((version) => ({
|
||||
id: version.id,
|
||||
version: version.version,
|
||||
status: version.status,
|
||||
})),
|
||||
},
|
||||
afterSnapshot: {
|
||||
retainedVersionId: retained.id,
|
||||
status: retained.status,
|
||||
},
|
||||
metadata: {
|
||||
removedVersionIds: removed.map((version) => version.id),
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return summary
|
||||
}, { maxWait: 10_000, timeout: 60_000 })
|
||||
}
|
||||
|
||||
try {
|
||||
const plan = await buildPlan()
|
||||
const preview = plan.map(({ template, retained, removed }) => ({
|
||||
templateId: template.id,
|
||||
templateCode: template.code,
|
||||
templateName: template.name,
|
||||
retained: retained
|
||||
? { id: retained.id, version: retained.version, status: retained.status }
|
||||
: null,
|
||||
removed: removed.map((version) => ({
|
||||
id: version.id,
|
||||
version: version.version,
|
||||
status: version.status,
|
||||
})),
|
||||
}))
|
||||
|
||||
if (!applyChanges) {
|
||||
console.log(JSON.stringify({ mode: 'preview', templates: preview }, null, 2))
|
||||
} else {
|
||||
const summary = await applyPlan(plan)
|
||||
console.log(JSON.stringify({ mode: 'applied', summary }, null, 2))
|
||||
}
|
||||
} finally {
|
||||
await prisma.$disconnect()
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user