fix(short-drama-agent-front): 修复资产库请求与管理流程
This commit is contained in:
1 parent
41d1cfe3ed
commit
f8b0fbb8ca
10 files changed
+672
-77
No files matched your search
@@ -27,21 +27,39 @@ const categoryPattern = /^[a-z0-9_-]+$/
|
|||||||
const query = useQuery(ref('all-project-assets'), (_, signal) => projectAssetsApi.listAll(signal))
|
const query = useQuery(ref('all-project-assets'), (_, signal) => projectAssetsApi.listAll(signal))
|
||||||
/** 上传需要列出包括尚无资产在内的全部剧本。 */
|
/** 上传需要列出包括尚无资产在内的全部剧本。 */
|
||||||
const projectsQuery = useQuery(ref('asset-project-options'), (_, signal) => projectsApi.list(signal))
|
const projectsQuery = useQuery(ref('asset-project-options'), (_, signal) => projectsApi.list(signal))
|
||||||
|
/** 当前本地搜索关键字。 */
|
||||||
const search = ref('')
|
const search = ref('')
|
||||||
|
/** 当前筛选的项目,不作为资产记录归属的替代。 */
|
||||||
const projectId = ref<string | null>(null)
|
const projectId = ref<string | null>(null)
|
||||||
|
/** 当前素材分类筛选。 */
|
||||||
const category = ref<string | null>(null)
|
const category = ref<string | null>(null)
|
||||||
const busy = ref(false)
|
/** 单一操作状态区分上传、保存与删除,避免把删除误显示为保存中。 */
|
||||||
|
const pendingAction = ref<'upload' | 'update' | 'remove' | null>(null)
|
||||||
|
/** 真实写入期间统一互斥并阻止意外关闭。 */
|
||||||
|
const busy = computed(() => pendingAction.value !== null)
|
||||||
|
/** 当前写操作的可读错误。 */
|
||||||
const actionError = ref('')
|
const actionError = ref('')
|
||||||
|
/** 本地文件校验错误。 */
|
||||||
const fileError = ref('')
|
const fileError = ref('')
|
||||||
|
/** 原生单文件选择入口。 */
|
||||||
const fileInput = ref<HTMLInputElement | null>(null)
|
const fileInput = ref<HTMLInputElement | null>(null)
|
||||||
|
/** 上传资料确认弹窗开关。 */
|
||||||
const uploadOpen = ref(false)
|
const uploadOpen = ref(false)
|
||||||
|
/** 素材详情弹窗开关。 */
|
||||||
const editOpen = ref(false)
|
const editOpen = ref(false)
|
||||||
|
/** 待用户确认上传的文件。 */
|
||||||
const selectedFile = ref<File | null>(null)
|
const selectedFile = ref<File | null>(null)
|
||||||
|
/** 当前详情对应的真实资产记录。 */
|
||||||
const selectedAsset = ref<GlobalProjectAsset | null>(null)
|
const selectedAsset = ref<GlobalProjectAsset | null>(null)
|
||||||
|
/** 仅为实际溢出的标题启用提示。 */
|
||||||
const overflowTitles = reactive(new Set<string>())
|
const overflowTitles = reactive(new Set<string>())
|
||||||
|
/** 上传归属、名称和分类表单。 */
|
||||||
const uploadForm = reactive({ projectId: '', name: '', category: 'reference' })
|
const uploadForm = reactive({ projectId: '', name: '', category: 'reference' })
|
||||||
|
/** 当前素材的可编辑展示信息。 */
|
||||||
const editForm = reactive({ name: '', category: '' })
|
const editForm = reactive({ name: '', category: '' })
|
||||||
|
/** 保留上次成功读取的素材,仅查询通过后允许写入。 */
|
||||||
const assets = computed(() => query.data.value ?? [])
|
const assets = computed(() => query.data.value ?? [])
|
||||||
|
/** 筛选仅使用资产记录中已确认的项目。 */
|
||||||
const projectOptions = computed(() => {
|
const projectOptions = computed(() => {
|
||||||
const projects = new Map<string, ProjectAssetProject>()
|
const projects = new Map<string, ProjectAssetProject>()
|
||||||
assets.value.forEach(asset => projects.set(asset.project.id, asset.project))
|
assets.value.forEach(asset => projects.set(asset.project.id, asset.project))
|
||||||
@@ -49,6 +67,7 @@ const projectOptions = computed(() => {
|
|||||||
.toSorted((a, b) => projectName(a).localeCompare(projectName(b), 'zh-CN'))
|
.toSorted((a, b) => projectName(a).localeCompare(projectName(b), 'zh-CN'))
|
||||||
.map(project => ({ label: projectName(project), value: project.id }))
|
.map(project => ({ label: projectName(project), value: project.id }))
|
||||||
})
|
})
|
||||||
|
/** 上传使用包括空资产项目在内的完整剧本列表。 */
|
||||||
const uploadProjectOptions = computed(() =>
|
const uploadProjectOptions = computed(() =>
|
||||||
(projectsQuery.data.value ?? [])
|
(projectsQuery.data.value ?? [])
|
||||||
.toSorted((a, b) => projectName(a).localeCompare(projectName(b), 'zh-CN'))
|
.toSorted((a, b) => projectName(a).localeCompare(projectName(b), 'zh-CN'))
|
||||||
@@ -61,17 +80,30 @@ const categoryOptions = computed(() =>
|
|||||||
false
|
false
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
/** 仅在本地筛选,不改写资产归属或查询结果。 */
|
||||||
const filteredAssets = computed(() => {
|
const filteredAssets = computed(() => {
|
||||||
const keyword = search.value.trim().toLowerCase()
|
const keyword = search.value.trim().toLowerCase()
|
||||||
return assets.value.filter(asset => {
|
return assets.value.filter(asset => {
|
||||||
if (projectId.value && asset.projectId !== projectId.value) return false
|
if (projectId.value && asset.projectId !== projectId.value) return false
|
||||||
if (category.value && asset.category !== category.value) return false
|
if (category.value && asset.category !== category.value) return false
|
||||||
if (!keyword) return true
|
if (!keyword) return true
|
||||||
return [asset.name, asset.category, projectName(asset.project)].some(value =>
|
return [asset.name, asset.category, categoryLabel(asset.category), projectName(asset.project)].some(value =>
|
||||||
value.toLowerCase().includes(keyword)
|
value.toLowerCase().includes(keyword)
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
/** 列表读取失败或刷新期间只保留只读浏览,暂停写入。 */
|
||||||
|
const canMutate = computed(() => !busy.value && !query.loading.value && !query.error.value && query.data.value !== null)
|
||||||
|
/** 上传还要求当前剧本选项已成功读取,不能使用失败后的旧选项。 */
|
||||||
|
const canUpload = computed(
|
||||||
|
() =>
|
||||||
|
canMutate.value &&
|
||||||
|
!projectsQuery.loading.value &&
|
||||||
|
!projectsQuery.error.value &&
|
||||||
|
!!projectsQuery.data.value &&
|
||||||
|
uploadProjectOptions.value.length > 0
|
||||||
|
)
|
||||||
|
/** 表单校验沿用正式分类与名称要求。 */
|
||||||
const formRules = {
|
const formRules = {
|
||||||
projectId: fieldRule(value => typeof value === 'string' && !!value, '请选择所属剧本'),
|
projectId: fieldRule(value => typeof value === 'string' && !!value, '请选择所属剧本'),
|
||||||
name: fieldRule(value => typeof value === 'string' && !!value.trim(), '请输入素材名称'),
|
name: fieldRule(value => typeof value === 'string' && !!value.trim(), '请输入素材名称'),
|
||||||
@@ -81,27 +113,48 @@ const formRules = {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 选择剧本展示名称,不改写正式主题。
|
||||||
|
* @param project 剧本最小摘要
|
||||||
|
* @returns 可读名称
|
||||||
|
*/
|
||||||
function projectName(project: Pick<ProjectAssetProject, 'title' | 'topic'>) {
|
function projectName(project: Pick<ProjectAssetProject, 'title' | 'topic'>) {
|
||||||
return project.title?.trim() || project.topic
|
return project.title?.trim() || project.topic
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 展示文件大小。
|
||||||
|
* @param value 文件字节数
|
||||||
|
* @returns 可读大小
|
||||||
|
*/
|
||||||
function formatBytes(value: number) {
|
function formatBytes(value: number) {
|
||||||
if (value < 1024) return `${value} B`
|
if (value < 1024) return `${value} B`
|
||||||
if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`
|
if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`
|
||||||
return `${(value / 1024 / 1024).toFixed(1)} MB`
|
return `${(value / 1024 / 1024).toFixed(1)} MB`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 展示素材时间,无效值保留原始文本。
|
||||||
|
* @param value 接口时间文本
|
||||||
|
* @returns 本地化时间
|
||||||
|
*/
|
||||||
function formatDate(value: string) {
|
function formatDate(value: string) {
|
||||||
const date = new Date(value)
|
const date = new Date(value)
|
||||||
return Number.isNaN(date.getTime()) ? value : date.toLocaleString('zh-CN', { hour12: false })
|
return Number.isNaN(date.getTime()) ? value : date.toLocaleString('zh-CN', { hour12: false })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 只读取可展示的原文件名。
|
||||||
|
* @param value 不透明元数据
|
||||||
|
* @returns 原始文件名或缺省说明
|
||||||
|
*/
|
||||||
function metadataOriginalName(value: unknown) {
|
function metadataOriginalName(value: unknown) {
|
||||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return '未记录'
|
if (!value || typeof value !== 'object' || Array.isArray(value)) return '未记录'
|
||||||
const originalName = (value as Record<string, unknown>).originalName
|
const originalName = (value as Record<string, unknown>).originalName
|
||||||
return typeof originalName === 'string' && originalName.trim() ? originalName : '未记录'
|
return typeof originalName === 'string' && originalName.trim() ? originalName : '未记录'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 清除本地筛选,不写入资产。 */
|
||||||
function clearFilters() {
|
function clearFilters() {
|
||||||
search.value = ''
|
search.value = ''
|
||||||
projectId.value = null
|
projectId.value = null
|
||||||
@@ -115,7 +168,7 @@ function selectFile(event: Event) {
|
|||||||
input.value = ''
|
input.value = ''
|
||||||
fileError.value = ''
|
fileError.value = ''
|
||||||
actionError.value = ''
|
actionError.value = ''
|
||||||
if (!file) return
|
if (!file || !canUpload.value) return
|
||||||
if (!ACCEPTED_TYPES.has(file.type)) {
|
if (!ACCEPTED_TYPES.has(file.type)) {
|
||||||
fileError.value = '仅支持 JPEG、PNG、WebP 图片。'
|
fileError.value = '仅支持 JPEG、PNG、WebP 图片。'
|
||||||
return
|
return
|
||||||
@@ -125,16 +178,24 @@ function selectFile(event: Event) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
selectedFile.value = file
|
selectedFile.value = file
|
||||||
uploadForm.projectId = projectId.value ?? ''
|
uploadForm.projectId = uploadProjectOptions.value.some(project => project.value === projectId.value)
|
||||||
|
? projectId.value!
|
||||||
|
: ''
|
||||||
uploadForm.name = file.name.replace(/\.[^.]+$/, '') || file.name
|
uploadForm.name = file.name.replace(/\.[^.]+$/, '') || file.name
|
||||||
uploadForm.category = 'reference'
|
uploadForm.category = 'reference'
|
||||||
uploadOpen.value = true
|
uploadOpen.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 仅在列表和归属选项有效时上传所选文件。 */
|
||||||
async function uploadAsset() {
|
async function uploadAsset() {
|
||||||
const file = selectedFile.value
|
const file = selectedFile.value
|
||||||
if (!file || busy.value) return
|
if (
|
||||||
busy.value = true
|
!file ||
|
||||||
|
!canUpload.value ||
|
||||||
|
!uploadProjectOptions.value.some(project => project.value === uploadForm.projectId)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
pendingAction.value = 'upload'
|
||||||
actionError.value = ''
|
actionError.value = ''
|
||||||
try {
|
try {
|
||||||
await projectAssetsApi.upload(uploadForm.projectId, {
|
await projectAssetsApi.upload(uploadForm.projectId, {
|
||||||
@@ -148,10 +209,14 @@ async function uploadAsset() {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
actionError.value = errorMessage(error)
|
actionError.value = errorMessage(error)
|
||||||
} finally {
|
} finally {
|
||||||
busy.value = false
|
pendingAction.value = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打开已有资产详情;失联时仍可只读查看。
|
||||||
|
* @param asset 用户选择的正式资产
|
||||||
|
*/
|
||||||
function openEdit(asset: GlobalProjectAsset) {
|
function openEdit(asset: GlobalProjectAsset) {
|
||||||
selectedAsset.value = asset
|
selectedAsset.value = asset
|
||||||
editForm.name = asset.name
|
editForm.name = asset.name
|
||||||
@@ -167,10 +232,11 @@ function checkTitleOverflow(assetId: string, event: MouseEvent) {
|
|||||||
else overflowTitles.delete(assetId)
|
else overflowTitles.delete(assetId)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 当前素材列表有效时保存名称和分类。 */
|
||||||
async function updateAsset() {
|
async function updateAsset() {
|
||||||
const asset = selectedAsset.value
|
const asset = selectedAsset.value
|
||||||
if (!asset || busy.value) return
|
if (!asset || !canMutate.value) return
|
||||||
busy.value = true
|
pendingAction.value = 'update'
|
||||||
actionError.value = ''
|
actionError.value = ''
|
||||||
try {
|
try {
|
||||||
await projectAssetsApi.update(asset.projectId, asset.id, {
|
await projectAssetsApi.update(asset.projectId, asset.id, {
|
||||||
@@ -183,14 +249,15 @@ async function updateAsset() {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
actionError.value = errorMessage(error)
|
actionError.value = errorMessage(error)
|
||||||
} finally {
|
} finally {
|
||||||
busy.value = false
|
pendingAction.value = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 当前素材列表有效时明确删除,引用冲突保留弹窗与原数据。 */
|
||||||
async function removeAsset() {
|
async function removeAsset() {
|
||||||
const asset = selectedAsset.value
|
const asset = selectedAsset.value
|
||||||
if (!asset || busy.value) return
|
if (!asset || !canMutate.value) return
|
||||||
busy.value = true
|
pendingAction.value = 'remove'
|
||||||
actionError.value = ''
|
actionError.value = ''
|
||||||
try {
|
try {
|
||||||
await projectAssetsApi.remove(asset.projectId, asset.id)
|
await projectAssetsApi.remove(asset.projectId, asset.id)
|
||||||
@@ -200,9 +267,13 @@ async function removeAsset() {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
actionError.value = errorMessage(error)
|
actionError.value = errorMessage(error)
|
||||||
} finally {
|
} finally {
|
||||||
busy.value = false
|
pendingAction.value = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/** 连接恢复时同时刷新资产与剧本选项;只重试读取,不重发上传或编辑。 */
|
||||||
|
async function refreshLibrary() {
|
||||||
|
await Promise.all([query.refresh(), projectsQuery.refresh()])
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -211,7 +282,7 @@ async function removeAsset() {
|
|||||||
<div class="page-heading asset-library-heading">
|
<div class="page-heading asset-library-heading">
|
||||||
<div>
|
<div>
|
||||||
<h1>资产库</h1>
|
<h1>资产库</h1>
|
||||||
<p class="page-description">汇总并管理所有剧本的人物、场景、道具和参考图片。</p>
|
<p class="page-description">集中管理各剧本上传的人物、场景、道具和参考图片。</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex items-center gap-2">
|
||||||
<input
|
<input
|
||||||
@@ -222,26 +293,32 @@ async function removeAsset() {
|
|||||||
aria-label="选择全局资产图片"
|
aria-label="选择全局资产图片"
|
||||||
@change="selectFile"
|
@change="selectFile"
|
||||||
/>
|
/>
|
||||||
<NButton
|
<NButton type="primary" :disabled="!canUpload" @click="fileInput?.click()">
|
||||||
type="primary"
|
|
||||||
:disabled="busy || !uploadProjectOptions.length"
|
|
||||||
@click="fileInput?.click()"
|
|
||||||
>
|
|
||||||
<template #icon><Upload :size="16" /></template>上传图片
|
<template #icon><Upload :size="16" /></template>上传图片
|
||||||
</NButton>
|
</NButton>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<!-- 以下是文件校验与连接恢复模块 -->
|
||||||
<FeedbackMessage v-if="fileError" :message="fileError" />
|
<FeedbackMessage v-if="fileError" :message="fileError" />
|
||||||
<ContextNotice v-if="query.error.value" type="error" :show-icon="false" class="mb-4">
|
<ContextNotice v-if="query.error.value" type="error" :show-icon="false" class="mb-4">
|
||||||
{{ query.error.value }}<NButton text class="ml-3" @click="query.refresh">重新连接</NButton>
|
{{ query.error.value }}
|
||||||
|
<span v-if="query.data.value">当前保留上次成功读取的素材,写操作已暂停。</span>
|
||||||
|
<NButton
|
||||||
|
text
|
||||||
|
class="ml-3"
|
||||||
|
:loading="query.loading.value || projectsQuery.loading.value"
|
||||||
|
@click="refreshLibrary"
|
||||||
|
>重新连接</NButton
|
||||||
|
>
|
||||||
</ContextNotice>
|
</ContextNotice>
|
||||||
<ContextNotice v-if="projectsQuery.error.value" type="warning" :show-icon="false" class="mb-4">
|
<ContextNotice v-if="projectsQuery.error.value" type="warning" :show-icon="false" class="mb-4">
|
||||||
剧本列表读取失败,暂时不能上传新图片。
|
剧本列表读取失败,暂时不能上传新图片。
|
||||||
<NButton text class="ml-3" @click="projectsQuery.refresh">重新读取</NButton>
|
<NButton text class="ml-3" @click="projectsQuery.refresh">重新读取</NButton>
|
||||||
</ContextNotice>
|
</ContextNotice>
|
||||||
|
|
||||||
|
<!-- 以下是本地搜索与分类筛选模块 -->
|
||||||
<div class="asset-library-filters">
|
<div class="asset-library-filters">
|
||||||
<NInput
|
<NInput
|
||||||
v-model:value="search"
|
v-model:value="search"
|
||||||
@@ -269,6 +346,7 @@ async function removeAsset() {
|
|||||||
<span class="text-xs text-muted">{{ filteredAssets.length }} / {{ assets.length }} 张</span>
|
<span class="text-xs text-muted">{{ filteredAssets.length }} / {{ assets.length }} 张</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 以下是素材图库与空态模块 -->
|
||||||
<div v-if="filteredAssets.length" class="asset-library-grid">
|
<div v-if="filteredAssets.length" class="asset-library-grid">
|
||||||
<article
|
<article
|
||||||
v-for="asset in filteredAssets"
|
v-for="asset in filteredAssets"
|
||||||
@@ -309,12 +387,13 @@ async function removeAsset() {
|
|||||||
:description="assets.length ? '调整搜索、剧本或分类筛选。' : '选择剧本并上传第一张图片。'"
|
:description="assets.length ? '调整搜索、剧本或分类筛选。' : '选择剧本并上传第一张图片。'"
|
||||||
>
|
>
|
||||||
<NButton v-if="assets.length" @click="clearFilters">清除筛选</NButton>
|
<NButton v-if="assets.length" @click="clearFilters">清除筛选</NButton>
|
||||||
<NButton v-else type="primary" :disabled="!uploadProjectOptions.length" @click="fileInput?.click()">
|
<NButton v-else type="primary" :disabled="!canUpload" @click="fileInput?.click()"> 上传第一张图片 </NButton>
|
||||||
上传第一张图片
|
|
||||||
</NButton>
|
|
||||||
</EmptyState>
|
</EmptyState>
|
||||||
<p v-else class="py-10 text-center text-sm text-muted" role="status">正在读取全部资产图片…</p>
|
<p v-else-if="query.loading.value" class="py-10 text-center text-sm text-muted" role="status">
|
||||||
|
正在读取全部资产图片…
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<!-- 以下是上传资料确认模块 -->
|
||||||
<AppDialog
|
<AppDialog
|
||||||
v-model:open="uploadOpen"
|
v-model:open="uploadOpen"
|
||||||
title="上传资产图片"
|
title="上传资产图片"
|
||||||
@@ -326,7 +405,7 @@ async function removeAsset() {
|
|||||||
id="library-upload-form"
|
id="library-upload-form"
|
||||||
:model="uploadForm"
|
:model="uploadForm"
|
||||||
:rules="formRules"
|
:rules="formRules"
|
||||||
:disabled="busy"
|
:disabled="!canUpload"
|
||||||
class="mt-5"
|
class="mt-5"
|
||||||
@submit="uploadAsset"
|
@submit="uploadAsset"
|
||||||
>
|
>
|
||||||
@@ -345,10 +424,18 @@ async function removeAsset() {
|
|||||||
</AppForm>
|
</AppForm>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<NButton :disabled="busy" @click="uploadOpen = false">取消</NButton>
|
<NButton :disabled="busy" @click="uploadOpen = false">取消</NButton>
|
||||||
<NButton type="primary" attr-type="submit" form="library-upload-form" :loading="busy">确认上传</NButton>
|
<NButton
|
||||||
|
type="primary"
|
||||||
|
attr-type="submit"
|
||||||
|
form="library-upload-form"
|
||||||
|
:disabled="!canUpload"
|
||||||
|
:loading="pendingAction === 'upload'"
|
||||||
|
>确认上传</NButton
|
||||||
|
>
|
||||||
</template>
|
</template>
|
||||||
</AppDialog>
|
</AppDialog>
|
||||||
|
|
||||||
|
<!-- 以下是素材详情与管理模块 -->
|
||||||
<AppDialog
|
<AppDialog
|
||||||
v-model:open="editOpen"
|
v-model:open="editOpen"
|
||||||
title="素材详情与管理"
|
title="素材详情与管理"
|
||||||
@@ -361,7 +448,7 @@ async function removeAsset() {
|
|||||||
id="library-edit-form"
|
id="library-edit-form"
|
||||||
:model="editForm"
|
:model="editForm"
|
||||||
:rules="formRules"
|
:rules="formRules"
|
||||||
:disabled="busy"
|
:disabled="!canMutate"
|
||||||
class="mt-5"
|
class="mt-5"
|
||||||
@submit="updateAsset"
|
@submit="updateAsset"
|
||||||
>
|
>
|
||||||
@@ -405,13 +492,14 @@ async function removeAsset() {
|
|||||||
<template #footer>
|
<template #footer>
|
||||||
<div class="asset-management-footer">
|
<div class="asset-management-footer">
|
||||||
<NPopconfirm
|
<NPopconfirm
|
||||||
:positive-button-props="{ disabled: busy }"
|
:positive-button-props="{ disabled: !canMutate, loading: pendingAction === 'remove' }"
|
||||||
|
:negative-button-props="{ disabled: busy }"
|
||||||
positive-text="确认删除"
|
positive-text="确认删除"
|
||||||
negative-text="取消"
|
negative-text="取消"
|
||||||
@positive-click="removeAsset"
|
@positive-click="removeAsset"
|
||||||
>
|
>
|
||||||
<template #trigger>
|
<template #trigger>
|
||||||
<NButton class="text-danger" :disabled="busy">
|
<NButton class="text-danger" :disabled="!canMutate" :loading="pendingAction === 'remove'">
|
||||||
<template #icon><Trash2 :size="14" /></template>删除素材
|
<template #icon><Trash2 :size="14" /></template>删除素材
|
||||||
</NButton>
|
</NButton>
|
||||||
</template>
|
</template>
|
||||||
@@ -419,7 +507,12 @@ async function removeAsset() {
|
|||||||
</NPopconfirm>
|
</NPopconfirm>
|
||||||
<div class="ml-auto flex gap-2">
|
<div class="ml-auto flex gap-2">
|
||||||
<NButton :disabled="busy" @click="editOpen = false">取消</NButton>
|
<NButton :disabled="busy" @click="editOpen = false">取消</NButton>
|
||||||
<NButton type="primary" attr-type="submit" form="library-edit-form" :loading="busy"
|
<NButton
|
||||||
|
type="primary"
|
||||||
|
attr-type="submit"
|
||||||
|
form="library-edit-form"
|
||||||
|
:disabled="!canMutate"
|
||||||
|
:loading="pendingAction === 'update'"
|
||||||
>保存修改</NButton
|
>保存修改</NButton
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import FeedbackMessage from '../../components/ui/FeedbackMessage.vue'
|
|||||||
|
|
||||||
import ContextNotice from '../../components/ui/ContextNotice.vue'
|
import ContextNotice from '../../components/ui/ContextNotice.vue'
|
||||||
|
|
||||||
import { computed, reactive, ref } from 'vue'
|
import { computed, reactive, ref, watch } from 'vue'
|
||||||
import { NButton, NFormItem, NInput, NPopconfirm, NSelect, NTag } from 'naive-ui'
|
import { NButton, NFormItem, NInput, NPopconfirm, NSelect, NTag } from 'naive-ui'
|
||||||
import { Pencil, Search, Trash2, Upload } from '@lucide/vue'
|
import { Pencil, Search, Trash2, Upload } from '@lucide/vue'
|
||||||
import { AppDialog, AssetImage, EmptyState } from '../../components/ui'
|
import { AppDialog, AssetImage, EmptyState } from '../../components/ui'
|
||||||
@@ -23,37 +23,53 @@ const ACCEPTED_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp'])
|
|||||||
const MAX_FILE_SIZE = 20 * 1024 * 1024
|
const MAX_FILE_SIZE = 20 * 1024 * 1024
|
||||||
const categoryPattern = /^[a-z0-9_-]+$/
|
const categoryPattern = /^[a-z0-9_-]+$/
|
||||||
|
|
||||||
const { projectId, blocked } = useProjectMutationGuard()
|
/** 沿用项目当前的编辑准入和活动操作约束。 */
|
||||||
|
const { projectId, blocked, operation } = useProjectMutationGuard()
|
||||||
|
/** API边界统一校验列表结构及项目归属,切换时取消旧读取。 */
|
||||||
const query = useQuery(projectId, async (id, signal) => {
|
const query = useQuery(projectId, async (id, signal) => {
|
||||||
const assets = await projectAssetsApi.list(id, signal)
|
return projectAssetsApi.list(id, signal)
|
||||||
if (assets.some(asset => asset.projectId !== id)) throw new Error('素材列表包含其它项目的数据,请刷新后重试。')
|
|
||||||
return assets
|
|
||||||
})
|
})
|
||||||
|
/** 当前项目最近一次成功读取的素材。 */
|
||||||
const assets = computed(() => query.data.value ?? [])
|
const assets = computed(() => query.data.value ?? [])
|
||||||
const disabled = computed(() => blocked.value || !!query.error.value || !query.data.value)
|
/** 只有实际写任务进行中才显示提交loading并暂时锁住关闭。 */
|
||||||
|
const mutationPending = computed(() => operation.value.pending)
|
||||||
|
/** 读取未就绪、失败或项目被锁时暂停写入。 */
|
||||||
|
const disabled = computed(() => blocked.value || query.loading.value || !!query.error.value || !query.data.value)
|
||||||
|
/** 项目内本地搜索文本。 */
|
||||||
const search = ref('')
|
const search = ref('')
|
||||||
|
/** 当前素材分类筛选。 */
|
||||||
const category = ref<string | null>(null)
|
const category = ref<string | null>(null)
|
||||||
|
/** 单文件选择入口。 */
|
||||||
const fileInput = ref<HTMLInputElement | null>(null)
|
const fileInput = ref<HTMLInputElement | null>(null)
|
||||||
|
/** 上传确认弹窗开关。 */
|
||||||
const uploadOpen = ref(false)
|
const uploadOpen = ref(false)
|
||||||
|
/** 编辑素材弹窗开关。 */
|
||||||
const editOpen = ref(false)
|
const editOpen = ref(false)
|
||||||
|
/** 当前待确认的文件。 */
|
||||||
const selectedFile = ref<File | null>(null)
|
const selectedFile = ref<File | null>(null)
|
||||||
|
/** 当前项目已选中的正式素材。 */
|
||||||
const selectedAsset = ref<ProjectAsset | null>(null)
|
const selectedAsset = ref<ProjectAsset | null>(null)
|
||||||
|
/** 本地文件格式与大小校验错误。 */
|
||||||
const fileError = ref('')
|
const fileError = ref('')
|
||||||
|
/** 上传名称与分类草稿。 */
|
||||||
const uploadForm = reactive({ name: '', category: 'reference' })
|
const uploadForm = reactive({ name: '', category: 'reference' })
|
||||||
|
/** 当前素材名称与分类草稿。 */
|
||||||
const editForm = reactive({ name: '', category: '' })
|
const editForm = reactive({ name: '', category: '' })
|
||||||
|
|
||||||
/** 项目筛选复用中文分类映射,兼容已有自定义分类。 */
|
/** 项目筛选复用中文分类映射,兼容已有自定义分类。 */
|
||||||
const categoryOptions = computed(() => assetCategoryOptions(assets.value.map(asset => asset.category)))
|
const categoryOptions = computed(() => assetCategoryOptions(assets.value.map(asset => asset.category)))
|
||||||
|
/** 匹配名称、中文分类及原文件名,不改变资产数据。 */
|
||||||
const filteredAssets = computed(() => {
|
const filteredAssets = computed(() => {
|
||||||
const keyword = search.value.trim().toLowerCase()
|
const keyword = search.value.trim().toLowerCase()
|
||||||
return assets.value.filter(asset => {
|
return assets.value.filter(asset => {
|
||||||
if (category.value && asset.category !== category.value) return false
|
if (category.value && asset.category !== category.value) return false
|
||||||
if (!keyword) return true
|
if (!keyword) return true
|
||||||
return [asset.name, asset.category, metadataOriginalName(asset.metadata)].some(value =>
|
return [asset.name, asset.category, categoryLabel(asset.category), metadataOriginalName(asset.metadata)].some(
|
||||||
value.toLowerCase().includes(keyword)
|
value => value.toLowerCase().includes(keyword)
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
/** 素材名称和分类的提交校验规则。 */
|
||||||
const formRules = {
|
const formRules = {
|
||||||
name: fieldRule(value => typeof value === 'string' && !!value.trim(), '请输入素材名称'),
|
name: fieldRule(value => typeof value === 'string' && !!value.trim(), '请输入素材名称'),
|
||||||
category: fieldRule(
|
category: fieldRule(
|
||||||
@@ -62,23 +78,39 @@ const formRules = {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从不透明元数据中读取原始文件名。
|
||||||
|
* @param value 正式素材元数据
|
||||||
|
* @returns 原文件名,未知时为空
|
||||||
|
*/
|
||||||
function metadataOriginalName(value: unknown) {
|
function metadataOriginalName(value: unknown) {
|
||||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return ''
|
if (!value || typeof value !== 'object' || Array.isArray(value)) return ''
|
||||||
const originalName = (value as Record<string, unknown>).originalName
|
const originalName = (value as Record<string, unknown>).originalName
|
||||||
return typeof originalName === 'string' ? originalName : ''
|
return typeof originalName === 'string' ? originalName : ''
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化文件大小。
|
||||||
|
* @param value 字节数
|
||||||
|
* @returns 可读大小
|
||||||
|
*/
|
||||||
function formatBytes(value: number) {
|
function formatBytes(value: number) {
|
||||||
if (value < 1024) return `${value} B`
|
if (value < 1024) return `${value} B`
|
||||||
if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`
|
if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`
|
||||||
return `${(value / 1024 / 1024).toFixed(1)} MB`
|
return `${(value / 1024 / 1024).toFixed(1)} MB`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化素材时间。
|
||||||
|
* @param value 原始时间
|
||||||
|
* @returns 本地化文本
|
||||||
|
*/
|
||||||
function formatDate(value: string) {
|
function formatDate(value: string) {
|
||||||
const date = new Date(value)
|
const date = new Date(value)
|
||||||
return Number.isNaN(date.getTime()) ? value : date.toLocaleString('zh-CN', { hour12: false })
|
return Number.isNaN(date.getTime()) ? value : date.toLocaleString('zh-CN', { hour12: false })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 清除当前项目的本地筛选。 */
|
||||||
function clearFilters() {
|
function clearFilters() {
|
||||||
search.value = ''
|
search.value = ''
|
||||||
category.value = null
|
category.value = null
|
||||||
@@ -105,17 +137,17 @@ function selectFile(event: Event) {
|
|||||||
uploadOpen.value = true
|
uploadOpen.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 仅提交当前确认文件一次,并由API统一核对结果。 */
|
||||||
async function uploadAsset() {
|
async function uploadAsset() {
|
||||||
const file = selectedFile.value
|
const file = selectedFile.value
|
||||||
if (!file || disabled.value) return
|
if (!file || disabled.value) return
|
||||||
const id = projectId.value
|
const id = projectId.value
|
||||||
const ok = await runOperation(id, '上传项目素材', async () => {
|
const ok = await runOperation(id, '上传项目素材', async () => {
|
||||||
const asset = await projectAssetsApi.upload(id, {
|
await projectAssetsApi.upload(id, {
|
||||||
file,
|
file,
|
||||||
name: uploadForm.name.trim(),
|
name: uploadForm.name.trim(),
|
||||||
category: uploadForm.category.trim()
|
category: uploadForm.category.trim()
|
||||||
})
|
})
|
||||||
if (!asset || asset.projectId !== id) throw new Error('未取得当前剧本的素材记录,请刷新后核对。')
|
|
||||||
})
|
})
|
||||||
if (!ok || projectId.value !== id) return
|
if (!ok || projectId.value !== id) return
|
||||||
uploadOpen.value = false
|
uploadOpen.value = false
|
||||||
@@ -123,6 +155,10 @@ async function uploadAsset() {
|
|||||||
await query.refresh()
|
await query.refresh()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 编辑当前项目的素材草稿。
|
||||||
|
* @param asset 已选择的正式素材
|
||||||
|
*/
|
||||||
function openEdit(asset: ProjectAsset) {
|
function openEdit(asset: ProjectAsset) {
|
||||||
selectedAsset.value = asset
|
selectedAsset.value = asset
|
||||||
editForm.name = asset.name
|
editForm.name = asset.name
|
||||||
@@ -130,17 +166,16 @@ function openEdit(asset: ProjectAsset) {
|
|||||||
editOpen.value = true
|
editOpen.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 保存当前素材草稿,项目切换后不回填旧响应。 */
|
||||||
async function updateAsset() {
|
async function updateAsset() {
|
||||||
const asset = selectedAsset.value
|
const asset = selectedAsset.value
|
||||||
if (!asset || disabled.value) return
|
if (!asset || disabled.value) return
|
||||||
const id = projectId.value
|
const id = projectId.value
|
||||||
const ok = await runOperation(id, '更新项目素材', async () => {
|
const ok = await runOperation(id, '更新项目素材', async () => {
|
||||||
const result = await projectAssetsApi.update(id, asset.id, {
|
await projectAssetsApi.update(id, asset.id, {
|
||||||
name: editForm.name.trim(),
|
name: editForm.name.trim(),
|
||||||
category: editForm.category.trim()
|
category: editForm.category.trim()
|
||||||
})
|
})
|
||||||
if (!result || result.id !== asset.id || result.projectId !== id)
|
|
||||||
throw new Error('素材更新结果尚未确认,请刷新后核对。')
|
|
||||||
})
|
})
|
||||||
if (!ok || projectId.value !== id) return
|
if (!ok || projectId.value !== id) return
|
||||||
editOpen.value = false
|
editOpen.value = false
|
||||||
@@ -148,16 +183,28 @@ async function updateAsset() {
|
|||||||
await query.refresh()
|
await query.refresh()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 明确删除当前项目素材,项目切换后不刷新新项目。
|
||||||
|
* @param asset 当前列表中选择的素材
|
||||||
|
*/
|
||||||
async function removeAsset(asset: ProjectAsset) {
|
async function removeAsset(asset: ProjectAsset) {
|
||||||
if (disabled.value) return
|
if (disabled.value) return
|
||||||
const id = projectId.value
|
const id = projectId.value
|
||||||
const ok = await runOperation(id, '删除项目素材', async () => {
|
const ok = await runOperation(id, '删除项目素材', async () => {
|
||||||
const result = await projectAssetsApi.remove(id, asset.id)
|
await projectAssetsApi.remove(id, asset.id)
|
||||||
if (!result || result.id !== asset.id || result.projectId !== id)
|
|
||||||
throw new Error('素材删除结果尚未确认,请刷新后核对。')
|
|
||||||
})
|
})
|
||||||
if (ok && projectId.value === id) await query.refresh()
|
if (ok && projectId.value === id) await query.refresh()
|
||||||
}
|
}
|
||||||
|
/** 切项目后清除旧文件和编辑草稿,不让旧弹窗继续操作新项目。 */
|
||||||
|
watch(projectId, () => {
|
||||||
|
uploadOpen.value = false
|
||||||
|
editOpen.value = false
|
||||||
|
selectedFile.value = null
|
||||||
|
selectedAsset.value = null
|
||||||
|
fileError.value = ''
|
||||||
|
search.value = ''
|
||||||
|
category.value = null
|
||||||
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -184,11 +231,14 @@ async function removeAsset(asset: ProjectAsset) {
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<!-- 以下是文件校验与查询恢复模块 -->
|
||||||
<FeedbackMessage v-if="fileError" :message="fileError" />
|
<FeedbackMessage v-if="fileError" :message="fileError" />
|
||||||
<ContextNotice v-if="query.error.value" type="error" :show-icon="false" class="mb-3">
|
<ContextNotice v-if="query.error.value" type="error" :show-icon="false" class="mb-3">
|
||||||
{{ query.error.value }} 当前保留上次成功读取的素材,写操作已暂停。
|
{{ query.error.value }} 当前保留上次成功读取的素材,写操作已暂停。
|
||||||
|
<NButton text :loading="query.loading.value" @click="query.refresh">重新读取</NButton>
|
||||||
</ContextNotice>
|
</ContextNotice>
|
||||||
|
|
||||||
|
<!-- 以下是当前项目的搜索与分类筛选模块 -->
|
||||||
<div class="asset-filter-bar">
|
<div class="asset-filter-bar">
|
||||||
<NInput
|
<NInput
|
||||||
v-model:value="search"
|
v-model:value="search"
|
||||||
@@ -208,6 +258,7 @@ async function removeAsset(asset: ProjectAsset) {
|
|||||||
<span class="text-xs text-muted">{{ filteredAssets.length }} / {{ assets.length }} 项</span>
|
<span class="text-xs text-muted">{{ filteredAssets.length }} / {{ assets.length }} 项</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 以下是当前项目素材与空态模块 -->
|
||||||
<div v-if="filteredAssets.length" class="project-asset-grid">
|
<div v-if="filteredAssets.length" class="project-asset-grid">
|
||||||
<article v-for="asset in filteredAssets" :key="asset.id" class="project-asset-card">
|
<article v-for="asset in filteredAssets" :key="asset.id" class="project-asset-card">
|
||||||
<AssetImage :src="asset.publicUrl" :alt="asset.name" preview class="project-asset-image" />
|
<AssetImage :src="asset.publicUrl" :alt="asset.name" preview class="project-asset-image" />
|
||||||
@@ -254,19 +305,22 @@ async function removeAsset(asset: ProjectAsset) {
|
|||||||
<NButton v-if="assets.length" @click="clearFilters">清除筛选</NButton>
|
<NButton v-if="assets.length" @click="clearFilters">清除筛选</NButton>
|
||||||
<NButton v-else type="primary" :disabled="disabled" @click="fileInput?.click()">上传第一张图片</NButton>
|
<NButton v-else type="primary" :disabled="disabled" @click="fileInput?.click()">上传第一张图片</NButton>
|
||||||
</EmptyState>
|
</EmptyState>
|
||||||
<p v-else class="py-10 text-center text-sm text-muted" role="status">正在读取项目素材…</p>
|
<p v-else-if="query.loading.value" class="py-10 text-center text-sm text-muted" role="status">
|
||||||
|
正在读取项目素材…
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<!-- 以下是单文件上传确认模块 -->
|
||||||
<AppDialog
|
<AppDialog
|
||||||
v-model:open="uploadOpen"
|
v-model:open="uploadOpen"
|
||||||
title="上传项目素材"
|
title="上传项目素材"
|
||||||
description="填写名称并选择分类,方便之后查找和使用这张图片。"
|
description="填写名称并选择分类,方便之后查找和使用这张图片。"
|
||||||
:busy="blocked"
|
:busy="mutationPending"
|
||||||
>
|
>
|
||||||
<AppForm
|
<AppForm
|
||||||
id="project-upload-form"
|
id="project-upload-form"
|
||||||
:model="uploadForm"
|
:model="uploadForm"
|
||||||
:rules="formRules"
|
:rules="formRules"
|
||||||
:disabled="blocked"
|
:disabled="disabled"
|
||||||
class="mt-5"
|
class="mt-5"
|
||||||
@submit="uploadAsset"
|
@submit="uploadAsset"
|
||||||
>
|
>
|
||||||
@@ -276,29 +330,35 @@ async function removeAsset(asset: ProjectAsset) {
|
|||||||
<AssetCategorySelect
|
<AssetCategorySelect
|
||||||
v-model:value="uploadForm.category"
|
v-model:value="uploadForm.category"
|
||||||
:categories="assets.map(asset => asset.category)"
|
:categories="assets.map(asset => asset.category)"
|
||||||
:disabled="blocked"
|
:disabled="disabled"
|
||||||
/>
|
/>
|
||||||
</NFormItem>
|
</NFormItem>
|
||||||
</AppForm>
|
</AppForm>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<NButton :disabled="blocked" @click="uploadOpen = false">取消</NButton>
|
<NButton :disabled="mutationPending" @click="uploadOpen = false">取消</NButton>
|
||||||
<NButton type="primary" attr-type="submit" form="project-upload-form" :loading="blocked"
|
<NButton
|
||||||
|
type="primary"
|
||||||
|
attr-type="submit"
|
||||||
|
form="project-upload-form"
|
||||||
|
:disabled="disabled"
|
||||||
|
:loading="mutationPending"
|
||||||
>确认上传</NButton
|
>确认上传</NButton
|
||||||
>
|
>
|
||||||
</template>
|
</template>
|
||||||
</AppDialog>
|
</AppDialog>
|
||||||
|
|
||||||
|
<!-- 以下是当前素材编辑模块 -->
|
||||||
<AppDialog
|
<AppDialog
|
||||||
v-model:open="editOpen"
|
v-model:open="editOpen"
|
||||||
title="编辑素材信息"
|
title="编辑素材信息"
|
||||||
description="只修改名称和分类,不会替换图片文件或修改已保存的引用地址。"
|
description="只修改名称和分类,不会替换图片文件或修改已保存的引用地址。"
|
||||||
:busy="blocked"
|
:busy="mutationPending"
|
||||||
>
|
>
|
||||||
<AppForm
|
<AppForm
|
||||||
id="project-edit-form"
|
id="project-edit-form"
|
||||||
:model="editForm"
|
:model="editForm"
|
||||||
:rules="formRules"
|
:rules="formRules"
|
||||||
:disabled="blocked"
|
:disabled="disabled"
|
||||||
class="mt-5"
|
class="mt-5"
|
||||||
@submit="updateAsset"
|
@submit="updateAsset"
|
||||||
>
|
>
|
||||||
@@ -307,12 +367,17 @@ async function removeAsset(asset: ProjectAsset) {
|
|||||||
><AssetCategorySelect
|
><AssetCategorySelect
|
||||||
v-model:value="editForm.category"
|
v-model:value="editForm.category"
|
||||||
:categories="assets.map(asset => asset.category)"
|
:categories="assets.map(asset => asset.category)"
|
||||||
:disabled="blocked"
|
:disabled="disabled"
|
||||||
/></NFormItem>
|
/></NFormItem>
|
||||||
</AppForm>
|
</AppForm>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<NButton :disabled="blocked" @click="editOpen = false">取消</NButton>
|
<NButton :disabled="mutationPending" @click="editOpen = false">取消</NButton>
|
||||||
<NButton type="primary" attr-type="submit" form="project-edit-form" :loading="blocked"
|
<NButton
|
||||||
|
type="primary"
|
||||||
|
attr-type="submit"
|
||||||
|
form="project-edit-form"
|
||||||
|
:disabled="disabled"
|
||||||
|
:loading="mutationPending"
|
||||||
>保存修改</NButton
|
>保存修改</NButton
|
||||||
>
|
>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -9,19 +9,147 @@ function assetPath(projectId: string, assetId?: string) {
|
|||||||
|
|
||||||
/** 项目素材 API;上传使用 multipart,浏览和编辑不调用生成模型。 */
|
/** 项目素材 API;上传使用 multipart,浏览和编辑不调用生成模型。 */
|
||||||
export const projectAssetsApi = {
|
export const projectAssetsApi = {
|
||||||
listAll: (signal?: AbortSignal) => request<GlobalProjectAsset[]>('/assets', { signal }),
|
/**
|
||||||
list: (projectId: string, signal?: AbortSignal) => request<ProjectAsset[]>(assetPath(projectId), { signal }),
|
* 读取全局素材,拒绝空协议数据和缺少项目归属的记录。
|
||||||
get: (projectId: string, assetId: string, signal?: AbortSignal) =>
|
* @param signal 页面查询取消信号
|
||||||
request<ProjectAsset>(assetPath(projectId, assetId), { signal }),
|
* @returns 所有素材及最小项目摘要
|
||||||
upload: (projectId: string, input: UploadProjectAssetInput) => {
|
*/
|
||||||
|
async listAll(signal?: AbortSignal) {
|
||||||
|
const rows = await request<GlobalProjectAsset[]>('/assets', { signal })
|
||||||
|
assertAssetList(rows, undefined, true)
|
||||||
|
return rows
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* 读取指定项目素材,归属检查由API边界统一执行。
|
||||||
|
* @param projectId 当前项目
|
||||||
|
* @param signal 页面查询取消信号
|
||||||
|
* @returns 当前项目素材列表
|
||||||
|
*/
|
||||||
|
async list(projectId: string, signal?: AbortSignal) {
|
||||||
|
const rows = await request<ProjectAsset[]>(assetPath(projectId), { signal })
|
||||||
|
assertAssetList(rows, projectId)
|
||||||
|
return rows
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* 读取并核对指定素材的正式归属。
|
||||||
|
* @param projectId 当前项目
|
||||||
|
* @param assetId 素材编号
|
||||||
|
* @param signal 查询取消信号
|
||||||
|
* @returns 当前素材
|
||||||
|
*/
|
||||||
|
async get(projectId: string, assetId: string, signal?: AbortSignal) {
|
||||||
|
return readAssetResult(
|
||||||
|
await request<ProjectAsset>(assetPath(projectId, assetId), { signal }),
|
||||||
|
projectId,
|
||||||
|
assetId
|
||||||
|
)
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* 明确上传一次文件,结果未确认时不自动重试。
|
||||||
|
* @param projectId 所属项目
|
||||||
|
* @param input 文件及展示信息
|
||||||
|
* @returns 正式素材记录
|
||||||
|
*/
|
||||||
|
async upload(projectId: string, input: UploadProjectAssetInput) {
|
||||||
const body = new FormData()
|
const body = new FormData()
|
||||||
body.append('file', input.file)
|
body.append('file', input.file)
|
||||||
body.append('name', input.name)
|
body.append('name', input.name)
|
||||||
body.append('category', input.category)
|
body.append('category', input.category)
|
||||||
return request<ProjectAsset>(assetPath(projectId), { method: 'POST', body, timeoutMs: 0 })
|
return readAssetResult(
|
||||||
|
await request<ProjectAsset>(assetPath(projectId), { method: 'POST', body, timeoutMs: 0 }),
|
||||||
|
projectId
|
||||||
|
)
|
||||||
},
|
},
|
||||||
update: (projectId: string, assetId: string, input: UpdateProjectAssetInput) =>
|
/**
|
||||||
request<ProjectAsset>(assetPath(projectId, assetId), { method: 'PUT', body: input }),
|
* 更新当前素材展示字段,统一校验返回归属。
|
||||||
remove: (projectId: string, assetId: string) =>
|
* @param projectId 当前项目
|
||||||
request<ProjectAsset>(assetPath(projectId, assetId), { method: 'DELETE' })
|
* @param assetId 素材编号
|
||||||
|
* @param input 可编辑字段
|
||||||
|
* @returns 已确认的素材记录
|
||||||
|
*/
|
||||||
|
async update(projectId: string, assetId: string, input: UpdateProjectAssetInput) {
|
||||||
|
return readAssetResult(
|
||||||
|
await request<ProjectAsset>(assetPath(projectId, assetId), { method: 'PUT', body: input }),
|
||||||
|
projectId,
|
||||||
|
assetId
|
||||||
|
)
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* 明确删除一次素材,不以空响应推断删除成功。
|
||||||
|
* @param projectId 当前项目
|
||||||
|
* @param assetId 素材编号
|
||||||
|
* @returns 已删除的原始记录
|
||||||
|
*/
|
||||||
|
async remove(projectId: string, assetId: string) {
|
||||||
|
return readAssetResult(
|
||||||
|
await request<ProjectAsset>(assetPath(projectId, assetId), { method: 'DELETE' }),
|
||||||
|
projectId,
|
||||||
|
assetId
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 区分真正的空数组与无效响应,避免数据缺失变成空态、加载假象或跨项目操作。
|
||||||
|
* @param value 接口返回的未知数据
|
||||||
|
* @param projectId 可选精确项目范围
|
||||||
|
* @param global 是否要求全局列表的最小项目摘要
|
||||||
|
*/
|
||||||
|
function assertAssetList(value: unknown, projectId?: string, global = false): asserts value is ProjectAsset[] {
|
||||||
|
const valid =
|
||||||
|
Array.isArray(value) &&
|
||||||
|
value.every(item => {
|
||||||
|
if (!item || typeof item !== 'object' || Array.isArray(item)) return false
|
||||||
|
const asset = item as Record<string, unknown>
|
||||||
|
if (
|
||||||
|
[
|
||||||
|
'id',
|
||||||
|
'projectId',
|
||||||
|
'name',
|
||||||
|
'type',
|
||||||
|
'category',
|
||||||
|
'mimeType',
|
||||||
|
'extension',
|
||||||
|
'publicUrl',
|
||||||
|
'createdAt',
|
||||||
|
'updatedAt'
|
||||||
|
].some(key => typeof asset[key] !== 'string')
|
||||||
|
)
|
||||||
|
return false
|
||||||
|
if (typeof asset.size !== 'number' || !Number.isFinite(asset.size) || asset.size < 0) return false
|
||||||
|
if (projectId && asset.projectId !== projectId) return false
|
||||||
|
if (global) {
|
||||||
|
const owner = asset.project
|
||||||
|
if (!owner || typeof owner !== 'object' || Array.isArray(owner)) return false
|
||||||
|
const project = owner as Record<string, unknown>
|
||||||
|
if (
|
||||||
|
project.id !== asset.projectId ||
|
||||||
|
typeof project.topic !== 'string' ||
|
||||||
|
typeof project.status !== 'string' ||
|
||||||
|
(project.title !== null && typeof project.title !== 'string')
|
||||||
|
)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if (!valid) throw new Error('素材列表数据不完整或归属不一致,请重新读取。')
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 全局页与项目页共用操作结果校验,不能将跨项目或未确认响应显示成成功。
|
||||||
|
* @param value 接口声明返回的素材
|
||||||
|
* @param projectId 本次操作项目
|
||||||
|
* @param assetId 已知素材编号,上传时缺省
|
||||||
|
* @returns 归属一致的正式记录
|
||||||
|
*/
|
||||||
|
function readAssetResult(value: ProjectAsset | null | undefined, projectId: string, assetId?: string): ProjectAsset {
|
||||||
|
if (
|
||||||
|
!value ||
|
||||||
|
typeof value.id !== 'string' ||
|
||||||
|
!value.id ||
|
||||||
|
value.projectId !== projectId ||
|
||||||
|
(assetId && value.id !== assetId)
|
||||||
|
)
|
||||||
|
throw new Error('素材操作结果尚未确认,请刷新后核对,避免重复提交。')
|
||||||
|
return value
|
||||||
}
|
}
|
||||||
@@ -9,7 +9,7 @@ import { NScrollbar, NButton, NPageHeader, NSpin, NEllipsis, NSkeleton } from 'n
|
|||||||
import { EmptyState, WorkspaceRefreshButton } from '../../components/ui'
|
import { EmptyState, WorkspaceRefreshButton } from '../../components/ui'
|
||||||
import { projectContextKey, useProjectData } from './context'
|
import { projectContextKey, useProjectData } from './context'
|
||||||
import { getOperation, operationErrorText } from '../workflows/operations'
|
import { getOperation, operationErrorText } from '../workflows/operations'
|
||||||
import { projectAccessKey, projectSectionFromPath, type ProjectAccess } from './access'
|
import { projectAccessKey, projectSectionFromPath, type ProjectAccess, type ProjectSectionAccess } from './access'
|
||||||
import { useProjectStageAccess } from './useProjectStageAccess'
|
import { useProjectStageAccess } from './useProjectStageAccess'
|
||||||
import { useWorkflowExecution } from '../workflows/execution'
|
import { useWorkflowExecution } from '../workflows/execution'
|
||||||
import { clearEpisodeSourceInvalidations, invalidateEpisodeSource } from '../storyboard/model'
|
import { clearEpisodeSourceInvalidations, invalidateEpisodeSource } from '../storyboard/model'
|
||||||
@@ -116,8 +116,15 @@ watchEffect(() => {
|
|||||||
})
|
})
|
||||||
const stageAccess = useProjectStageAccess(id, context.stageReadiness)
|
const stageAccess = useProjectStageAccess(id, context.stageReadiness)
|
||||||
const complete = stageAccess.scriptReady
|
const complete = stageAccess.scriptReady
|
||||||
|
/** 当前路由所属的制作步骤;项目素材不是制作步骤。 */
|
||||||
const currentSection = computed(() => projectSectionFromPath(route.path))
|
const currentSection = computed(() => projectSectionFromPath(route.path))
|
||||||
const currentAccess = computed(() => {
|
/** 仅正式项目素材路由独立开放,未知路由不能借null步骤绕过限制。 */
|
||||||
|
const isProjectAssets = computed(
|
||||||
|
() => route.path.replace(/\/+$/, '') === `/projects/${encodeURIComponent(id.value)}/assets`
|
||||||
|
)
|
||||||
|
/** 已知素材页可读取,具体写入仍由其项目互斥和归属检查决定。 */
|
||||||
|
const currentAccess = computed<ProjectSectionAccess | null>(() => {
|
||||||
|
if (isProjectAssets.value) return { enabled: true, reason: '' }
|
||||||
const section = currentSection.value
|
const section = currentSection.value
|
||||||
return section ? stageAccess.sections.value[section] : null
|
return section ? stageAccess.sections.value[section] : null
|
||||||
})
|
})
|
||||||
|
|||||||
+18
-2
@@ -27,6 +27,17 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
|||||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网关中断可能发生在操作已提交后,说明恢复方式但不自动重试写入。
|
||||||
|
* @param status 原始HTTP状态
|
||||||
|
* @returns 网关连接提示,普通业务错误返回undefined
|
||||||
|
*/
|
||||||
|
function gatewayErrorMessage(status: number): string | undefined {
|
||||||
|
return [502, 503, 504].includes(status)
|
||||||
|
? '服务连接暂时中断,请重新连接;已提交的操作请先刷新结果后核对。'
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 解析公开响应及顶层同步错误码,不自动重试写入。
|
* 解析公开响应及顶层同步错误码,不自动重试写入。
|
||||||
* @param path 不含统一 API 前缀的正式路径
|
* @param path 不含统一 API 前缀的正式路径
|
||||||
@@ -59,11 +70,16 @@ export async function request<T>(path: string, options: RequestOptions = {}): Pr
|
|||||||
try {
|
try {
|
||||||
data = text ? JSON.parse(text) : undefined
|
data = text ? JSON.parse(text) : undefined
|
||||||
} catch {
|
} catch {
|
||||||
throw new ApiError('服务暂时无法返回有效结果,请稍后重试。', response.status)
|
throw new ApiError(
|
||||||
|
gatewayErrorMessage(response.status) ?? '服务暂时无法返回有效结果,请稍后重试。',
|
||||||
|
response.status
|
||||||
|
)
|
||||||
}
|
}
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const message =
|
const message =
|
||||||
isRecord(data) && typeof data.message === 'string' ? data.message : `请求失败(${response.status})`
|
isRecord(data) && typeof data.message === 'string' && data.message.trim()
|
||||||
|
? data.message
|
||||||
|
: (gatewayErrorMessage(response.status) ?? `请求失败(${response.status})`)
|
||||||
throw new ApiError(
|
throw new ApiError(
|
||||||
message,
|
message,
|
||||||
response.status,
|
response.status,
|
||||||
|
|||||||
@@ -20,6 +20,36 @@ const asset: ProjectAsset = {
|
|||||||
afterEach(() => vi.unstubAllGlobals())
|
afterEach(() => vi.unstubAllGlobals())
|
||||||
|
|
||||||
describe('项目资产 API', () => {
|
describe('项目资产 API', () => {
|
||||||
|
it.each(['upload', 'update', 'remove'] as const)('素材%s结果归属错误时不能当成成功', async action => {
|
||||||
|
vi.stubGlobal(
|
||||||
|
'fetch',
|
||||||
|
vi
|
||||||
|
.fn<typeof fetch>()
|
||||||
|
.mockResolvedValue(new Response(JSON.stringify({ data: { ...asset, projectId: 'other-project' } })))
|
||||||
|
)
|
||||||
|
const result =
|
||||||
|
action === 'upload'
|
||||||
|
? projectAssetsApi.upload(asset.projectId, {
|
||||||
|
file: new File(['fixture'], 'fixture.png', { type: 'image/png' }),
|
||||||
|
name: '参考',
|
||||||
|
category: 'reference'
|
||||||
|
})
|
||||||
|
: action === 'update'
|
||||||
|
? projectAssetsApi.update(asset.projectId, asset.id, { name: '新名称' })
|
||||||
|
: projectAssetsApi.remove(asset.projectId, asset.id)
|
||||||
|
await expect(result).rejects.toThrow('结果')
|
||||||
|
})
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{ data: null },
|
||||||
|
{ data: {} },
|
||||||
|
{ data: [{ ...asset, project: null }] },
|
||||||
|
{ data: [{ ...asset, project: { id: 'other', title: null, topic: '主题', status: 'completed' } }] }
|
||||||
|
])('无效全局素材列表不能当成成功数据:%j', async ({ data }) => {
|
||||||
|
vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify({ data }))))
|
||||||
|
await expect(projectAssetsApi.listAll()).rejects.toThrow('素材列表')
|
||||||
|
})
|
||||||
|
|
||||||
it('通过单个全局接口读取全部项目素材', async () => {
|
it('通过单个全局接口读取全部项目素材', async () => {
|
||||||
const globalAsset = {
|
const globalAsset = {
|
||||||
...asset,
|
...asset,
|
||||||
@@ -56,9 +86,17 @@ describe('项目资产 API', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('按正式项目和素材 ID 读取、编辑及删除', async () => {
|
it('按正式项目和素材 ID 读取、编辑及删除', async () => {
|
||||||
const fetcher = vi
|
const fetcher = vi.fn<typeof fetch>().mockImplementation(
|
||||||
.fn<typeof fetch>()
|
async (url, init) =>
|
||||||
.mockImplementation(async () => new Response(JSON.stringify({ data: asset })))
|
new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
data:
|
||||||
|
String(url).endsWith('/assets') && (!init?.method || init.method === 'GET')
|
||||||
|
? [{ ...asset, id: 'asset/db', projectId: 'project/db' }]
|
||||||
|
: { ...asset, id: 'asset/db', projectId: 'project/db' }
|
||||||
|
})
|
||||||
|
)
|
||||||
|
)
|
||||||
vi.stubGlobal('fetch', fetcher)
|
vi.stubGlobal('fetch', fetcher)
|
||||||
|
|
||||||
await projectAssetsApi.list('project/db')
|
await projectAssetsApi.list('project/db')
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||||
import { DOMWrapper, flushPromises, mount, type VueWrapper } from '@vue/test-utils'
|
import { DOMWrapper, flushPromises, mount, type VueWrapper } from '@vue/test-utils'
|
||||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||||
import { NSelect, NTooltip } from 'naive-ui'
|
import { NButton, NSelect, NTooltip } from 'naive-ui'
|
||||||
import AssetLibraryPage from '@/features/project-assets/AssetLibraryPage.vue'
|
import AssetLibraryPage from '@/features/project-assets/AssetLibraryPage.vue'
|
||||||
import AssetCategorySelect from '@/features/project-assets/components/AssetCategorySelect.vue'
|
import AssetCategorySelect from '@/features/project-assets/components/AssetCategorySelect.vue'
|
||||||
|
|
||||||
@@ -14,6 +14,139 @@ afterEach(() => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('全局资产库', () => {
|
describe('全局资产库', () => {
|
||||||
|
it('删除进行中只标记删除loading,不把保存按钮显示为正在保存', async () => {
|
||||||
|
const asset = {
|
||||||
|
id: 'deleting-asset',
|
||||||
|
projectId: 'p',
|
||||||
|
name: '待删除测试图',
|
||||||
|
type: 'image',
|
||||||
|
category: 'reference',
|
||||||
|
mimeType: 'image/png',
|
||||||
|
extension: 'png',
|
||||||
|
size: 1024,
|
||||||
|
publicUrl: '/storage/fixture.png',
|
||||||
|
metadata: null,
|
||||||
|
createdAt: '2026-11-01',
|
||||||
|
updatedAt: '2026-11-01',
|
||||||
|
project: { id: 'p', title: '测试剧本', topic: '主题', status: 'completed' }
|
||||||
|
}
|
||||||
|
let finish!: (response: Response) => void
|
||||||
|
vi.stubGlobal(
|
||||||
|
'fetch',
|
||||||
|
vi.fn<typeof fetch>().mockImplementation(async (input, init) => {
|
||||||
|
if (init?.method === 'DELETE')
|
||||||
|
return new Promise<Response>(resolve => {
|
||||||
|
finish = resolve
|
||||||
|
})
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({ data: String(input).endsWith('/projects') ? [asset.project] : [asset] })
|
||||||
|
)
|
||||||
|
})
|
||||||
|
)
|
||||||
|
wrapper = mount(AssetLibraryPage, { attachTo: document.body })
|
||||||
|
await flushPromises()
|
||||||
|
await wrapper.get('.asset-library-card').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
;[...document.querySelectorAll<HTMLButtonElement>('button')]
|
||||||
|
.find(button => button.textContent?.trim() === '删除素材')!
|
||||||
|
.click()
|
||||||
|
await flushPromises()
|
||||||
|
;[...document.querySelectorAll<HTMLButtonElement>('button')]
|
||||||
|
.find(button => button.textContent?.trim() === '确认删除')!
|
||||||
|
.click()
|
||||||
|
await flushPromises()
|
||||||
|
try {
|
||||||
|
const buttons = wrapper.findAllComponents(NButton)
|
||||||
|
expect(buttons.find(button => button.text().trim() === '保存修改')!.props('loading')).toBe(false)
|
||||||
|
expect(buttons.find(button => button.text().trim() === '删除素材')!.props('loading')).toBe(true)
|
||||||
|
} finally {
|
||||||
|
finish(new Response(JSON.stringify({ data: asset })))
|
||||||
|
await flushPromises()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('保存成功后列表刷新失败时保留旧结果,只读详情不再允许重复写入', async () => {
|
||||||
|
const asset = {
|
||||||
|
id: 'retained-asset',
|
||||||
|
projectId: 'p',
|
||||||
|
name: '保留图片',
|
||||||
|
type: 'image',
|
||||||
|
category: 'reference',
|
||||||
|
mimeType: 'image/png',
|
||||||
|
extension: 'png',
|
||||||
|
size: 1024,
|
||||||
|
publicUrl: '/storage/fixture.png',
|
||||||
|
metadata: null,
|
||||||
|
createdAt: '2026-11-01',
|
||||||
|
updatedAt: '2026-11-01',
|
||||||
|
project: { id: 'p', title: '保留剧本', topic: '主题', status: 'completed' }
|
||||||
|
}
|
||||||
|
let updated = false
|
||||||
|
vi.stubGlobal(
|
||||||
|
'fetch',
|
||||||
|
vi.fn<typeof fetch>().mockImplementation(async (input, init) => {
|
||||||
|
if (init?.method === 'PUT') {
|
||||||
|
updated = true
|
||||||
|
return new Response(JSON.stringify({ data: asset }))
|
||||||
|
}
|
||||||
|
if (String(input).endsWith('/projects')) return new Response(JSON.stringify({ data: [asset.project] }))
|
||||||
|
return updated ? new Response('', { status: 502 }) : new Response(JSON.stringify({ data: [asset] }))
|
||||||
|
})
|
||||||
|
)
|
||||||
|
wrapper = mount(AssetLibraryPage, { attachTo: document.body })
|
||||||
|
await flushPromises()
|
||||||
|
await wrapper.get('.asset-library-card').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
const first = document.querySelector('[role="dialog"][aria-label="素材详情与管理"]')!
|
||||||
|
;[...first.querySelectorAll<HTMLButtonElement>('button')]
|
||||||
|
.find(button => button.textContent?.trim() === '保存修改')!
|
||||||
|
.click()
|
||||||
|
await flushPromises()
|
||||||
|
expect(wrapper.findAll('.asset-library-card')).toHaveLength(1)
|
||||||
|
expect(wrapper.text()).toContain('写操作已暂停')
|
||||||
|
await wrapper.get('.asset-library-card').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
const current = document.querySelector('[role="dialog"][aria-label="素材详情与管理"]')!
|
||||||
|
expect(
|
||||||
|
[...current.querySelectorAll<HTMLButtonElement>('button')]
|
||||||
|
.filter(button => ['保存修改', '删除素材'].includes(button.textContent?.trim() ?? ''))
|
||||||
|
.every(button => button.disabled)
|
||||||
|
).toBe(true)
|
||||||
|
expect(
|
||||||
|
[...current.querySelectorAll<HTMLButtonElement>('button')].find(
|
||||||
|
button => button.textContent?.trim() === '取消'
|
||||||
|
)!.disabled
|
||||||
|
).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('首次502失败后结束加载,一次重连同时恢复资产和剧本选项', async () => {
|
||||||
|
let available = false
|
||||||
|
const fetcher = vi.fn<typeof fetch>().mockImplementation(async input =>
|
||||||
|
available
|
||||||
|
? new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
data: String(input).endsWith('/projects')
|
||||||
|
? [{ id: 'project-one', title: '可用剧本', topic: '主题' }]
|
||||||
|
: []
|
||||||
|
})
|
||||||
|
)
|
||||||
|
: new Response('', { status: 502 })
|
||||||
|
)
|
||||||
|
vi.stubGlobal('fetch', fetcher)
|
||||||
|
wrapper = mount(AssetLibraryPage, { attachTo: document.body })
|
||||||
|
await flushPromises()
|
||||||
|
expect(wrapper.find('[role="status"]').exists()).toBe(false)
|
||||||
|
expect(wrapper.find('.empty-state').exists()).toBe(false)
|
||||||
|
available = true
|
||||||
|
const reconnect = wrapper.findAll('button').find(button => button.text().trim() === '重新连接')!
|
||||||
|
await reconnect.trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
expect(wrapper.text()).not.toContain('剧本列表读取失败')
|
||||||
|
expect(wrapper.text()).toContain('资产库还是空的')
|
||||||
|
const upload = wrapper.findAll('button').find(button => button.text().trim() === '上传图片')!
|
||||||
|
expect(upload.attributes('disabled')).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
it('单次读取并直接显示全部剧本图片,支持按图片与剧本搜索', async () => {
|
it('单次读取并直接显示全部剧本图片,支持按图片与剧本搜索', async () => {
|
||||||
const assets = [
|
const assets = [
|
||||||
{
|
{
|
||||||
@@ -124,5 +257,8 @@ describe('全局资产库', () => {
|
|||||||
expect(wrapper.findAll('.asset-library-card')).toHaveLength(1)
|
expect(wrapper.findAll('.asset-library-card')).toHaveLength(1)
|
||||||
expect(wrapper.text()).toContain('林默正面照')
|
expect(wrapper.text()).toContain('林默正面照')
|
||||||
expect(wrapper.text()).not.toContain('雨夜街道')
|
expect(wrapper.text()).not.toContain('雨夜街道')
|
||||||
|
await wrapper.get('input[aria-label="搜索资产图片"]').setValue('人物')
|
||||||
|
expect(wrapper.findAll('.asset-library-card')).toHaveLength(1)
|
||||||
|
expect(wrapper.text()).toContain('林默正面照')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -4,6 +4,7 @@ import { createMemoryHistory, createRouter } from 'vue-router'
|
|||||||
import ProjectAssetsPage from '@/features/project-assets/ProjectAssetsPage.vue'
|
import ProjectAssetsPage from '@/features/project-assets/ProjectAssetsPage.vue'
|
||||||
import { projectContextKey } from '@/features/projects/context'
|
import { projectContextKey } from '@/features/projects/context'
|
||||||
import { testProjectContext } from '@/testing/project-context'
|
import { testProjectContext } from '@/testing/project-context'
|
||||||
|
import AppDialog from '@/components/ui/AppDialog.vue'
|
||||||
|
|
||||||
let wrapper: VueWrapper | undefined
|
let wrapper: VueWrapper | undefined
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -13,7 +14,88 @@ afterEach(() => {
|
|||||||
vi.unstubAllGlobals()
|
vi.unstubAllGlobals()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
/** 当前项目的受控素材,未调用真实资产接口。 */
|
||||||
|
const projectAssetFixture = {
|
||||||
|
id: 'fixture-asset',
|
||||||
|
projectId: 'capability-test',
|
||||||
|
name: '隔离测试图片',
|
||||||
|
type: 'image',
|
||||||
|
category: 'reference',
|
||||||
|
mimeType: 'image/png',
|
||||||
|
extension: 'png',
|
||||||
|
size: 1024,
|
||||||
|
publicUrl: '/storage/fixture.png',
|
||||||
|
metadata: null,
|
||||||
|
createdAt: '2026-11-01T00:00:00Z',
|
||||||
|
updatedAt: '2026-11-01T00:00:00Z'
|
||||||
|
}
|
||||||
|
|
||||||
describe('项目资产库页面', () => {
|
describe('项目资产库页面', () => {
|
||||||
|
it('项目读取失败只暂停保存,仍允许取消已有草稿', async () => {
|
||||||
|
vi.stubGlobal(
|
||||||
|
'fetch',
|
||||||
|
vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify({ data: [projectAssetFixture] })))
|
||||||
|
)
|
||||||
|
const context = testProjectContext()
|
||||||
|
wrapper = mount(ProjectAssetsPage, {
|
||||||
|
attachTo: document.body,
|
||||||
|
global: { provide: { [projectContextKey as symbol]: context } }
|
||||||
|
})
|
||||||
|
await flushPromises()
|
||||||
|
await wrapper
|
||||||
|
.findAll('button')
|
||||||
|
.find(button => button.text().trim() === '编辑')!
|
||||||
|
.trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
context.error.value = '项目暂时读取失败'
|
||||||
|
await flushPromises()
|
||||||
|
const dialog = document.querySelector('[role="dialog"][aria-label="编辑素材信息"]')!
|
||||||
|
const cancel = [...dialog.querySelectorAll<HTMLButtonElement>('button')].find(
|
||||||
|
button => button.textContent?.trim() === '取消'
|
||||||
|
)!
|
||||||
|
expect(cancel.disabled).toBe(false)
|
||||||
|
cancel.click()
|
||||||
|
await flushPromises()
|
||||||
|
expect(
|
||||||
|
wrapper
|
||||||
|
.findAllComponents(AppDialog)
|
||||||
|
.find(item => item.props('title') === '编辑素材信息')!
|
||||||
|
.props('open')
|
||||||
|
).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('切换项目时关闭旧素材编辑,不让旧项目草稿留在新页面', async () => {
|
||||||
|
vi.stubGlobal(
|
||||||
|
'fetch',
|
||||||
|
vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify({ data: [projectAssetFixture] })))
|
||||||
|
)
|
||||||
|
const context = testProjectContext()
|
||||||
|
wrapper = mount(ProjectAssetsPage, {
|
||||||
|
attachTo: document.body,
|
||||||
|
global: { provide: { [projectContextKey as symbol]: context } }
|
||||||
|
})
|
||||||
|
await flushPromises()
|
||||||
|
await wrapper
|
||||||
|
.findAll('button')
|
||||||
|
.find(button => button.text().trim() === '编辑')!
|
||||||
|
.trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
expect(
|
||||||
|
wrapper
|
||||||
|
.findAllComponents(AppDialog)
|
||||||
|
.find(dialog => dialog.props('title') === '编辑素材信息')!
|
||||||
|
.props('open')
|
||||||
|
).toBe(true)
|
||||||
|
context.data.value!.project.id = 'second-project'
|
||||||
|
await flushPromises()
|
||||||
|
expect(
|
||||||
|
wrapper
|
||||||
|
.findAllComponents(AppDialog)
|
||||||
|
.find(dialog => dialog.props('title') === '编辑素材信息')!
|
||||||
|
.props('open')
|
||||||
|
).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
it('读取当前项目素材并支持名称、分类和原文件名筛选', async () => {
|
it('读取当前项目素材并支持名称、分类和原文件名筛选', async () => {
|
||||||
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(
|
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(
|
||||||
new Response(
|
new Response(
|
||||||
@@ -74,6 +156,9 @@ describe('项目资产库页面', () => {
|
|||||||
expect(wrapper.text()).toContain('雨夜街道')
|
expect(wrapper.text()).toContain('雨夜街道')
|
||||||
expect(wrapper.text()).toContain('林默正面照')
|
expect(wrapper.text()).toContain('林默正面照')
|
||||||
|
|
||||||
|
await wrapper.get('input[aria-label="搜索项目素材"]').setValue('场景')
|
||||||
|
expect(wrapper.findAll('.project-asset-card')).toHaveLength(1)
|
||||||
|
expect(wrapper.text()).toContain('雨夜街道')
|
||||||
await wrapper.get('input[aria-label="搜索项目素材"]').setValue('street-original')
|
await wrapper.get('input[aria-label="搜索项目素材"]').setValue('street-original')
|
||||||
expect(wrapper.findAll('.project-asset-card')).toHaveLength(1)
|
expect(wrapper.findAll('.project-asset-card')).toHaveLength(1)
|
||||||
expect(wrapper.text()).toContain('雨夜街道')
|
expect(wrapper.text()).toContain('雨夜街道')
|
||||||
|
|||||||
@@ -90,7 +90,7 @@ async function openProject(initialPath: string) {
|
|||||||
{
|
{
|
||||||
path: '/projects/:projectId',
|
path: '/projects/:projectId',
|
||||||
component: ProjectLayout,
|
component: ProjectLayout,
|
||||||
children: ['create-drama', ...downstream].map(path => ({
|
children: ['create-drama', ...downstream, 'assets', 'unknown-step'].map(path => ({
|
||||||
path,
|
path,
|
||||||
component: {
|
component: {
|
||||||
setup() {
|
setup() {
|
||||||
@@ -114,6 +114,20 @@ async function openProject(initialPath: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('剧本完成前的下游访问限制', () => {
|
describe('剧本完成前的下游访问限制', () => {
|
||||||
|
it('已知项目资产入口不受制作阶段拦截,未知工作区仍默认锁定', async () => {
|
||||||
|
const id = 'independent-project-assets'
|
||||||
|
vi.mocked(projectsApi.stageReadiness).mockResolvedValue(readiness(id, false))
|
||||||
|
vi.spyOn(projectsApi, 'detail').mockResolvedValue(project(id, 'generating'))
|
||||||
|
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([])
|
||||||
|
const { router, mounted } = await openProject(`/projects/${id}/assets`)
|
||||||
|
expect(mounted).toHaveBeenCalledExactlyOnceWith('assets')
|
||||||
|
expect(wrapper!.find('.project-access-gate').exists()).toBe(false)
|
||||||
|
await router.push(`/projects/${id}/unknown-step`)
|
||||||
|
await flushPromises()
|
||||||
|
expect(mounted).not.toHaveBeenCalledWith('unknown-step')
|
||||||
|
expect(wrapper!.find('.project-access-gate').exists()).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
it('导航使用当前阶段结果,旧待审标记不盖过已审核状态,下游素材仍独立限制', async () => {
|
it('导航使用当前阶段结果,旧待审标记不盖过已审核状态,下游素材仍独立限制', async () => {
|
||||||
const id = 'current-review-navigation'
|
const id = 'current-review-navigation'
|
||||||
const state = readiness(id, false)
|
const state = readiness(id, false)
|
||||||
|
|||||||
+14
-1
@@ -17,6 +17,16 @@ afterEach(() => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('后端 API 契约', () => {
|
describe('后端 API 契约', () => {
|
||||||
|
it.each([502, 503, 504])('网关%s的空响应和HTML响应保留状态并提供连接恢复说明', async status => {
|
||||||
|
vi.stubGlobal(
|
||||||
|
'fetch',
|
||||||
|
vi
|
||||||
|
.fn<typeof fetch>()
|
||||||
|
.mockImplementation(async () => new Response('<html>gateway unavailable</html>', { status }))
|
||||||
|
)
|
||||||
|
await expect(request('/assets')).rejects.toMatchObject({ status, message: expect.stringContaining('连接') })
|
||||||
|
})
|
||||||
|
|
||||||
it('图库读取与单图、批量和切换主图使用各自接口,模型由后端统一配置', async () => {
|
it('图库读取与单图、批量和切换主图使用各自接口,模型由后端统一配置', async () => {
|
||||||
const fetcher = vi.fn<typeof fetch>().mockImplementation(async () => new Response('{"data":[]}'))
|
const fetcher = vi.fn<typeof fetch>().mockImplementation(async () => new Response('{"data":[]}'))
|
||||||
vi.stubGlobal('fetch', fetcher)
|
vi.stubGlobal('fetch', fetcher)
|
||||||
@@ -169,7 +179,10 @@ describe('后端 API 契约', () => {
|
|||||||
.mockResolvedValueOnce(new Response('<html>Bad Gateway</html>', { status: 502 }))
|
.mockResolvedValueOnce(new Response('<html>Bad Gateway</html>', { status: 502 }))
|
||||||
)
|
)
|
||||||
await expect(request('/projects')).rejects.toMatchObject({ status: 400, details: ['缺少形态'] })
|
await expect(request('/projects')).rejects.toMatchObject({ status: 400, details: ['缺少形态'] })
|
||||||
await expect(request('/projects')).rejects.toThrow('服务暂时无法返回有效结果')
|
await expect(request('/projects')).rejects.toMatchObject({
|
||||||
|
status: 502,
|
||||||
|
message: expect.stringContaining('连接')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('预览模块使用逗号参数,三种恢复不误发到 start', async () => {
|
it('预览模块使用逗号参数,三种恢复不误发到 start', async () => {
|
||||||
|
|||||||
Reference in new issue
Block a user