fix: 客户端处理考核调研视觉作品

This commit is contained in:
chenpei 2026-07-17 10:46:14 +08:00
parent 1a8c7c0f23
commit d2e5530a1c
9 changed files with 1394 additions and 90 deletions

View File

@ -8,6 +8,7 @@ import { useSession } from 'next-auth/react'
import { pinyin } from 'pinyin-pro'
import { createPortal } from 'react-dom'
import { sortPerformanceSurveyImagesByName } from '@/lib/performance-survey-image-order'
import { preparePerformanceSurveyImagesInBrowser } from '@/lib/performance-survey-image-browser'
import { calculatePerformanceSurveyResponseProgress } from '@/lib/performance-survey-response-progress'
import { groupVisualScoresByEvaluator } from '@/lib/performance-survey-result-grouping'
@ -220,8 +221,18 @@ async function uploadPerformanceSurveyImageFiles(
onProgress?: (label: string) => void,
) {
const { chunkUpload } = await import('@/lib/chunk-upload')
const uploaded: Array<{ uploadId: string; mimeType: string }> = []
const orderedFiles = sortPerformanceSurveyImagesByName(files, (file) => file.name)
const uploaded: Array<{
uploadId: string
mimeType: 'image/webp'
width: number
height: number
kind: 'slice' | 'preview'
sourceName: string
sourceIndex: number
sliceIndex: number
sliceCount: number
}> = []
const processedImages = await preparePerformanceSurveyImagesInBrowser(files, onProgress)
const dingtalkToken = getStoredDingtalkPerformanceToken()
const requestHeaders = dingtalkToken
? {
@ -230,16 +241,27 @@ async function uploadPerformanceSurveyImageFiles(
}
: undefined
for (let index = 0; index < orderedFiles.length; index += 1) {
const file = orderedFiles[index]
onProgress?.(`正在上传图片 ${index + 1}/${orderedFiles.length}`)
for (let index = 0; index < processedImages.length; index += 1) {
const image = processedImages[index]
const file = image.file
onProgress?.(`正在上传处理结果 ${index + 1}/${processedImages.length}`)
const result = await chunkUpload(
file,
{ materialType: '考核调研-视觉评分', fileName: file.name },
{ skipComplete: true, requestHeaders },
)
if (!result?.uploadId) throw new Error(`图片「${file.name}」上传失败,请重试`)
uploaded.push({ uploadId: result.uploadId, mimeType: file.type })
uploaded.push({
uploadId: result.uploadId,
mimeType: image.mimeType,
width: image.width,
height: image.height,
kind: image.kind,
sourceName: image.sourceName,
sourceIndex: image.sourceIndex,
sliceIndex: image.sliceIndex,
sliceCount: image.sliceCount,
})
}
return uploaded
@ -2832,7 +2854,7 @@ function CreateSurveyForm({
templateVariant: selectedTemplateInfo?.templateVariant || null,
assessmentMonth: selectedAssessmentMonth,
dueAt: deadlineAt ? new Date(deadlineAt).toISOString() : null,
openNow,
openNow: visualTemplateSelected ? false : openNow,
targetEmployeeIds: effectiveTargetEmployees.map((employee) => employee.id),
targetItems: targetItemsToSubmit,
evaluatorEmployeeIds: evaluatorEmployees.map((employee) => employee.id),
@ -2858,10 +2880,17 @@ function CreateSurveyForm({
targetId: uploadTarget.id,
title: draft.title.trim() || `案例 ${index + 1}`,
description: draft.description.trim(),
images,
processedImages: images,
}),
})
}
setPublishingLabel('正在确认作品并发布调研')
const opened = await apiRequest<any>(`/surveys/${created.id}`, {
method: 'PATCH',
body: JSON.stringify({ status: 'open' }),
})
setCreatedSurvey(opened)
}
setTitle('')
@ -2886,7 +2915,7 @@ function CreateSurveyForm({
const message = err instanceof Error ? err.message : '创建失败'
setError(
createdForAttempt && visualTemplateSelected
? `调研已创建,但作品没有全部上传完成:${message}`
? `调研尚未发布,作品没有全部上传完成:${message}`
: message,
)
} finally {
@ -3077,21 +3106,31 @@ function CreateSurveyForm({
onClick={submit}
className="h-12 w-full rounded bg-[#0050cb] px-5 text-[15px] font-bold text-white hover:bg-[#003fa4] disabled:cursor-not-allowed disabled:bg-[#aeb9c9]"
>
{saving ? publishingLabel || '发布中...' : createdSurvey ? '调研已发布' : visualTemplateSelected ? '发布并开始自评' : '发布调研'}
{saving
? publishingLabel || '发布中...'
: createdSurvey?.status === 'open'
? '调研已发布'
: createdSurvey
? '调研待完成'
: visualTemplateSelected
? '上传作品并发布'
: '发布调研'}
</button>
{createdSurvey && (
<div className="flex items-center justify-between gap-3 border border-[#b3c5ff] bg-[#f8faff] px-4 py-3 text-sm font-semibold text-[#0050cb]">
<span>
{isVisualTemplate(selectedTemplateInfo) && !currentTargetSelected
? '已发布,已通知被考核人提交作品'
: '已发布'}
{createdSurvey.status === 'open'
? isVisualTemplate(selectedTemplateInfo) && !currentTargetSelected
? '已发布,已通知被考核人提交作品'
: '已发布'
: '尚未发布,请继续上传作品;作品完整后才能发布'}
</span>
{createdUploadTarget?.id && (
<Link
href={`/performance-survey/survey/${createdSurvey.id}?targetId=${encodeURIComponent(createdUploadTarget.id)}`}
className="shrink-0 rounded bg-[#0050cb] px-3 py-1.5 text-white"
>
上传作品
{createdSurvey.status === 'open' ? '查看作品' : '继续上传'}
</Link>
)}
</div>
@ -3177,7 +3216,8 @@ function PerformanceSurveyImageDropzone({
>
<span className={`flex h-8 w-8 items-center justify-center rounded-full text-[20px] font-light ${dragging ? 'bg-[#0050cb] text-white' : 'bg-[#eef5ff] text-[#0050cb]'}`}>↑</span>
<span className="mt-2 text-[13px] font-bold text-[#0050cb]">{dragging ? '松开即可添加' : '拖拽图片到这里'}</span>
<span className="mt-0.5 text-[11px] text-[#98a2b3]">或点击选择 · 单张长图,或最多 60 张有序切片;单张 200MB</span>
<span className="mt-0.5 text-[11px] text-[#98a2b3]">或点击选择 · 单张长图由浏览器切片,多张按数字文件名顺序处理上传;单张 200MB</span>
<span className="mt-0.5 text-[10px] text-[#98a2b3]">请使用桌面版 Chrome 或 Edge</span>
</button>
</div>
)
@ -4344,10 +4384,32 @@ function VisualCaseSurvey({
}) {
const requiredCount = Number(template?.requiredWorkItemCount || 3)
const workItems = activeTarget?.workItems || []
const canUpload = Boolean(activeTarget?.canUploadWorkItems && detail.data?.status === 'open')
const canUpload = Boolean(activeTarget?.canUploadWorkItems && ['draft', 'open'].includes(detail.data?.status))
const canScore = Boolean(activeTarget?.currentAssignment && detail.data?.status === 'open')
const submitted = activeTarget?.currentAssignment?.status === 'submitted'
const completedScores = workItems.filter((item: any) => item.scores?.length > 0).length
const [publishing, setPublishing] = useState(false)
const [publishError, setPublishError] = useState<string | null>(null)
const draftReadyToPublish = detail.data?.status === 'draft'
&& Boolean(detail.data?.canManage)
&& workItems.length >= requiredCount
const publishDraft = async () => {
if (!draftReadyToPublish || publishing) return
setPublishing(true)
setPublishError(null)
try {
await apiRequest(`/surveys/${surveyId}`, {
method: 'PATCH',
body: JSON.stringify({ status: 'open' }),
})
await detail.refresh()
} catch (error) {
setPublishError(error instanceof Error ? error.message : '发布失败')
} finally {
setPublishing(false)
}
}
return (
<main className="min-h-[100dvh] bg-white text-[#111827]">
@ -4406,8 +4468,29 @@ function VisualCaseSurvey({
/>
)}
{detail.data?.status === 'draft' && (
<section className="mb-3 rounded-xl border border-[#dfe6f0] bg-[#f8faff] px-4 py-4">
<div className="text-[14px] font-semibold text-[#101828]">
{draftReadyToPublish
? '作品已完整,确认发布后才会通知评分人'
: `当前为未发布草稿,还需上传 ${Math.max(0, requiredCount - workItems.length)} 个案例`}
</div>
{publishError && <div className="mt-2 text-sm font-medium text-[#d92d20]">{publishError}</div>}
{draftReadyToPublish && (
<button
type="button"
disabled={publishing}
onClick={publishDraft}
className="mt-3 w-full rounded-[12px] bg-[#1677ff] px-4 py-2.5 text-sm font-semibold text-white disabled:bg-[#9ec9ff]"
>
{publishing ? '发布中...' : '确认发布调研'}
</button>
)}
</section>
)}
{workItems.length === 0 && (
detail.data?.status === 'open' ? (
['draft', 'open'].includes(detail.data?.status) ? (
<div className="rounded-xl border border-dashed border-[#d9e0ea] bg-white px-4 py-10 text-center text-[15px] font-semibold text-[#667085]">
{canUpload ? '请先上传案例图片' : '等待被考核人提交案例'}
</div>
@ -4479,6 +4562,7 @@ function WorkItemUploadForm({
const [files, setFiles] = useState<File[]>([])
const [busy, setBusy] = useState(false)
const [message, setMessage] = useState<string | null>(null)
const [messageTone, setMessageTone] = useState<'progress' | 'success' | 'error'>('progress')
const addFiles = (selectedFiles: File[]) => {
const merged = [...files, ...selectedFiles].filter((file, index, items) => {
@ -4488,6 +4572,7 @@ function WorkItemUploadForm({
const orderedFiles = sortPerformanceSurveyImagesByName(merged, (file) => file.name)
const validationError = validatePerformanceSurveyImageFiles(orderedFiles)
if (validationError) {
setMessageTone('error')
setMessage(validationError)
return
}
@ -4499,28 +4584,36 @@ function WorkItemUploadForm({
if (disabled) return
const validationError = validatePerformanceSurveyImageFiles(files)
if (validationError) {
setMessageTone('error')
setMessage(validationError)
return
}
setBusy(true)
setMessageTone('progress')
setMessage(null)
try {
const images = await uploadPerformanceSurveyImageFiles(files, setMessage)
setMessage('图片上传完成,正在生成评分预览')
const processedImages = await uploadPerformanceSurveyImageFiles(files, (label) => {
setMessageTone('progress')
setMessage(label)
})
setMessage('图片处理和上传完成,正在保存作品')
await apiRequest(`/surveys/${surveyId}/work-items`, {
method: 'POST',
body: JSON.stringify({
targetId,
title: title.trim() || '案例作品',
description: description.trim(),
images,
processedImages,
}),
})
setTitle('')
setDescription('')
setFiles([])
await onUploaded()
setMessageTone('success')
setMessage('作品已保存')
} catch (error) {
setMessageTone('error')
setMessage(error instanceof Error ? error.message : '上传失败')
} finally {
setBusy(false)
@ -4559,7 +4652,17 @@ function WorkItemUploadForm({
setMessage(null)
}}
/>
{message && <div className="text-sm font-medium text-[#d92d20]">{message}</div>}
{message && (
<div className={`text-sm font-medium ${
messageTone === 'error'
? 'text-[#d92d20]'
: messageTone === 'success'
? 'text-[#087a3c]'
: 'text-[#1677ff]'
}`}>
{message}
</div>
)}
<button
type="button"
disabled={busy || disabled || files.length === 0}

View File

@ -0,0 +1,90 @@
/** @jest-environment node */
import {
readPerformanceSurveyWebpDimensions,
validatePerformanceSurveyProcessedImages,
} from '@/lib/performance-survey-processed-images'
function record(overrides: Record<string, unknown> = {}) {
return {
uploadId: 'upload-1',
mimeType: 'image/webp',
width: 1600,
height: 1500,
kind: 'slice',
sourceName: '详情长图.png',
sourceIndex: 0,
sliceIndex: 0,
sliceCount: 1,
...overrides,
}
}
function vp8xHeader(width: number, height: number) {
const buffer = Buffer.alloc(30)
buffer.write('RIFF', 0, 'ascii')
buffer.write('WEBP', 8, 'ascii')
buffer.write('VP8X', 12, 'ascii')
buffer.writeUIntLE(width - 1, 24, 3)
buffer.writeUIntLE(height - 1, 27, 3)
return buffer
}
describe('performance survey processed image contract', () => {
test('accepts one optional preview plus ordered slices from one long source', () => {
const groups = validatePerformanceSurveyProcessedImages([
record({ uploadId: 'slice-2', sliceIndex: 1, sliceCount: 2, height: 800 }),
record({ uploadId: 'preview', kind: 'preview', width: 720, height: 560, sliceCount: 2 }),
record({ uploadId: 'slice-1', sliceIndex: 0, sliceCount: 2 }),
])
expect(groups).toHaveLength(1)
expect(groups[0].preview?.uploadId).toBe('preview')
expect(groups[0].slices.map((item) => item.uploadId)).toEqual(['slice-1', 'slice-2'])
})
test('accepts pre-cut files as independent source groups without previews', () => {
const groups = validatePerformanceSurveyProcessedImages([
record({ uploadId: 'part-1', sourceName: '1.webp' }),
record({ uploadId: 'part-2', sourceName: '2.webp', sourceIndex: 1 }),
])
expect(groups).toHaveLength(2)
expect(groups.every((group) => group.preview === null && group.sliceCount === 1)).toBe(true)
})
test('rejects missing or duplicated slice positions', () => {
expect(() => validatePerformanceSurveyProcessedImages([
record({ uploadId: 'slice-1', sliceIndex: 0, sliceCount: 2 }),
record({ uploadId: 'slice-duplicate', sliceIndex: 0, sliceCount: 2 }),
])).toThrow('切片序号不连续')
})
test('limits final ordered slices to 60 per work item', () => {
const sixtySlices = Array.from({ length: 60 }, (_, index) => record({
uploadId: `long-${index}`,
sliceIndex: index,
sliceCount: 60,
}))
expect(validatePerformanceSurveyProcessedImages(sixtySlices)[0].slices).toHaveLength(60)
expect(() => validatePerformanceSurveyProcessedImages([
...sixtySlices,
record({ uploadId: 'part-61', sourceName: '2.webp', sourceIndex: 1 }),
])).toThrow('最多上传 60 张有序切片')
})
test('requires safe WebP dimensions declared by the browser', () => {
expect(() => validatePerformanceSurveyProcessedImages([
record({ mimeType: 'image/png' }),
])).toThrow('只接受 WebP')
expect(() => validatePerformanceSurveyProcessedImages([
record({ height: 1501 }),
])).toThrow('图片高度无效')
})
test('reads VP8X dimensions without decoding image pixels', () => {
expect(readPerformanceSurveyWebpDimensions(vp8xHeader(1600, 900))).toEqual({ width: 1600, height: 900 })
expect(() => readPerformanceSurveyWebpDimensions(Buffer.from('not-webp'))).toThrow('不是有效的 WebP')
})
})

View File

@ -1057,7 +1057,7 @@ describe('performance survey service policies', () => {
])
})
test('自动匹配工作配合度评分人时,P级档案缺少主管唯一值会明确拒绝创建', async () => {
test('自动匹配工作配合度评分人时,P级档案缺少主管唯一值且组织内无唯一M级会明确拒绝创建', async () => {
const target = {
...baseEmployee,
id: 'employee-target',
@ -1086,12 +1086,84 @@ describe('performance survey service policies', () => {
assessmentMonth: '2026-07',
targetEmployeeIds: [target.id],
})).rejects.toEqual(new PerformanceSurveyApiError(
'无法确定缺主管人员的直属主管:人员档案缺少主管唯一值',
'无法唯一确定缺主管人员所在组织的 M 级主管,请手动选择评分人',
409,
))
expect(prisma.$transaction).not.toHaveBeenCalled()
})
test('自动匹配工作配合度评分人时,P级档案缺少主管唯一值会使用同一完整组织内唯一M级主管', async () => {
const target = {
...baseEmployee,
id: 'employee-yijiang',
displayName: '忆江',
departmentName: '综合支持部',
departmentPath: '集团A/品牌中心/综合支持部',
dingtalkUserId: 'ding-yijiang',
levelType: 'P',
positionLevel: 'P4',
managerDingtalkUserId: null,
}
const uniqueManager = {
...baseEmployee,
id: 'employee-wuxie',
displayName: '无邪',
departmentName: target.departmentName,
departmentPath: target.departmentPath,
dingtalkUserId: 'ding-wuxie',
levelType: 'M',
positionLevel: 'M1',
}
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockResolvedValue(target)
;(getPerformanceSurveyTemplate as jest.Mock).mockResolvedValue({
code: 'work_cooperation',
name: '工作配合度满意度调研',
shortName: '工作配合度',
surveyType: 'person_period',
weight: 0.2,
questions: [],
scoreBands: [],
})
;(prisma.performanceSurveyEmployeeProfile.findMany as jest.Mock)
.mockResolvedValueOnce([target])
.mockResolvedValueOnce([uniqueManager])
.mockResolvedValueOnce([uniqueManager])
;(prisma.user.findMany as jest.Mock).mockResolvedValue([{
id: 'user-wuxie',
dingtalkUserId: uniqueManager.dingtalkUserId,
}])
;(prisma.performanceSurvey.findUnique as jest.Mock).mockResolvedValue(buildSurvey({
templateCode: 'work_cooperation',
creatorEmployeeId: target.id,
targets: [{
id: 'target-work-cooperation',
employeeProfileId: target.id,
targetType: 'employee',
targetName: target.displayName,
targetSnapshot: {},
responses: [],
assignments: [],
workItems: [],
}],
}))
await createPerformanceSurvey(session, {
templateCode: 'work_cooperation',
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,
}),
])
})
test('元泽本人发起工作配合度时要求手动选择其他评分人', async () => {
const yuanzhe = {
...baseEmployee,

View File

@ -0,0 +1,226 @@
/** @jest-environment node */
import { mkdtemp, rm, writeFile } from 'fs/promises'
import os from 'os'
import path from 'path'
import type { Session } from 'next-auth'
import {
PerformanceSurveyApiError,
createPerformanceSurveyWorkItemFromRequest,
} from '@/lib/performance-survey-service'
import { prisma } from '@/lib/prisma'
import { ensurePerformanceSurveyEmployeeProfileForUser } from '@/lib/performance-survey-report-sync'
import { uploadFileToS3 } from '@/lib/s3'
import {
deleteOwnedUploadSession,
getOwnedUploadedFile,
getOwnedUploadSession,
} from '@/lib/upload-sessions'
jest.mock('@/lib/prisma', () => ({
prisma: {
user: { findUnique: jest.fn(), findMany: jest.fn() },
performanceSurvey: { findUnique: jest.fn(), count: jest.fn() },
performanceSurveyWorkItem: { findUnique: jest.fn() },
$transaction: jest.fn(),
},
}))
jest.mock('@/lib/performance-survey-report-sync', () => ({
ensurePerformanceSurveyDailyEmployeeSyncStarted: jest.fn(),
ensurePerformanceSurveyEmployeeProfileForUser: jest.fn(),
getPerformanceSurveyAccountProfileWhere: jest.fn(async () => ({ id: { not: '__hidden__' } })),
}))
jest.mock('@/lib/performance-survey-notifications', () => ({
ensurePerformanceSurveyNotificationWorkerStarted: jest.fn(),
}))
jest.mock('@/lib/dingtalk-client', () => ({
getDingtalkPerformanceSurveyNotificationChannel: jest.fn(() => 'work_notice'),
getDingtalkRobotOtoConfigStatus: jest.fn(() => ({ configured: true })),
getDingtalkRobotOtoTestUserIds: jest.fn(() => []),
getDingtalkWorkNoticeConfigStatus: jest.fn(() => ({ configured: true })),
}))
jest.mock('@/lib/s3', () => ({
deleteFromS3: jest.fn(),
uploadFileToS3: jest.fn(),
uploadToS3: jest.fn(),
}))
jest.mock('@/lib/upload-sessions', () => ({
deleteOwnedUploadSession: jest.fn(),
getOwnedUploadSession: jest.fn(),
getOwnedUploadedFile: jest.fn(),
}))
function vp8xHeader(width: number, height: number) {
const buffer = Buffer.alloc(30)
buffer.write('RIFF', 0, 'ascii')
buffer.write('WEBP', 8, 'ascii')
buffer.write('VP8X', 12, 'ascii')
buffer.writeUIntLE(width - 1, 24, 3)
buffer.writeUIntLE(height - 1, 27, 3)
return buffer
}
const session = { user: { id: 'user-1' } } as Session
const employee = {
id: 'employee-1',
displayName: '测试人员',
departmentName: '综合支持部',
departmentPath: '集团/品牌中心/综合支持部',
levelType: 'P',
positionLevel: 'P4',
isLeadership: false,
}
describe('performance survey processed work item upload', () => {
let tempRoot = ''
let webpPath = ''
beforeEach(async () => {
jest.clearAllMocks()
tempRoot = await mkdtemp(path.join(os.tmpdir(), 'survey-processed-'))
process.env.UPLOAD_DIR = tempRoot
webpPath = path.join(tempRoot, 'slice.webp')
await writeFile(webpPath, vp8xHeader(1600, 900))
;(prisma.user.findUnique as jest.Mock).mockResolvedValue({
id: 'user-1',
username: 'tester',
email: 'tester@example.com',
role: 'USER',
department: '综合支持部',
managedDepartment: null,
isSuperAdmin: false,
dingtalkUserId: 'ding-user-1',
realName: '测试人员',
avatar: null,
})
;(ensurePerformanceSurveyEmployeeProfileForUser as jest.Mock).mockResolvedValue(employee)
;(prisma.performanceSurvey.findUnique as jest.Mock).mockResolvedValue({
id: 'survey-1',
title: '2026年7月 · 视觉评分',
templateCode: 'visual_brand_tone',
templateSnapshot: {
code: 'visual_brand_tone',
surveyType: 'visual_case',
requiredWorkItemCount: 3,
},
status: 'draft',
creatorUserId: 'user-1',
creatorEmployeeId: 'employee-1',
departmentName: '综合支持部',
targets: [{ id: 'target-1', employeeProfileId: 'employee-1' }],
workItems: [],
})
;(getOwnedUploadSession as jest.Mock).mockResolvedValue({
fileName: 'slice.webp',
fileSize: 30,
userId: 'user-1',
})
;(getOwnedUploadedFile as jest.Mock).mockResolvedValue(webpPath)
;(uploadFileToS3 as jest.Mock).mockImplementation(async (_filePath, fileName) => `https://s3.example/${fileName}`)
;(deleteOwnedUploadSession as jest.Mock).mockResolvedValue(true)
const transactionClient = {
$queryRawUnsafe: jest.fn().mockResolvedValue([{ status: 'draft', dueAt: null }]),
performanceSurveyWorkItem: {
count: jest.fn().mockResolvedValue(0),
create: jest.fn(async ({ data }) => ({
...data,
id: 'work-item-1',
})),
},
}
;(prisma.$transaction as jest.Mock).mockImplementation(async (callback) => callback(transactionClient))
})
afterEach(async () => {
await rm(tempRoot, { recursive: true, force: true })
})
test('streams validated WebP slices to S3 and uses the first slice as optional preview fallback', async () => {
const request = new Request('https://example.test/api/performance-survey/surveys/survey-1/work-items', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
targetId: 'target-1',
title: '案例 1',
processedImages: [{
uploadId: 'upload-1',
mimeType: 'image/webp',
width: 1600,
height: 900,
kind: 'slice',
sourceName: '1.webp',
sourceIndex: 0,
sliceIndex: 0,
sliceCount: 1,
}],
}),
})
const result = await createPerformanceSurveyWorkItemFromRequest(session, 'survey-1', request)
expect(uploadFileToS3).toHaveBeenCalledTimes(1)
expect(result.imageGroups).toEqual([
expect.objectContaining({
sourceName: '1.webp',
previewUrl: expect.stringContaining('.webp'),
previewWidth: 1600,
previewHeight: 900,
slices: [expect.objectContaining({ width: 1600, height: 900 })],
}),
])
expect(deleteOwnedUploadSession).toHaveBeenCalledWith('upload-1', 'user-1')
})
test('rejects client dimensions that do not match the actual WebP header', async () => {
const request = new Request('https://example.test/upload', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
targetId: 'target-1',
processedImages: [{
uploadId: 'upload-1',
mimeType: 'image/webp',
width: 1600,
height: 800,
kind: 'slice',
sourceName: '1.webp',
sourceIndex: 0,
sliceIndex: 0,
sliceCount: 1,
}],
}),
})
await expect(createPerformanceSurveyWorkItemFromRequest(session, 'survey-1', request)).rejects.toEqual(
new PerformanceSurveyApiError('图片「1.webp」尺寸校验失败,请重新上传'),
)
expect(uploadFileToS3).not.toHaveBeenCalled()
})
test('explicitly rejects raw JSON and legacy multipart uploads', async () => {
const rawJsonRequest = new Request('https://example.test/upload', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ images: [{ uploadId: 'old-upload', mimeType: 'image/png' }] }),
})
await expect(createPerformanceSurveyWorkItemFromRequest(session, 'survey-1', rawJsonRequest)).rejects.toEqual(
new PerformanceSurveyApiError('原始图片上传协议已停用,请刷新页面后重新上传', 409),
)
const multipartRequest = new Request('https://example.test/upload', {
method: 'POST',
headers: { 'content-type': 'multipart/form-data; boundary=legacy' },
body: '--legacy--',
})
await expect(createPerformanceSurveyWorkItemFromRequest(session, 'survey-1', multipartRequest)).rejects.toEqual(
new PerformanceSurveyApiError('旧版图片上传协议已停用,请刷新页面并使用最新版 Chrome 或 Edge 重新上传', 409),
)
})
})

View File

@ -0,0 +1,112 @@
import { sortPerformanceSurveyImagesByName } from '@/lib/performance-survey-image-order'
export type PerformanceSurveyProcessedImageKind = 'slice' | 'preview'
export type PerformanceSurveyBrowserProcessedImage = {
file: File
mimeType: 'image/webp'
width: number
height: number
kind: PerformanceSurveyProcessedImageKind
sourceName: string
sourceIndex: number
sliceIndex: number
sliceCount: number
}
type WorkerProcessedImage = Omit<PerformanceSurveyBrowserProcessedImage, 'file'> & {
blob: Blob
fileName: string
}
type WorkerSuccessMessage = {
id: string
ok: true
images: WorkerProcessedImage[]
}
type WorkerErrorMessage = {
id: string
ok: false
error: string
}
const DESKTOP_BROWSER_REQUIRED_MESSAGE = '图片需要在桌面版 Chrome 或 Edge 中处理,请更换浏览器后重新上传'
function assertPerformanceSurveyBrowserImageSupport() {
if (
typeof window === 'undefined'
|| typeof Worker === 'undefined'
|| typeof OffscreenCanvas === 'undefined'
|| typeof createImageBitmap === 'undefined'
) {
throw new Error(DESKTOP_BROWSER_REQUIRED_MESSAGE)
}
}
function runImageWorker(files: File[]): Promise<WorkerProcessedImage[]> {
assertPerformanceSurveyBrowserImageSupport()
return new Promise((resolve, reject) => {
let worker: Worker
try {
worker = new Worker(new URL('./performance-survey-image.worker.ts', import.meta.url), { type: 'module' })
} catch {
reject(new Error('浏览器图片处理线程启动失败,请使用桌面版 Chrome 或 Edge 重试'))
return
}
const requestId = `${Date.now()}-${Math.random().toString(36).slice(2)}`
let settled = false
const finish = (callback: () => void) => {
if (settled) return
settled = true
worker.terminate()
callback()
}
worker.onmessage = (event: MessageEvent<WorkerSuccessMessage | WorkerErrorMessage>) => {
const data = event.data
if (data?.id !== requestId) return
if (data.ok === true) {
finish(() => resolve(data.images))
} else {
finish(() => reject(new Error(data.error || '浏览器图片处理失败')))
}
}
worker.onerror = () => {
finish(() => reject(new Error('浏览器图片处理线程启动失败,请使用桌面版 Chrome 或 Edge 重试')))
}
worker.postMessage({ id: requestId, files })
})
}
export async function preparePerformanceSurveyImagesInBrowser(
files: File[],
onProgress?: (label: string) => void,
): Promise<PerformanceSurveyBrowserProcessedImage[]> {
if (files.length === 0) throw new Error('请至少选择 1 张图片')
const orderedFiles = sortPerformanceSurveyImagesByName(files, (file) => file.name)
onProgress?.(
orderedFiles.length === 1
? '正在浏览器后台生成预览和 WebP 切片'
: `正在浏览器后台转换 ${orderedFiles.length} 张有序切片为 WebP`,
)
const processed = await runImageWorker(orderedFiles)
return processed.map((item) => ({
file: new File([item.blob], item.fileName, {
type: item.mimeType,
lastModified: Date.now(),
}),
mimeType: item.mimeType,
width: item.width,
height: item.height,
kind: item.kind,
sourceName: item.sourceName,
sourceIndex: item.sourceIndex,
sliceIndex: item.sliceIndex,
sliceCount: item.sliceCount,
}))
}

View File

@ -0,0 +1,249 @@
/// <reference lib="webworker" />
export {}
type WorkerRequest = {
id: string
files: File[]
}
type WorkerProcessedImage = {
blob: Blob
fileName: string
mimeType: 'image/webp'
width: number
height: number
kind: 'slice' | 'preview'
sourceName: string
sourceIndex: number
sliceIndex: number
sliceCount: number
}
const OUTPUT_WIDTH = 1_600
const SLICE_HEIGHT = 1_500
const PREVIEW_WIDTH = 720
const PREVIEW_HEIGHT = 560
const MAX_SLICES_PER_SOURCE = 60
const MAX_ORDERED_SLICE_COUNT = 60
const SLICE_QUALITY = 0.76
const PREVIEW_QUALITY = 0.68
const workerScope = self as unknown as DedicatedWorkerGlobalScope
function removeFileExtension(fileName: string) {
const extensionIndex = fileName.lastIndexOf('.')
return extensionIndex > 0 ? fileName.slice(0, extensionIndex) : fileName
}
function getCanvasContext(canvas: OffscreenCanvas) {
const context = canvas.getContext('2d', { alpha: false })
if (!context) throw new Error('当前浏览器无法创建图片处理画布,请使用桌面版 Chrome 或 Edge')
return context
}
async function decodeImage(file: File) {
try {
return await createImageBitmap(file)
} catch {
throw new Error(`图片「${file.name}」无法解码,请确认文件没有损坏并使用 PNG、JPG 或 WebP 格式`)
}
}
async function renderSlice(
bitmap: ImageBitmap,
outputWidth: number,
outputHeight: number,
scale: number,
sliceIndex: number,
sliceCount: number,
) {
const outputTop = sliceIndex * SLICE_HEIGHT
const sliceHeight = Math.min(SLICE_HEIGHT, outputHeight - outputTop)
const sourceTop = Math.floor(outputTop / scale)
const sourceBottom = sliceIndex === sliceCount - 1
? bitmap.height
: Math.min(bitmap.height, Math.ceil((outputTop + sliceHeight) / scale))
const sourceHeight = Math.max(1, sourceBottom - sourceTop)
const canvas = new OffscreenCanvas(outputWidth, sliceHeight)
const context = getCanvasContext(canvas)
context.drawImage(
bitmap,
0,
sourceTop,
bitmap.width,
sourceHeight,
0,
0,
outputWidth,
sliceHeight,
)
const blob = await canvas.convertToBlob({ type: 'image/webp', quality: SLICE_QUALITY })
return { blob, width: outputWidth, height: sliceHeight }
}
async function renderPreview(firstSlice: Blob, sliceWidth: number, sliceHeight: number) {
const bitmap = await createImageBitmap(firstSlice)
try {
const targetWidth = Math.min(PREVIEW_WIDTH, sliceWidth)
const targetHeight = Math.min(PREVIEW_HEIGHT, sliceHeight)
const coverScale = Math.max(targetWidth / bitmap.width, targetHeight / bitmap.height)
const sourceWidth = Math.min(bitmap.width, targetWidth / coverScale)
const sourceHeight = Math.min(bitmap.height, targetHeight / coverScale)
const sourceLeft = Math.max(0, (bitmap.width - sourceWidth) / 2)
const canvas = new OffscreenCanvas(targetWidth, targetHeight)
const context = getCanvasContext(canvas)
context.drawImage(
bitmap,
sourceLeft,
0,
sourceWidth,
sourceHeight,
0,
0,
targetWidth,
targetHeight,
)
const blob = await canvas.convertToBlob({ type: 'image/webp', quality: PREVIEW_QUALITY })
return { blob, width: targetWidth, height: targetHeight }
} finally {
bitmap.close()
}
}
async function processSingleOriginal(file: File): Promise<WorkerProcessedImage[]> {
const bitmap = await decodeImage(file)
try {
if (!bitmap.width || !bitmap.height) throw new Error(`图片「${file.name}」尺寸无效`)
const scale = Math.min(1, OUTPUT_WIDTH / bitmap.width)
const outputWidth = Math.max(1, Math.round(bitmap.width * scale))
const outputHeight = Math.max(1, Math.round(bitmap.height * scale))
const sliceCount = Math.max(1, Math.ceil(outputHeight / SLICE_HEIGHT))
if (sliceCount > MAX_SLICES_PER_SOURCE) {
throw new Error(`图片「${file.name}」处理后需要 ${sliceCount} 个切片,单张长图最多支持 ${MAX_SLICES_PER_SOURCE} 个切片`)
}
const baseName = removeFileExtension(file.name)
const slices: WorkerProcessedImage[] = []
for (let sliceIndex = 0; sliceIndex < sliceCount; sliceIndex += 1) {
const rendered = await renderSlice(bitmap, outputWidth, outputHeight, scale, sliceIndex, sliceCount)
slices.push({
...rendered,
fileName: `${baseName}-${String(sliceIndex + 1).padStart(3, '0')}.webp`,
mimeType: 'image/webp',
kind: 'slice',
sourceName: file.name,
sourceIndex: 0,
sliceIndex,
sliceCount,
})
}
const preview = await renderPreview(slices[0].blob, slices[0].width, slices[0].height)
return [{
...preview,
fileName: `${baseName}-preview.webp`,
mimeType: 'image/webp',
kind: 'preview',
sourceName: file.name,
sourceIndex: 0,
sliceIndex: 0,
sliceCount,
}, ...slices]
} catch (error) {
throw new Error(
error instanceof Error && error.message
? error.message
: `图片「${file.name}」无法在浏览器中处理`,
)
} finally {
bitmap.close()
}
}
async function processOrderedSlices(files: File[]): Promise<WorkerProcessedImage[]> {
if (files.length > MAX_ORDERED_SLICE_COUNT) {
throw new Error(`单个案例最多上传 ${MAX_ORDERED_SLICE_COUNT} 张有序切片`)
}
const plans: Array<{
outputWidth: number
outputHeight: number
scale: number
sliceCount: number
}> = []
let totalSliceCount = 0
for (const file of files) {
const bitmap = await decodeImage(file)
try {
if (!bitmap.width || !bitmap.height) throw new Error(`图片「${file.name}」尺寸无效`)
const scale = Math.min(1, OUTPUT_WIDTH / bitmap.width)
const outputWidth = Math.max(1, Math.round(bitmap.width * scale))
const outputHeight = Math.max(1, Math.round(bitmap.height * scale))
const sliceCount = Math.max(1, Math.ceil(outputHeight / SLICE_HEIGHT))
if (sliceCount > MAX_SLICES_PER_SOURCE) {
throw new Error(`图片「${file.name}」处理后需要 ${sliceCount} 个切片,单张源图最多支持 ${MAX_SLICES_PER_SOURCE} 个切片`)
}
totalSliceCount += sliceCount
plans.push({ outputWidth, outputHeight, scale, sliceCount })
} finally {
bitmap.close()
}
}
if (totalSliceCount > MAX_ORDERED_SLICE_COUNT) {
throw new Error(`这些图片处理后共需 ${totalSliceCount} 个切片,单个案例最多支持 ${MAX_ORDERED_SLICE_COUNT} 个切片`)
}
const processed: WorkerProcessedImage[] = []
for (let sourceIndex = 0; sourceIndex < files.length; sourceIndex += 1) {
const file = files[sourceIndex]
const plan = plans[sourceIndex]
const bitmap = await decodeImage(file)
try {
for (let sliceIndex = 0; sliceIndex < plan.sliceCount; sliceIndex += 1) {
const rendered = await renderSlice(
bitmap,
plan.outputWidth,
plan.outputHeight,
plan.scale,
sliceIndex,
plan.sliceCount,
)
processed.push({
...rendered,
fileName: plan.sliceCount === 1
? `${removeFileExtension(file.name)}.webp`
: `${removeFileExtension(file.name)}-${String(sliceIndex + 1).padStart(3, '0')}.webp`,
mimeType: 'image/webp',
kind: 'slice',
sourceName: file.name,
sourceIndex,
sliceIndex,
sliceCount: plan.sliceCount,
})
}
} finally {
bitmap.close()
}
}
return processed
}
workerScope.onmessage = async (event: MessageEvent<WorkerRequest>) => {
const { id, files } = event.data || {}
try {
if (!id || !Array.isArray(files) || files.length === 0) throw new Error('没有可处理的图片')
if (typeof OffscreenCanvas === 'undefined' || typeof createImageBitmap === 'undefined') {
throw new Error('图片需要在桌面版 Chrome 或 Edge 中处理,请更换浏览器后重新上传')
}
const images = files.length === 1
? await processSingleOriginal(files[0])
: await processOrderedSlices(files)
workerScope.postMessage({ id, ok: true, images })
} catch (error) {
workerScope.postMessage({
id,
ok: false,
error: error instanceof Error ? error.message : '浏览器图片处理失败',
})
}
}

View File

@ -0,0 +1,215 @@
import { PERFORMANCE_SURVEY_IMAGE_LIMITS } from '@/lib/performance-survey-image-processing'
export const PERFORMANCE_SURVEY_PROCESSED_IMAGE_LIMITS = {
maxArtifactBytes: 8 * 1024 * 1024,
maxBatchBytes: 256 * 1024 * 1024,
maxSliceWidth: PERFORMANCE_SURVEY_IMAGE_LIMITS.maxOutputWidth,
maxSliceHeight: PERFORMANCE_SURVEY_IMAGE_LIMITS.sliceHeight,
maxPreviewWidth: PERFORMANCE_SURVEY_IMAGE_LIMITS.previewWidth,
maxPreviewHeight: PERFORMANCE_SURVEY_IMAGE_LIMITS.previewHeight,
} as const
export type PerformanceSurveyProcessedImageKind = 'slice' | 'preview'
export type PerformanceSurveyProcessedImageDeclaration = {
uploadId: string
mimeType: 'image/webp'
width: number
height: number
kind: PerformanceSurveyProcessedImageKind
sourceName: string
sourceIndex: number
sliceIndex: number
sliceCount: number
}
export type PerformanceSurveyProcessedImageGroup = {
sourceIndex: number
sourceName: string
sliceCount: number
preview: PerformanceSurveyProcessedImageDeclaration | null
slices: PerformanceSurveyProcessedImageDeclaration[]
}
export class PerformanceSurveyProcessedImageError extends Error {}
function readRequiredText(value: unknown, label: string, maxLength: number) {
const normalized = String(value ?? '').trim()
if (!normalized) throw new PerformanceSurveyProcessedImageError(`${label}不能为空`)
if (normalized.length > maxLength || /[\u0000-\u001f\u007f]/.test(normalized)) {
throw new PerformanceSurveyProcessedImageError(`${label}格式无效`)
}
return normalized
}
function readInteger(value: unknown, label: string, min: number, max: number) {
const normalized = Number(value)
if (!Number.isInteger(normalized) || normalized < min || normalized > max) {
throw new PerformanceSurveyProcessedImageError(`${label}无效`)
}
return normalized
}
function normalizeDeclaration(value: unknown): PerformanceSurveyProcessedImageDeclaration {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new PerformanceSurveyProcessedImageError('预处理图片参数无效')
}
const input = value as Record<string, unknown>
const kind = String(input.kind || '').trim()
if (kind !== 'slice' && kind !== 'preview') {
throw new PerformanceSurveyProcessedImageError('预处理图片类型无效')
}
const mimeType = String(input.mimeType || '').trim().toLowerCase()
if (mimeType !== 'image/webp') {
throw new PerformanceSurveyProcessedImageError('预处理图片只接受 WebP 格式')
}
const maxWidth = kind === 'preview'
? PERFORMANCE_SURVEY_PROCESSED_IMAGE_LIMITS.maxPreviewWidth
: PERFORMANCE_SURVEY_PROCESSED_IMAGE_LIMITS.maxSliceWidth
const maxHeight = kind === 'preview'
? PERFORMANCE_SURVEY_PROCESSED_IMAGE_LIMITS.maxPreviewHeight
: PERFORMANCE_SURVEY_PROCESSED_IMAGE_LIMITS.maxSliceHeight
return {
uploadId: readRequiredText(input.uploadId, '图片上传凭证', 128),
mimeType: 'image/webp',
width: readInteger(input.width, '图片宽度', 1, maxWidth),
height: readInteger(input.height, '图片高度', 1, maxHeight),
kind,
sourceName: readRequiredText(input.sourceName, '源文件名', 255),
sourceIndex: readInteger(
input.sourceIndex,
'源文件序号',
0,
PERFORMANCE_SURVEY_IMAGE_LIMITS.maxSourceCount - 1,
),
sliceIndex: readInteger(
input.sliceIndex,
'切片序号',
0,
PERFORMANCE_SURVEY_IMAGE_LIMITS.maxSourceCount - 1,
),
sliceCount: readInteger(
input.sliceCount,
'切片数量',
1,
PERFORMANCE_SURVEY_IMAGE_LIMITS.maxSourceCount,
),
}
}
export function validatePerformanceSurveyProcessedImages(
value: unknown,
): PerformanceSurveyProcessedImageGroup[] {
if (!Array.isArray(value) || value.length === 0) {
throw new PerformanceSurveyProcessedImageError('每个案例至少上传 1 张预处理图片')
}
if (value.length > PERFORMANCE_SURVEY_IMAGE_LIMITS.maxSourceCount * 2) {
throw new PerformanceSurveyProcessedImageError('预处理图片数量过多')
}
const declarations = value.map(normalizeDeclaration)
const uploadIds = new Set<string>()
const groups = new Map<number, PerformanceSurveyProcessedImageDeclaration[]>()
for (const declaration of declarations) {
if (uploadIds.has(declaration.uploadId)) {
throw new PerformanceSurveyProcessedImageError('图片上传凭证重复')
}
uploadIds.add(declaration.uploadId)
const current = groups.get(declaration.sourceIndex) || []
current.push(declaration)
groups.set(declaration.sourceIndex, current)
}
const sourceIndexes = Array.from(groups.keys()).sort((a, b) => a - b)
if (sourceIndexes.length > PERFORMANCE_SURVEY_IMAGE_LIMITS.maxSourceCount) {
throw new PerformanceSurveyProcessedImageError(
`单个案例最多上传 ${PERFORMANCE_SURVEY_IMAGE_LIMITS.maxSourceCount} 张源图片`,
)
}
sourceIndexes.forEach((sourceIndex, index) => {
if (sourceIndex !== index) {
throw new PerformanceSurveyProcessedImageError('源文件序号必须从 0 开始且连续')
}
})
let totalSliceCount = 0
return sourceIndexes.map((sourceIndex) => {
const records = groups.get(sourceIndex) || []
const sourceNames = new Set(records.map((item) => item.sourceName))
const sliceCounts = new Set(records.map((item) => item.sliceCount))
if (sourceNames.size !== 1 || sliceCounts.size !== 1) {
throw new PerformanceSurveyProcessedImageError('同一源文件的名称或切片数量不一致')
}
const previews = records.filter((item) => item.kind === 'preview')
const slices = records.filter((item) => item.kind === 'slice').sort((a, b) => a.sliceIndex - b.sliceIndex)
const sliceCount = records[0].sliceCount
if (previews.length > 1) {
throw new PerformanceSurveyProcessedImageError(`源文件「${records[0].sourceName}」只能有 1 张预览图`)
}
if (previews[0] && previews[0].sliceIndex !== 0) {
throw new PerformanceSurveyProcessedImageError(`源文件「${records[0].sourceName}」预览图序号无效`)
}
if (slices.length !== sliceCount) {
throw new PerformanceSurveyProcessedImageError(`源文件「${records[0].sourceName}」切片不完整`)
}
slices.forEach((slice, index) => {
if (slice.sliceIndex !== index) {
throw new PerformanceSurveyProcessedImageError(`源文件「${records[0].sourceName}」切片序号不连续`)
}
})
totalSliceCount += slices.length
if (totalSliceCount > PERFORMANCE_SURVEY_IMAGE_LIMITS.maxSourceCount) {
throw new PerformanceSurveyProcessedImageError(
`单个案例最多上传 ${PERFORMANCE_SURVEY_IMAGE_LIMITS.maxSourceCount} 张有序切片`,
)
}
return {
sourceIndex,
sourceName: records[0].sourceName,
sliceCount,
preview: previews[0] || null,
slices,
}
})
}
function readUInt24LE(buffer: Buffer, offset: number) {
return buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16)
}
export function readPerformanceSurveyWebpDimensions(buffer: Buffer) {
if (buffer.length < 30 || buffer.toString('ascii', 0, 4) !== 'RIFF' || buffer.toString('ascii', 8, 12) !== 'WEBP') {
throw new PerformanceSurveyProcessedImageError('预处理图片不是有效的 WebP 文件')
}
const chunkType = buffer.toString('ascii', 12, 16)
if (chunkType === 'VP8X') {
return {
width: readUInt24LE(buffer, 24) + 1,
height: readUInt24LE(buffer, 27) + 1,
}
}
if (chunkType === 'VP8L' && buffer[20] === 0x2f) {
const b1 = buffer[21]
const b2 = buffer[22]
const b3 = buffer[23]
const b4 = buffer[24]
return {
width: 1 + (b1 | ((b2 & 0x3f) << 8)),
height: 1 + ((b2 >> 6) | (b3 << 2) | ((b4 & 0x0f) << 10)),
}
}
if (chunkType === 'VP8 ' && buffer[23] === 0x9d && buffer[24] === 0x01 && buffer[25] === 0x2a) {
return {
width: buffer.readUInt16LE(26) & 0x3fff,
height: buffer.readUInt16LE(28) & 0x3fff,
}
}
throw new PerformanceSurveyProcessedImageError('无法读取预处理 WebP 图片尺寸')
}

View File

@ -1,5 +1,5 @@
import { randomUUID } from 'crypto'
import { readFile, rm, unlink } from 'fs/promises'
import { open, rm, unlink } from 'fs/promises'
import path from 'path'
import type { Session } from 'next-auth'
import { pinyin } from 'pinyin-pro'
@ -41,16 +41,21 @@ import {
PERFORMANCE_SURVEY_IMAGE_LIMITS,
PerformanceSurveyImageProcessingError,
assertPerformanceSurveyImageBatch,
assertPerformanceSurveyImageRequestSize,
inspectPerformanceSurveyImage,
processPerformanceSurveyImage,
serializePerformanceSurveyImagePayload,
withPerformanceSurveyImageProcessingSlot,
type PerformanceSurveyStoredImageGroup,
} from '@/lib/performance-survey-image-processing'
import { getPerformanceSurveyTargetEmployeeIds } from '@/lib/performance-survey-target-policy'
import { sortPerformanceSurveyImagesByName } from '@/lib/performance-survey-image-order'
import { deleteFromS3, uploadToS3 } from '@/lib/s3'
import {
PERFORMANCE_SURVEY_PROCESSED_IMAGE_LIMITS,
PerformanceSurveyProcessedImageError,
readPerformanceSurveyWebpDimensions,
validatePerformanceSurveyProcessedImages,
type PerformanceSurveyProcessedImageDeclaration,
} from '@/lib/performance-survey-processed-images'
import { deleteFromS3, uploadFileToS3, uploadToS3 } from '@/lib/s3'
import {
deleteOwnedUploadSession,
getOwnedUploadSession,
@ -109,6 +114,19 @@ function assertLockedSurveyOpen(survey: { status: string; dueAt?: Date | null }
}
}
function assertLockedSurveyAcceptsWorkItem(
survey: { status: string; dueAt?: Date | null } | null,
allowDraft: boolean,
) {
if (!survey) throw new PerformanceSurveyApiError('调研不存在', 404)
if (survey.status !== 'open' && !(allowDraft && survey.status === 'draft')) {
throw new PerformanceSurveyApiError('调研未开放或已关闭')
}
if (survey.status === 'open' && survey.dueAt && new Date(survey.dueAt).getTime() < Date.now()) {
throw new PerformanceSurveyApiError('调研已超过截止时间')
}
}
const PERFORMANCE_SURVEY_DEPARTMENT_CACHE_MS = Math.max(
5,
Number(process.env.PERFORMANCE_SURVEY_DEPARTMENT_CACHE_SECONDS || 60),
@ -2247,8 +2265,8 @@ export async function createPerformanceSurvey(session: Session | null, body: any
if (openNow) {
await queueSurveyAssignmentNotifications(surveyId)
await queueSurveyTargetConfirmationNotifications(surveyId)
}
await queueSurveyTargetConfirmationNotifications(surveyId)
return getPerformanceSurveyDetail(session, surveyId)
}
@ -2478,6 +2496,29 @@ export async function updatePerformanceSurvey(session: Session | null, surveyId:
throw new PerformanceSurveyApiError('已撤销的调研不能修改')
}
if (data.status === 'open' && lockedSurvey.status === 'draft') {
const template = survey.templateSnapshot as PerformanceSurveyTemplateShape
if (isVisualCaseTemplate(template)) {
const requiredWorkItemCount = Math.max(1, Number(template.requiredWorkItemCount || 3))
const targets = await tx.performanceSurveyTarget.findMany({
where: { surveyId },
select: {
targetName: true,
_count: { select: { workItems: true } },
},
})
const incompleteTargets = targets.filter((target) => target._count.workItems < requiredWorkItemCount)
if (incompleteTargets.length > 0) {
throw new PerformanceSurveyApiError(
`视觉评分作品尚未上传完整:${incompleteTargets
.map((target) => `${target.targetName}(${target._count.workItems}/${requiredWorkItemCount})`)
.join('、')}`,
409,
)
}
}
}
if (isMonthlyAssessment && body?.assessmentMonth !== undefined) {
await lockMonthlyAssessmentKeys(
tx,
@ -2813,14 +2854,10 @@ export async function getPerformanceSurveyResults(
}
}
function readFormText(formData: FormData, key: string) {
return clean(formData.get(key))
}
function readImageFiles(formData: FormData) {
return ['images', 'image', 'files']
.flatMap((key) => formData.getAll(key))
.filter((value): value is File => typeof File !== 'undefined' && value instanceof File && value.size > 0)
type ResolvedPerformanceSurveyProcessedImage = {
declaration: PerformanceSurveyProcessedImageDeclaration
filePath: string
fileSize: number
}
type PerformanceSurveyWorkItemImageSource = {
@ -2830,9 +2867,14 @@ type PerformanceSurveyWorkItemImageSource = {
readBuffer: () => Promise<Buffer>
}
type PerformanceSurveyChunkedImage = {
uploadId?: unknown
mimeType?: unknown
function readFormText(formData: FormData, key: string) {
return clean(formData.get(key))
}
function readImageFiles(formData: FormData) {
return ['images', 'image', 'files']
.flatMap((key) => formData.getAll(key))
.filter((value): value is File => typeof File !== 'undefined' && value instanceof File && value.size > 0)
}
async function cleanupPerformanceSurveyChunkedUploads(
@ -2851,76 +2893,210 @@ export async function createPerformanceSurveyWorkItemFromRequest(
surveyId: string,
request: Request,
) {
try {
return await withPerformanceSurveyImageProcessingSlot(async () => {
const contentType = (request.headers.get('content-type') || '').toLowerCase()
if (contentType.includes('application/json')) {
const body = await request.json()
return createPerformanceSurveyWorkItemFromChunkedUploads(session, surveyId, body)
}
const contentType = (request.headers.get('content-type') || '').toLowerCase()
if (!contentType.includes('application/json')) {
throw new PerformanceSurveyApiError('旧版图片上传协议已停用,请刷新页面并使用最新版 Chrome 或 Edge 重新上传', 409)
}
assertPerformanceSurveyImageRequestSize(request.headers.get('content-length'))
const formData = await request.formData()
return createPerformanceSurveyWorkItem(session, surveyId, formData)
})
} catch (error) {
if (error instanceof PerformanceSurveyImageProcessingError) {
const status = error.message.includes('任务较多') ? 429 : 400
throw new PerformanceSurveyApiError(error.message, status)
}
throw error
const body = await request.json()
if (Array.isArray(body?.processedImages)) {
return createPerformanceSurveyWorkItemFromProcessedUploads(session, surveyId, body)
}
if (Array.isArray(body?.images)) {
throw new PerformanceSurveyApiError('原始图片上传协议已停用,请刷新页面后重新上传', 409)
}
throw new PerformanceSurveyApiError('缺少预处理图片')
}
async function readPerformanceSurveyWebpFileDimensions(filePath: string) {
const handle = await open(filePath, 'r')
try {
const header = Buffer.alloc(64)
const { bytesRead } = await handle.read(header, 0, header.length, 0)
return readPerformanceSurveyWebpDimensions(header.subarray(0, bytesRead))
} finally {
await handle.close()
}
}
async function createPerformanceSurveyWorkItemFromChunkedUploads(
async function resolvePerformanceSurveyProcessedUpload(
declaration: PerformanceSurveyProcessedImageDeclaration,
userId: string,
): Promise<ResolvedPerformanceSurveyProcessedImage> {
const uploadSession = await getOwnedUploadSession(declaration.uploadId, userId)
if (!uploadSession) throw new PerformanceSurveyApiError('图片上传已过期,请重新选择图片')
if (uploadSession.fileSize > PERFORMANCE_SURVEY_PROCESSED_IMAGE_LIMITS.maxArtifactBytes) {
throw new PerformanceSurveyApiError('单张预处理图片不能超过 8MB')
}
const filePath = await getOwnedUploadedFile(declaration.uploadId, userId)
if (!filePath) throw new PerformanceSurveyApiError(`图片「${declaration.sourceName}」上传不完整,请重试`)
return {
declaration,
filePath,
fileSize: uploadSession.fileSize,
}
}
async function createPerformanceSurveyWorkItemFromProcessedUploads(
session: Session | null,
surveyId: string,
body: any,
) {
const ctx = await getPerformanceSurveyContext(session)
const userId = clean((session?.user as any)?.id)
if (!userId) throw new PerformanceSurveyApiError('请先登录', 401)
const targetId = clean(body?.targetId)
if (!targetId) throw new PerformanceSurveyApiError('缺少评价对象')
const declaredImages = Array.isArray(body?.images) ? body.images as PerformanceSurveyChunkedImage[] : []
if (declaredImages.length === 0) throw new PerformanceSurveyApiError('每个案例至少上传 1 张图片')
if (declaredImages.length > PERFORMANCE_SURVEY_IMAGE_LIMITS.maxSourceCount) {
throw new PerformanceSurveyApiError(`单个案例最多上传 ${PERFORMANCE_SURVEY_IMAGE_LIMITS.maxSourceCount} 张切片`)
let groups: ReturnType<typeof validatePerformanceSurveyProcessedImages>
try {
groups = validatePerformanceSurveyProcessedImages(body?.processedImages)
} catch (error) {
if (error instanceof PerformanceSurveyProcessedImageError) {
throw new PerformanceSurveyApiError(error.message)
}
throw error
}
const survey = await prisma.performanceSurvey.findUnique({
where: { id: surveyId },
include: {
targets: true,
workItems: { where: { targetId }, select: { id: true } },
},
})
if (!survey) throw new PerformanceSurveyApiError('调研不存在', 404)
const template = survey.templateSnapshot as PerformanceSurveyTemplateShape
if (!isVisualCaseTemplate(template)) throw new PerformanceSurveyApiError('当前模板不支持案例上传')
const target = survey.targets.find((item) => item.id === targetId)
if (!target) throw new PerformanceSurveyApiError('评价对象不存在', 404)
const canManage = await canManageSurvey(ctx, survey)
if (survey.status !== 'open' && !(survey.status === 'draft' && canManage)) {
throw new PerformanceSurveyApiError('调研未开放或已关闭')
}
const canUpload = canManage || Boolean(ctx.employee?.id && target.employeeProfileId === ctx.employee.id)
if (!canUpload) throw new PerformanceSurveyApiError('无权限提交该案例', 403)
const requiredWorkItemCount = Math.max(1, Number(template.requiredWorkItemCount || 3))
if (survey.workItems.length >= requiredWorkItemCount) {
throw new PerformanceSurveyApiError(`当前调研最多提交 ${requiredWorkItemCount} 个案例`)
}
const uploads: Array<{ uploadId: string; filePath: string }> = []
const sources: PerformanceSurveyWorkItemImageSource[] = []
const resolvedByUploadId = new Map<string, ResolvedPerformanceSurveyProcessedImage>()
const uploadedUrls: string[] = []
try {
for (const declared of declaredImages) {
const uploadId = clean(declared?.uploadId)
const mimeType = clean(declared?.mimeType) || 'image/unknown'
if (!uploadId) throw new PerformanceSurveyApiError('图片上传凭证无效')
if (uploads.some((item) => item.uploadId === uploadId)) {
throw new PerformanceSurveyApiError('图片上传凭证重复')
let totalBytes = 0
for (const group of groups) {
for (const declaration of [...group.slices, ...(group.preview ? [group.preview] : [])]) {
const resolved = await resolvePerformanceSurveyProcessedUpload(declaration, userId)
uploads.push({ uploadId: declaration.uploadId, filePath: resolved.filePath })
totalBytes += resolved.fileSize
if (totalBytes > PERFORMANCE_SURVEY_PROCESSED_IMAGE_LIMITS.maxBatchBytes) {
throw new PerformanceSurveyApiError('单个案例的预处理图片总大小不能超过 256MB')
}
const dimensions = await readPerformanceSurveyWebpFileDimensions(resolved.filePath)
if (dimensions.width !== declaration.width || dimensions.height !== declaration.height) {
throw new PerformanceSurveyApiError(`图片「${declaration.sourceName}」尺寸校验失败,请重新上传`)
}
resolvedByUploadId.set(declaration.uploadId, resolved)
}
if (!mimeType.startsWith('image/')) throw new PerformanceSurveyApiError('只支持上传图片文件')
}
const uploadSession = await getOwnedUploadSession(uploadId, userId)
if (!uploadSession) throw new PerformanceSurveyApiError('图片上传已过期,请重新选择图片')
if (uploadSession.fileSize > PERFORMANCE_SURVEY_IMAGE_LIMITS.maxSourceBytes) {
throw new PerformanceSurveyApiError('单张图片不能超过 200MB')
const uploadBatchId = `${Date.now()}-${randomUUID()}`
const imageGroups: PerformanceSurveyStoredImageGroup[] = []
for (const group of groups) {
const sliceRecords: PerformanceSurveyStoredImageGroup['slices'] = []
for (const declaration of group.slices) {
const resolved = resolvedByUploadId.get(declaration.uploadId)!
const fileName = [
'performance-survey/work-items',
surveyId,
targetId,
`${uploadBatchId}-${group.sourceIndex + 1}-${declaration.sliceIndex + 1}.webp`,
].join('/')
const url = await uploadFileToS3(resolved.filePath, fileName, declaration.mimeType)
uploadedUrls.push(url)
sliceRecords.push({ url, width: declaration.width, height: declaration.height })
}
const filePath = await getOwnedUploadedFile(uploadId, userId)
if (!filePath) throw new PerformanceSurveyApiError(`图片「${uploadSession.fileName}」上传不完整,请重试`)
uploads.push({ uploadId, filePath })
sources.push({
name: uploadSession.fileName,
size: uploadSession.fileSize,
mimeType,
readBuffer: () => readFile(filePath),
const firstSlice = sliceRecords[0]
let previewUrl = firstSlice.url
let previewWidth = firstSlice.width
let previewHeight = firstSlice.height
if (group.preview) {
const resolved = resolvedByUploadId.get(group.preview.uploadId)!
const previewFileName = [
'performance-survey/work-items',
surveyId,
targetId,
`${uploadBatchId}-${group.sourceIndex + 1}-preview.webp`,
].join('/')
previewUrl = await uploadFileToS3(resolved.filePath, previewFileName, group.preview.mimeType)
uploadedUrls.push(previewUrl)
previewWidth = group.preview.width
previewHeight = group.preview.height
}
const width = Math.max(...sliceRecords.map((slice) => slice.width))
const height = sliceRecords.reduce((sum, slice) => sum + slice.height, 0)
imageGroups.push({
version: 1,
sourceName: group.sourceName,
sourceWidth: width,
sourceHeight: height,
width,
height,
previewUrl,
previewWidth,
previewHeight,
slices: sliceRecords,
})
}
return await createPerformanceSurveyWorkItemFromSources(session, surveyId, {
targetId: clean(body?.targetId),
title: clean(body?.title),
description: clean(body?.description),
sources: sortPerformanceSurveyImagesByName(sources, (source) => source.name),
const title = clean(body?.title) || `案例 ${survey.workItems.length + 1}`
const description = clean(body?.description)
const created = await prisma.$transaction(async (tx) => {
assertLockedSurveyAcceptsWorkItem(
await lockPerformanceSurvey(tx, surveyId),
survey.status === 'draft' && canManage,
)
const currentCount = await tx.performanceSurveyWorkItem.count({ where: { surveyId, targetId } })
if (currentCount >= requiredWorkItemCount) {
throw new PerformanceSurveyApiError(`当前调研最多提交 ${requiredWorkItemCount} 个案例`)
}
return tx.performanceSurveyWorkItem.create({
data: {
id: randomUUID(),
surveyId,
targetId,
submitterUserId: ctx.user.id,
submitterEmployeeId: ctx.employee?.id || null,
title,
description,
imageUrls: imageGroups as any,
sortOrder: currentCount,
status: 'submitted',
submittedAt: new Date(),
},
})
})
const images = serializePerformanceSurveyImagePayload(created.imageUrls)
return {
id: created.id,
title: created.title,
description: created.description,
imageUrls: images.imageUrls,
imageGroups: images.imageGroups,
submittedAt: created.submittedAt,
}
} catch (error) {
await Promise.allSettled(uploadedUrls.map((url) => deleteFromS3(url)))
if (error instanceof PerformanceSurveyProcessedImageError) {
throw new PerformanceSurveyApiError(error.message)
}
throw error
} finally {
await cleanupPerformanceSurveyChunkedUploads(userId, uploads)
}
@ -2970,11 +3146,12 @@ async function createPerformanceSurveyWorkItemFromSources(
if (!survey) throw new PerformanceSurveyApiError('调研不存在', 404)
const template = survey.templateSnapshot as PerformanceSurveyTemplateShape
if (!isVisualCaseTemplate(template)) throw new PerformanceSurveyApiError('当前模板不支持案例上传')
if (survey.status !== 'open') throw new PerformanceSurveyApiError('调研未开放或已关闭')
const target = survey.targets.find((item) => item.id === targetId)
if (!target) throw new PerformanceSurveyApiError('评价对象不存在', 404)
const canManage = await canManageSurvey(ctx, survey)
if (survey.status !== 'open' && !(survey.status === 'draft' && canManage)) {
throw new PerformanceSurveyApiError('调研未开放或已关闭')
}
const canUpload = canManage || Boolean(ctx.employee?.id && target.employeeProfileId === ctx.employee.id)
if (!canUpload) throw new PerformanceSurveyApiError('无权限提交该案例', 403)
const requiredWorkItemCount = Math.max(1, Number(template.requiredWorkItemCount || 3))
@ -3066,7 +3243,10 @@ async function createPerformanceSurveyWorkItemFromSources(
}
const created = await prisma.$transaction(async (tx) => {
assertLockedSurveyOpen(await lockPerformanceSurvey(tx, surveyId))
assertLockedSurveyAcceptsWorkItem(
await lockPerformanceSurvey(tx, surveyId),
survey.status === 'draft' && canManage,
)
const currentCount = await tx.performanceSurveyWorkItem.count({ where: { surveyId, targetId } })
if (currentCount >= requiredWorkItemCount) {
throw new PerformanceSurveyApiError(`当前调研最多提交 ${requiredWorkItemCount} 个案例`)
@ -3682,7 +3862,25 @@ async function resolveWorkCooperationEvaluators(targetEmployee: any) {
} else if (isWorkCooperationPLevel(targetEmployee)) {
evaluatorDingtalkUserId = clean(targetEmployee.managerDingtalkUserId)
if (!evaluatorDingtalkUserId) {
throw new PerformanceSurveyApiError(`无法确定${targetName}的直属主管:人员档案缺少主管唯一值`, 409)
const departmentPath = normalizeDepartmentPath(targetEmployee.departmentPath)
if (!departmentPath) {
throw new PerformanceSurveyApiError(`无法确定${targetName}的直属主管:缺少完整组织路径,请手动选择评分人`, 409)
}
const managers = await prisma.performanceSurveyEmployeeProfile.findMany({
where: {
AND: [
accountWhere,
{ departmentPath },
{ OR: [{ levelType: 'M' }, { positionLevel: { startsWith: 'M' } }] },
{ id: { not: targetEmployee.id } },
],
},
take: 2,
})
if (managers.length !== 1 || !clean(managers[0].dingtalkUserId)) {
throw new PerformanceSurveyApiError(`无法唯一确定${targetName}所在组织的 M 级主管,请手动选择评分人`, 409)
}
evaluatorDingtalkUserId = clean(managers[0].dingtalkUserId)
}
} else {
throw new PerformanceSurveyApiError(`无法确定${targetName}的 P/M 职级,请先校准钉钉人员档案`, 409)

View File

@ -1,4 +1,6 @@
import { S3Client, PutObjectCommand, DeleteObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3'
import { createReadStream } from 'fs'
import { stat } from 'fs/promises'
import { Readable } from 'stream'
/**
@ -107,6 +109,43 @@ export async function uploadToS3(
}
}
/**
* 将磁盘文件以流的方式写入 S3,避免把浏览器已预处理的图片再次整体读入 Node.js 内存。
*/
export async function uploadFileToS3(
filePath: string,
fileName: string,
contentType: string,
): Promise<string> {
const fileStats = await stat(filePath)
if (!fileStats.isFile() || fileStats.size <= 0) {
throw new Error('待上传文件无效')
}
const s3FilePath = (process.env.S3_FILE_PATH || '').trim()
const normalizedPath = s3FilePath && !s3FilePath.endsWith('/') ? `${s3FilePath}/` : s3FilePath
const normalizedFileName = fileName.startsWith('/') ? fileName.slice(1) : fileName
const key = `${normalizedPath}${normalizedFileName}`
const body = createReadStream(filePath)
const command = new PutObjectCommand({
Bucket: process.env.S3_BUCKET!,
Key: key,
Body: body,
ContentLength: fileStats.size,
ContentType: contentType,
ACL: 'public-read',
})
try {
await s3Client.send(command)
return `${process.env.S3_PUBLIC_DOMAIN}/${key}`
} catch (error) {
body.destroy()
console.error('[S3] File stream upload error (after all retries):', error)
throw new Error('S3上传失败,请稍后重试')
}
}
export async function downloadFromS3(fileUrl: string): Promise<Buffer> {
try {
// Extract key from URL