'use client'; import { useCallback, useEffect, useRef, useState, type RefObject } from 'react'; import { Download, FileText, LoaderCircle, Paperclip, RotateCw, X } from 'lucide-react'; import { MAX_ATTACHMENT_BYTES, MAX_ATTACHMENTS, formatFileSize, type Attachment } from '@/lib/attachments'; import { appPath } from '@/lib/base-path'; export function AttachmentList({ files }: { files: Attachment[] }) { if (!files.length) return

暂无附件

; return ; } export function AttachmentPicker({ files, onChange, disabled, uploading, onUploadingChange, onNewUpload, inputRef, compact = false }: { inputRef?: RefObject; compact?: boolean; files: Attachment[]; onChange: (files: Attachment[]) => void; disabled: boolean; uploading: boolean; onUploadingChange: (busy: boolean) => void; onNewUpload: (file: Attachment) => void; }) { const localInput = useRef(null); const input = inputRef ?? localInput; const inFlight = useRef(false); const [errors, setErrors] = useState([]); const [progress, setProgress] = useState(''); const [recoverable, setRecoverable] = useState([]); const [recoveryLoading, setRecoveryLoading] = useState(true); const [recoveryError, setRecoveryError] = useState(''); const [recoveryOpen, setRecoveryOpen] = useState(false); const recoveryRequest = useRef(null); const loadRecovery = useCallback(() => { recoveryRequest.current?.abort(); const controller = new AbortController(); recoveryRequest.current = controller; const timeout = setTimeout(() => controller.abort(), 15000); return fetch(appPath('/api/attachments'), { signal: controller.signal, cache: 'no-store' }) .then(async response => { const result = await response.json().catch(() => null) as { attachments?: Attachment[]; error?: string } | null; if (!response.ok || !Array.isArray(result?.attachments)) throw new Error(result?.error || '未能加载未保存附件,请重试。'); return result.attachments; }) .then(attachments => { if (recoveryRequest.current === controller) setRecoverable(attachments); }) .catch(error => { // Superseded requests and unmounted pickers must not replace the latest result. if (recoveryRequest.current === controller) setRecoveryError(controller.signal.aborted ? '未保存附件加载超时,请重试。' : error instanceof Error ? error.message : '未能加载未保存附件,请重试。'); }) .finally(() => { clearTimeout(timeout); if (recoveryRequest.current === controller) { recoveryRequest.current = null; setRecoveryLoading(false); } }); }, []); function refreshRecovery() { setRecoveryLoading(true); setRecoveryError(''); void loadRecovery(); } useEffect(() => { void loadRecovery(); return () => { recoveryRequest.current?.abort(); recoveryRequest.current = null; }; }, [loadRecovery]); const available = recoverable.filter(file => !files.some(selected => selected.id === file.id)); async function discard(file: Attachment) { onUploadingChange(true); try { const response = await fetch(appPath('/api/attachments/' + file.id), { method: 'DELETE' }); if (!response.ok) throw new Error('该附件可能已保存,请刷新后核对。'); setRecoverable(previous => previous.filter(item => item.id !== file.id)); } catch (error) { setErrors([error instanceof Error ? error.message : '附件移除失败,请重试。']); } finally { onUploadingChange(false); } } async function upload(selected: File[]) { if (!selected.length || inFlight.current || disabled) return; const issues: string[] = []; const allowed: File[] = []; for (const file of selected) { if (!file.size) issues.push(`${file.name}:空文件无法上传。`); else if (file.size > MAX_ATTACHMENT_BYTES) issues.push(`${file.name}:超过 20 MB,请压缩后重新选择。`); else if (files.length + allowed.length >= MAX_ATTACHMENTS) issues.push(`${file.name}:每条需求最多 10 个附件。`); else allowed.push(file); } setErrors(issues); if (!allowed.length) return; inFlight.current = true; onUploadingChange(true); const uploaded = [...files]; try { for (let index = 0; index < allowed.length; index++) { const file = allowed[index]; setProgress(`正在上传 ${index + 1}/${allowed.length}:${file.name}`); const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 120000); let quotaReached = false; try { const body = new FormData(); body.append('file', file); const response = await fetch(appPath('/api/attachments'), { method: 'POST', body, signal: controller.signal }); const result = await response.json().catch(() => ({})) as { error?: string; attachment?: Attachment }; if (response.status === 409) { quotaReached = true; setRecoveryOpen(true); refreshRecovery(); } if (!response.ok || !result.attachment) throw new Error(result.error || '上传失败,请重新选择此文件重试。'); uploaded.push(result.attachment); onNewUpload(result.attachment); onChange([...uploaded]); } catch (error) { issues.push(`${file.name}:${controller.signal.aborted ? '上传超时,请重新选择此文件重试。' : error instanceof Error ? error.message : '上传失败,请重新选择重试。'}`); if (quotaReached && index < allowed.length - 1) issues.push('本批剩余文件尚未上传,请先选用或清理未保存附件,再重新选择文件。'); setErrors([...issues]); } finally { clearTimeout(timeout); } if (quotaReached) break; } } finally { inFlight.current = false; onUploadingChange(false); setProgress(''); } } return
{!compact &&
文件附件{files.length}/{MAX_ATTACHMENTS}
}

可上传文档、图片等参考材料,每个文件不超过 20 MB,最多 10 个。保存需求后生效。

{ const selected = Array.from(event.currentTarget.files ?? []); event.currentTarget.value = ''; void upload(selected); }}/> {!compact && } {progress &&

{progress}

} {errors.length > 0 &&
    {errors.map((message, index) =>
  • {message}
  • )}
} {files.length > 0 &&
    {files.map(file =>
  • )}
}
{recoveryLoading ?

正在读取未保存附件…

: recoveryError ?
未保存附件列表加载失败:{recoveryError}
: }
{available.length > 0 &&
setRecoveryOpen(event.currentTarget.open)}>找回未保存的附件({available.length})

此前已上传但尚未保存到需求的文件,24 小时内可选用。选用后移除或取消编辑会保留原文件;“清理”会删除文件,请核对其他窗口是否仍在使用。

    {available.map(file =>
  • {file.name}{formatFileSize(file.size)}
  • )}
}

{compact ? '文档链接可在下方填写。' : '链接可继续填写在上方。'}修改已有附件后需保存;历史评审引用的文件仍会保留。

; }