diff --git a/app/api/admin/data-stats/export/route.ts b/app/api/admin/data-stats/export/route.ts index 2c4aefb4..5f167d4a 100644 --- a/app/api/admin/data-stats/export/route.ts +++ b/app/api/admin/data-stats/export/route.ts @@ -1,3 +1,4 @@ +import { buildMaterialOrganizationWhere } from '@/lib/material-organization-access' import type { NextRequest } from 'next/server' import { NextResponse } from 'next/server' import { getServerSession } from 'next-auth' @@ -65,7 +66,9 @@ export async function GET(request: NextRequest) { const endDate = searchParams.get('endDate') const departmentKey = searchParams.get('departmentKey') + const accessWhere = await buildMaterialOrganizationWhere((session.user as any).id) const stats = await getMaterialUploadStats({ + accessWhere, startDate, endDate, departmentKey, @@ -101,6 +104,7 @@ export async function GET(request: NextRequest) { where: { deletedAt: null, userId: { in: selectedUserIds }, + ...accessWhere, ...(createdAtFilter.gte || createdAtFilter.lte ? { createdAt: createdAtFilter } : {}), }, orderBy: { createdAt: 'desc' }, diff --git a/app/api/admin/data-stats/route.ts b/app/api/admin/data-stats/route.ts index 8255abd9..ae41030a 100644 --- a/app/api/admin/data-stats/route.ts +++ b/app/api/admin/data-stats/route.ts @@ -1,3 +1,4 @@ +import { buildMaterialOrganizationWhere } from '@/lib/material-organization-access' import type { NextRequest } from 'next/server' import { NextResponse } from 'next/server' import { getServerSession } from 'next-auth' @@ -37,7 +38,9 @@ export async function GET(request: NextRequest) { const endDate = searchParams.get('endDate') const departmentKey = searchParams.get('departmentKey') + const accessWhere = await buildMaterialOrganizationWhere((session.user as any).id) const stats = await getMaterialUploadStats({ + accessWhere, startDate, endDate, departmentKey, diff --git a/app/api/admin/external-notification-deliveries/route.ts b/app/api/admin/external-notification-deliveries/route.ts index 4b3c74db..84fdb32b 100644 --- a/app/api/admin/external-notification-deliveries/route.ts +++ b/app/api/admin/external-notification-deliveries/route.ts @@ -1,3 +1,4 @@ +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' import { NextRequest, NextResponse } from 'next/server' import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' @@ -15,14 +16,14 @@ async function assertAdminPermission() { return NextResponse.json({ success: false, error: '仅超级管理员可访问' }, { status: 403 }) } - return null + return userId } export async function GET(request: NextRequest) { try { - const authError = await assertAdminPermission() - if (authError) { - return authError + const operatorUserId = await assertAdminPermission() + if (typeof operatorUserId !== 'string') { + return operatorUserId } const { searchParams } = new URL(request.url) @@ -31,6 +32,7 @@ export async function GET(request: NextRequest) { const limit = Number.isFinite(parsedLimit) && parsedLimit! > 0 ? parsedLimit : undefined const deliveries = await listExternalNotificationDeliveries({ + canAccessOperationsG: await canAccessOperationsGMaterials(operatorUserId), status: searchParams.get('status') || undefined, targetId: searchParams.get('targetId') || undefined, materialId: searchParams.get('materialId') || undefined, diff --git a/app/api/admin/material-operation-logs/route.ts b/app/api/admin/material-operation-logs/route.ts index 70a88ba5..ea3c9f3c 100644 --- a/app/api/admin/material-operation-logs/route.ts +++ b/app/api/admin/material-operation-logs/route.ts @@ -1,3 +1,4 @@ +import { canAccessOperationsGMaterials, getOperationsGMaterialIds } from '@/lib/material-organization-access' import { NextRequest, NextResponse } from 'next/server' import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' @@ -52,8 +53,9 @@ export async function GET(request: NextRequest) { const endDate = searchParams.get('endDate') const keyword = normalizeKeyword(searchParams.get('keyword')) - const materialLogWhere: any = {} - const downloadLogWhere: any = {} + const excludedIds = await canAccessOperationsGMaterials((session.user as any).id) ? [] : await getOperationsGMaterialIds() + const materialLogWhere: any = { ...(excludedIds.length ? { materialId: { notIn: excludedIds } } : {}) } + const downloadLogWhere: any = { ...(excludedIds.length ? { materialId: { notIn: excludedIds } } : {}) } if (startDate || endDate) { const timestampFilter: { gte?: Date; lte?: Date } = {} diff --git a/app/api/admin/materials/batch-delete/route.ts b/app/api/admin/materials/batch-delete/route.ts index 440acbe7..75df32df 100644 --- a/app/api/admin/materials/batch-delete/route.ts +++ b/app/api/admin/materials/batch-delete/route.ts @@ -1,3 +1,5 @@ +import { invalidateMaterialFacetsCache } from '@/lib/material-facets-cache' +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' import { NextRequest, NextResponse } from 'next/server' import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' @@ -61,13 +63,17 @@ export async function POST(request: NextRequest) { // 查询素材(需要处理任务号) const materials = await prisma.material.findMany({ where: { id: { in: ids } }, - select: { id: true, taskNo: true, productModel: true, materialType: true } + select: { id: true, taskNo: true, productModel: true, materialType: true, accessScope: true } }) if (materials.length === 0) { return NextResponse.json({ error: '未找到要删除的素材' }, { status: 404 }) } + if (materials.some((material) => material.accessScope === 'operations_g') && !(await canAccessOperationsGMaterials(operatorId))) { + return NextResponse.json({ error: '无权限操作运营中心 G 专属素材' }, { status: 403 }) + } + const deletedAt = new Date() await prisma.$transaction([ @@ -116,6 +122,7 @@ export async function POST(request: NextRequest) { ) ) + invalidateMaterialFacetsCache() console.log(`[BatchDelete] 软删除完成: ${materials.length} 条素材`) return NextResponse.json({ diff --git a/app/api/admin/materials/purge-jobs/route.ts b/app/api/admin/materials/purge-jobs/route.ts index 077d8cbb..6a1599ab 100644 --- a/app/api/admin/materials/purge-jobs/route.ts +++ b/app/api/admin/materials/purge-jobs/route.ts @@ -3,6 +3,7 @@ import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' import { isSystemAdmin } from '@/lib/department-permission' import { prisma } from '@/lib/prisma' +import { canAccessOperationsGMaterials, getOperationsGMaterialIds } from '@/lib/material-organization-access' import { ensureMaterialPurgeWorkerStarted, MaterialPurgeError, retryMaterialPurge, toPurgeJobView } from '@/lib/material-purge' export const dynamic = 'force-dynamic' @@ -14,15 +15,18 @@ async function operator() { } export async function GET(request: NextRequest) { - if (!await operator()) return NextResponse.json({ error: '无权限' }, { status: 403 }) + const operatorId = await operator() + if (!operatorId) return NextResponse.json({ error: '无权限' }, { status: 403 }) const ids = request.nextUrl.searchParams.getAll('id') if (ids.length > 100 || ids.some(id => !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id))) { return NextResponse.json({ error: '清理任务无效' }, { status: 400 }) } try { + const excludedIds = await canAccessOperationsGMaterials(operatorId) ? [] : await getOperationsGMaterialIds() + const scopeWhere = excludedIds.length ? { materialId: { notIn: excludedIds } } : {} const [pending, tracked] = await Promise.all([ - prisma.materialPurgeJob.findMany({ where: { status: { not: 'completed' } }, orderBy: { createdAt: 'asc' }, take: 100 }), - ids.length ? prisma.materialPurgeJob.findMany({ where: { id: { in: ids } } }) : Promise.resolve([]), + prisma.materialPurgeJob.findMany({ where: { ...scopeWhere, status: { not: 'completed' } }, orderBy: { createdAt: 'asc' }, take: 100 }), + ids.length ? prisma.materialPurgeJob.findMany({ where: { ...scopeWhere, id: { in: ids } } }) : Promise.resolve([]), ]) const jobs = [...tracked, ...pending.filter(job => !tracked.some(item => item.id === job.id))] return NextResponse.json({ jobs: jobs.map(toPurgeJobView) }, { headers: { 'Cache-Control': 'no-store' } }) diff --git a/app/api/admin/regenerate-pdf-preview/route.ts b/app/api/admin/regenerate-pdf-preview/route.ts index b0118c62..171098d1 100644 --- a/app/api/admin/regenerate-pdf-preview/route.ts +++ b/app/api/admin/regenerate-pdf-preview/route.ts @@ -1,3 +1,5 @@ +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' +import { isRestrictedMaterial } from '@/lib/material-access-scope' import { createHash, timingSafeEqual } from 'crypto' import { lstat, realpath } from 'fs/promises' import path from 'path' @@ -242,6 +244,7 @@ async function inspectTrustedPdfSource(storedPath: string): Promise<{ async function processTrustedPdfSource( realPath: string, snapshot: FileSnapshot, + protectedMaterialId?: string, ) { return withImageProcessingSlot(async () => { // processPdfUpload 会读取 PDF 文件头和生成内容;这些读取必须全程处在全局锁内。 @@ -256,7 +259,7 @@ async function processTrustedPdfSource( throw new RegeneratePdfPreviewInputError('PDF 源文件在处理前发生变化', 409) } - return processPdfUpload(currentRealPath, '') + return processPdfUpload(currentRealPath, '', protectedMaterialId) }) } @@ -280,6 +283,7 @@ export async function POST(request: NextRequest) { select: { id: true, materialType: true, + accessScope: true, zipFilePath: true, }, }) @@ -287,6 +291,10 @@ export async function POST(request: NextRequest) { if (!material) { throw new RegeneratePdfPreviewInputError('素材不存在', 404) } + const session = isRestrictedMaterial(material) ? await getServerSession(authOptions) : null + if (isRestrictedMaterial(material) && !(await canAccessOperationsGMaterials((session?.user as any)?.id))) { + throw new RegeneratePdfPreviewInputError('无权限操作此素材', 403) + } if (material.materialType !== '品牌VI灵感') { throw new RegeneratePdfPreviewInputError('此接口仅适用于品牌VI灵感类型素材') } @@ -297,7 +305,7 @@ export async function POST(request: NextRequest) { } const source = await inspectTrustedPdfSource(storedPath) - const pdfResult = await processTrustedPdfSource(source.realPath, source.snapshot) + const pdfResult = await processTrustedPdfSource(source.realPath, source.snapshot, isRestrictedMaterial(material) ? materialId : undefined) if (!pdfResult.success || !pdfResult.previewUrl) { console.error('[Regenerate PDF Preview] PDF 预览生成失败:', pdfResult.error) throw new Error('PDF 预览生成失败') diff --git a/app/api/admin/regenerate-preview/route.ts b/app/api/admin/regenerate-preview/route.ts index 6c20f4af..89f3e16d 100644 --- a/app/api/admin/regenerate-preview/route.ts +++ b/app/api/admin/regenerate-preview/route.ts @@ -21,6 +21,7 @@ import { } from '@/lib/path-security' import { prisma } from '@/lib/prisma' import { canAccessMaterialPrivacy } from '@/lib/task-detail-privacy' +import { isRestrictedMaterial } from '@/lib/material-access-scope' import { saveTaskDetailPreview } from '@/lib/task-detail-preview-storage' import { deleteFromS3, verifyUploadedS3Object } from '@/lib/s3' import { getUploadRootDir, resolveStoredUploadPath } from '@/lib/upload-paths' @@ -260,7 +261,7 @@ async function regeneratePreview(materialId: string, userId: string) { if (!(await canAccessMaterialPrivacy(material, userId))) { throw new RegeneratePreviewInputError('无权限操作', 403) } - const isPrivate = Boolean(material.taskDetailPrivate) + const isPrivate = isRestrictedMaterial(material) const detailAssets = await prisma.materialAsset.findMany({ where: { materialId, assetType: 'detail' }, diff --git a/app/api/admin/system-status/route.ts b/app/api/admin/system-status/route.ts index cddb6e43..496d1b92 100644 --- a/app/api/admin/system-status/route.ts +++ b/app/api/admin/system-status/route.ts @@ -10,6 +10,7 @@ import { NextRequest, NextResponse } from 'next/server' import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' import { prisma } from '@/lib/prisma' +import { buildMaterialOrganizationWhere } from '@/lib/material-organization-access' export async function GET(req: NextRequest) { try { @@ -23,6 +24,8 @@ export async function GET(req: NextRequest) { ) } + const organizationWhere = await buildMaterialOrganizationWhere((session.user as any).id) + // 计算时间范围(30天前和7天前) const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) @@ -38,7 +41,7 @@ export async function GET(req: NextRequest) { }), prisma.material.aggregate({ _count: { id: true }, - where: { createdAt: { gte: thirtyDaysAgo }, deletedAt: null } as any, + where: { ...organizationWhere, createdAt: { gte: thirtyDaysAgo }, deletedAt: null } as any, }), prisma.systemSettings.findFirst({ select: { siteName: true }, @@ -46,7 +49,7 @@ export async function GET(req: NextRequest) { prisma.material.findMany({ take: 10, orderBy: { createdAt: 'desc' }, - where: { deletedAt: null } as any, + where: { ...organizationWhere, deletedAt: null } as any, select: { id: true, productModel: true, @@ -60,7 +63,7 @@ export async function GET(req: NextRequest) { }, }), prisma.user.count(), - prisma.material.count({ where: { deletedAt: null } as any }), + prisma.material.count({ where: { ...organizationWhere, deletedAt: null } as any }), prisma.user.count({ where: { updatedAt: { gte: sevenDaysAgo } } }), prisma.user.groupBy({ by: ['department'], @@ -95,6 +98,7 @@ export async function GET(req: NextRequest) { id: true, }, where: { + ...organizationWhere, deletedAt: null, // 只统计未删除的素材 } as any, }) @@ -113,6 +117,7 @@ export async function GET(req: NextRequest) { try { const deletedCount = await prisma.material.count({ where: { + ...organizationWhere, deletedAt: { not: null }, } as any, }) @@ -126,6 +131,7 @@ export async function GET(req: NextRequest) { if (error?.meta?.column?.includes('deletedAt')) { const materialTypeStats = await prisma.material.groupBy({ by: ['materialType'], + where: organizationWhere, _count: { id: true, }, @@ -195,6 +201,7 @@ export async function GET(req: NextRequest) { // 获取存储统计(素材文件大小) const storageStats = await prisma.material.aggregate({ + where: organizationWhere, _sum: { zipFileSize: true, }, diff --git a/app/api/admin/trash/route.ts b/app/api/admin/trash/route.ts index b42c530d..64d72198 100644 --- a/app/api/admin/trash/route.ts +++ b/app/api/admin/trash/route.ts @@ -1,3 +1,4 @@ +import { buildMaterialOrganizationWhere } from '@/lib/material-organization-access' /** * 回收站 API - 获取已删除的素材 * @@ -26,10 +27,13 @@ export async function GET(req: NextRequest) { const pageSize = parseInt(searchParams.get('pageSize') || '20') const skip = (page - 1) * pageSize + const scopeWhere = await buildMaterialOrganizationWhere((session.user as any).id) + // 获取已删除的素材 const [deletedMaterials, total] = await Promise.all([ prisma.material.findMany({ where: { + ...scopeWhere, deletedAt: { not: null }, // 只返回已删除的素材 }, select: { @@ -58,6 +62,7 @@ export async function GET(req: NextRequest) { } as any), prisma.material.count({ where: { + ...scopeWhere, deletedAt: { not: null }, }, } as any), diff --git a/app/api/admin/video-transcode-stats/route.ts b/app/api/admin/video-transcode-stats/route.ts index 41bbae9b..65497317 100644 --- a/app/api/admin/video-transcode-stats/route.ts +++ b/app/api/admin/video-transcode-stats/route.ts @@ -11,6 +11,7 @@ import { NextRequest, NextResponse } from 'next/server' import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' import { prisma } from '@/lib/prisma' +import { buildMaterialOrganizationWhere } from '@/lib/material-organization-access' import { LEGACY_COMPATIBLE_VIDEO_MATERIAL_TYPES } from '@/lib/video-material-types' import { USER_TRANSCODE_FAILURE_MESSAGE } from '@/lib/video-transcode-task' @@ -26,6 +27,8 @@ export async function GET(req: NextRequest) { ) } + const organizationWhere = await buildMaterialOrganizationWhere((session.user as any).id) + // 识别视频素材类型 const videoMaterialTypes = [...LEGACY_COMPATIBLE_VIDEO_MATERIAL_TYPES] @@ -36,6 +39,7 @@ export async function GET(req: NextRequest) { const videoMaterials = await prisma.material.findMany({ where: { AND: [ + organizationWhere, { materialType: { in: videoMaterialTypes, @@ -132,6 +136,7 @@ export async function GET(req: NextRequest) { // 降级查询:只统计视频素材数量 const videoMaterials = await prisma.material.findMany({ where: { + ...organizationWhere, materialType: { in: videoMaterialTypes, }, diff --git a/app/api/categories/route.ts b/app/api/categories/route.ts index 0d1be754..7dce702d 100644 --- a/app/api/categories/route.ts +++ b/app/api/categories/route.ts @@ -1,3 +1,4 @@ +import { buildMaterialOrganizationWhere } from '@/lib/material-organization-access' import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; @@ -11,6 +12,8 @@ export async function GET() { return NextResponse.json({ error: '未登录' }, { status: 401 }); } + const scopeWhere = await buildMaterialOrganizationWhere((session.user as any).id); + const categories = await prisma.category.findMany({ orderBy: { name: 'asc' }, }); @@ -22,6 +25,7 @@ export async function GET() { try { count = await prisma.material.count({ where: { + ...scopeWhere, categoryName: category.name, deletedAt: null, } as any, @@ -30,7 +34,7 @@ export async function GET() { // 兼容旧版本数据库(没有deletedAt字段) if (e?.meta?.column?.includes('deletedAt')) { count = await prisma.material.count({ - where: { categoryName: category.name }, + where: { ...scopeWhere, categoryName: category.name }, }); } else { throw e; diff --git a/app/api/external/dingtalk-material-match/route.ts b/app/api/external/dingtalk-material-match/route.ts index 40c60756..17e84ff5 100644 --- a/app/api/external/dingtalk-material-match/route.ts +++ b/app/api/external/dingtalk-material-match/route.ts @@ -181,7 +181,7 @@ export async function GET(request: NextRequest) { try { const matchedMaterial = await prisma.material.findFirst({ where: { - taskDetailPrivate: false, + taskDetailPrivate: false, accessScope: 'general', deletedAt: null, productModel: trace.normalizedSpu, ...(materialType ? { materialType } : {}), diff --git a/app/api/external/download/route.ts b/app/api/external/download/route.ts index 5c4d4d1c..afdd8620 100644 --- a/app/api/external/download/route.ts +++ b/app/api/external/download/route.ts @@ -1,3 +1,4 @@ +import { isRestrictedMaterial } from '@/lib/material-access-scope' /** * 外部接口:文件下载 * GET - 通过 Token 下载文件 @@ -16,7 +17,7 @@ import { createReadStream } from 'fs'; import { access, stat } from 'fs/promises'; import { lookup, extension } from 'mime-types'; import { isProductPackageType } from '@/lib/material-type-mapper'; -import { isPrivateTaskDetail } from '@/lib/task-detail-privacy'; + import { resolveExternalImageDownloadSource } from '@/lib/external-image-assets'; import { resolveCertificateReportSource } from '@/lib/external-certificate-reports'; import { nodeReadableToWebStream } from '@/lib/node-readable-stream'; @@ -67,13 +68,13 @@ async function handleDownload(request: NextRequest) { try { // 查询素材 const material: any = await prisma.material.findUnique({ - where: { id: materialId, deletedAt: null }, + where: { accessScope: 'general', id: materialId, deletedAt: null }, include: { assets: true, }, }); - if (!material || isPrivateTaskDetail(material)) { + if (!material || isRestrictedMaterial(material)) { return errorResponse(API_ERROR.TASK_NOT_FOUND); } @@ -318,7 +319,7 @@ async function downloadStandardModelWhiteBackground( } const sku = await prisma.materialSku.findFirst({ - where: { + where: { material: { accessScope: 'general' }, id: skuId, materialId: material.id, deletedAt: null, diff --git a/app/api/external/maixiang-spu-assets/route.ts b/app/api/external/maixiang-spu-assets/route.ts index 492dc225..5d925ae8 100644 --- a/app/api/external/maixiang-spu-assets/route.ts +++ b/app/api/external/maixiang-spu-assets/route.ts @@ -276,7 +276,7 @@ export async function GET(request: NextRequest) { try { const searchOrConditions = await buildMaterialSearchOrConditions(trace.normalizedSpu) const materials = await prisma.material.findMany({ - where: { + where: { accessScope: 'general', deletedAt: null, ...(searchOrConditions ? { OR: searchOrConditions } : {}), materialType: { diff --git a/app/api/external/product-assets/route.ts b/app/api/external/product-assets/route.ts index 69c9a8bc..a19a80d5 100644 --- a/app/api/external/product-assets/route.ts +++ b/app/api/external/product-assets/route.ts @@ -1,4 +1,5 @@ -import { isPrivateTaskDetail } from '@/lib/task-detail-privacy'; +import { isRestrictedMaterial } from '@/lib/material-access-scope' + /** * 外部接口:产品全案素材查询和删除 * GET - 通过任务号查询素材详情 @@ -103,7 +104,7 @@ export async function GET(request: NextRequest) { // 查询素材 console.log('[external/product-assets] Querying material:', { taskNo, materialId }); const found: any = materialId ? await getMaterialById(materialId) : await getMaterialByTaskNo(taskNo as string); - const material = found && !isPrivateTaskDetail(found) ? found : null; + const material = found && !isRestrictedMaterial(found) ? found : null; console.log('[external/product-assets] Material found:', material ? { id: material.id, taskNo: material.taskNo, @@ -400,7 +401,7 @@ export async function DELETE(request: NextRequest) { try { // 查询素材 const found: any = await getMaterialByTaskNo(taskNo); - const material = found && !isPrivateTaskDetail(found) ? found : null; + const material = found && !isRestrictedMaterial(found) ? found : null; if (!material) { await logApiCall({ diff --git a/app/api/external/product-barcode-images/route.ts b/app/api/external/product-barcode-images/route.ts index 2038c68b..ef77544c 100644 --- a/app/api/external/product-barcode-images/route.ts +++ b/app/api/external/product-barcode-images/route.ts @@ -64,7 +64,7 @@ export async function GET(request: NextRequest) { assetType: 'sku-preview', material: { materialType: '任务-详情', - taskDetailPrivate: false, + taskDetailPrivate: false, accessScope: 'general', deletedAt: null, }, }, diff --git a/app/api/external/standard-model-sku-white-background/route.ts b/app/api/external/standard-model-sku-white-background/route.ts index fdd25134..056f96a6 100644 --- a/app/api/external/standard-model-sku-white-background/route.ts +++ b/app/api/external/standard-model-sku-white-background/route.ts @@ -291,7 +291,7 @@ async function handleSkuQuery(normalizedSkuName: string, logBase: LogBase, trace deletedAt: null, skuName: normalizedSkuName, material: { - is: { + is: { accessScope: 'general', materialType: '标准模型', deletedAt: null, }, @@ -415,7 +415,7 @@ async function handleSkuQuery(normalizedSkuName: string, logBase: LogBase, trace async function handleSpuQuery(normalizedSpu: string, logBase: LogBase, trace: TraceContext) { try { const material = await prisma.material.findFirst({ - where: { + where: { accessScope: 'general', productModel: normalizedSpu, materialType: '标准模型', deletedAt: null, diff --git a/app/api/external/standard-model-white-background/by-spu/route.ts b/app/api/external/standard-model-white-background/by-spu/route.ts index 6a111c29..a5b82d00 100644 --- a/app/api/external/standard-model-white-background/by-spu/route.ts +++ b/app/api/external/standard-model-white-background/by-spu/route.ts @@ -233,7 +233,7 @@ async function findDuplicateStandardModelSkuName(skuName: string, excludeMateria }, ...(excludeMaterialId ? { NOT: { materialId: excludeMaterialId } } : {}), material: { - is: { + is: { accessScope: 'general', materialType: '标准模型', deletedAt: null, }, @@ -299,7 +299,7 @@ async function createStandardModelSku(input: { skuName: string }) { const maxSortOrder = await prisma.materialSku.aggregate({ - where: { materialId: input.materialId }, + where: { material: { accessScope: 'general' }, materialId: input.materialId }, _max: { sortOrder: true }, }) @@ -325,7 +325,7 @@ async function ensureProductBarcodeBinding(input: { skuId: string }) { const existing = await prisma.materialSkuBarcode.findFirst({ - where: { + where: { sku: { material: { accessScope: 'general' } }, barcode: input.barcode, deletedAt: null, }, @@ -380,7 +380,7 @@ async function ensureProductBarcodeBinding(input: { } catch (error: any) { if (error?.code === 'P2002') { const current = await prisma.materialSkuBarcode.findFirst({ - where: { + where: { sku: { material: { accessScope: 'general' } }, barcode: input.barcode, deletedAt: null, }, @@ -429,7 +429,7 @@ async function resolveStandardModelTargetBySpu(input: { operatorUserId: string }): Promise { const matches = await prisma.material.findMany({ - where: { + where: { accessScope: 'general', productModel: { equals: input.spu, mode: 'insensitive', diff --git a/app/api/external/standard-model-white-background/route.ts b/app/api/external/standard-model-white-background/route.ts index f35382ff..9f52106d 100644 --- a/app/api/external/standard-model-white-background/route.ts +++ b/app/api/external/standard-model-white-background/route.ts @@ -301,7 +301,7 @@ export async function GET(request: NextRequest) { deletedAt: null, skuName: normalizedSkuName, material: { - is: { + is: { accessScope: 'general', materialType: '标准模型', deletedAt: null, }, @@ -500,7 +500,7 @@ async function handleSpuQuery( try { // 通过 productModel(SPU)查找标准模型素材 const material = await prisma.material.findFirst({ - where: { + where: { accessScope: 'general', productModel: normalizedSpu, materialType: '标准模型', deletedAt: null, @@ -642,7 +642,7 @@ async function getTaskDetailMaterialsBySpu(normalizedSpu: string) { where: { productModel: normalizedSpu, materialType: '任务-详情', - taskDetailPrivate: false, + taskDetailPrivate: false, accessScope: 'general', deletedAt: null, }, select: { @@ -743,7 +743,7 @@ async function handleTaskDetailSkuQuery( deletedAt: null, skuName: normalizedSkuName, material: { - is: { + is: { accessScope: 'general', materialType: '标准模型', deletedAt: null, }, diff --git a/app/api/external/video-assets/route.ts b/app/api/external/video-assets/route.ts index 57e87252..c8250d85 100644 --- a/app/api/external/video-assets/route.ts +++ b/app/api/external/video-assets/route.ts @@ -239,7 +239,7 @@ async function findVideoMaterials(keyword: string): Promise { where: { barcode: { equals: keyword, mode: 'insensitive' }, deletedAt: null, - sku: { deletedAt: null }, + sku: { material: { accessScope: 'general' }, deletedAt: null }, }, select: { sku: { select: { materialId: true } } }, }) @@ -250,7 +250,7 @@ async function findVideoMaterials(keyword: string): Promise { ) const materials = await prisma.material.findMany({ - where: { + where: { accessScope: 'general', id: { in: materialIds }, deletedAt: null, materialType: { in: VIDEO_MATERIAL_TYPES }, @@ -266,7 +266,7 @@ async function findVideoMaterials(keyword: string): Promise { // ── Layer 2: SKU-name contains match ────────────────────────────────── const skuRecords = await prisma.materialSku.findMany({ - where: { + where: { material: { accessScope: 'general' }, skuName: { contains: keyword, mode: 'insensitive' }, deletedAt: null, }, @@ -277,7 +277,7 @@ async function findVideoMaterials(keyword: string): Promise { const materialIds = Array.from(new Set(skuRecords.map((r) => r.materialId))) const materials = await prisma.material.findMany({ - where: { + where: { accessScope: 'general', id: { in: materialIds }, deletedAt: null, materialType: { in: VIDEO_MATERIAL_TYPES }, @@ -293,7 +293,7 @@ async function findVideoMaterials(keyword: string): Promise { // ── Layer 3: SPU (productModel) contains match ──────────────────────── const materials = await prisma.material.findMany({ - where: { + where: { accessScope: 'general', productModel: { contains: keyword, mode: 'insensitive' }, deletedAt: null, materialType: { in: VIDEO_MATERIAL_TYPES }, diff --git a/app/api/materials/[id]/assets/route.ts b/app/api/materials/[id]/assets/route.ts index 140a9a4c..64ac318c 100644 --- a/app/api/materials/[id]/assets/route.ts +++ b/app/api/materials/[id]/assets/route.ts @@ -1,3 +1,4 @@ +import { isRestrictedMaterial } from '@/lib/material-access-scope' /** * 素材资产管理接口 * GET - 获取资产列表 @@ -21,7 +22,7 @@ import { type MaterialAuthorizationUser, } from '@/lib/material-authorization'; import { isProductPackageType } from '@/lib/material-type-mapper'; -import { canAccessMaterialPrivacy, isPrivateTaskDetail, TASK_DETAIL_PRIVACY_SELECT, type TaskDetailPrivacyMaterial } from '@/lib/task-detail-privacy'; +import { canAccessMaterialPrivacy, TASK_DETAIL_PRIVACY_SELECT, type TaskDetailPrivacyMaterial } from '@/lib/task-detail-privacy'; type AssetRouteSessionUser = MaterialAuthorizationUser & { department?: string | null; @@ -32,7 +33,7 @@ async function canViewMaterial( user: AssetRouteSessionUser, material: { userId: string; materialType: string } & TaskDetailPrivacyMaterial, ) { - if (isPrivateTaskDetail(material)) return canAccessMaterialPrivacy(material, user.id); + if (isRestrictedMaterial(material)) return canAccessMaterialPrivacy(material, user.id); if (material.userId === user.id) { return true; } diff --git a/app/api/materials/[id]/route.ts b/app/api/materials/[id]/route.ts index 4c6ac108..e55f73aa 100644 --- a/app/api/materials/[id]/route.ts +++ b/app/api/materials/[id]/route.ts @@ -1,4 +1,5 @@ -import { canAccessMaterialPrivacy, isPrivateTaskDetail, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'; +import { isRestrictedMaterial } from '@/lib/material-access-scope' +import { canAccessMaterialPrivacy, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'; import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import path from 'path'; @@ -325,7 +326,7 @@ export async function GET( return NextResponse.json({ error: '素材不存在' }, { status: 404 }); } if (!(await canAccessMaterialPrivacy(material as any, (session.user as any).id))) { - return NextResponse.json({ error: '无权限查看该私密素材' }, { status: 403, headers: { 'Cache-Control': 'private, no-store' } }); + return NextResponse.json({ error: '无权限查看此素材' }, { status: 403, headers: { 'Cache-Control': 'private, no-store' } }); } let canAccessSource = false; @@ -413,11 +414,12 @@ export async function GET( taskDetailRequesterName: materialWithUser.taskDetailRequesterName || null, taskDetailDemandType: materialWithUser.taskDetailDemandType || null, taskDetailPrivate: materialWithUser.taskDetailPrivate === true, + accessScope: materialWithUser.accessScope || 'general', canEdit: true, }); } - if (!userIsSuperAdmin && !isPrivateTaskDetail(material as any)) { + if (!userIsSuperAdmin && !isRestrictedMaterial(material as any)) { const canView = await canUserViewMaterial( userDepartment, userRole, @@ -446,7 +448,7 @@ export async function GET( select: { canDownload: true }, }); if (userDownloadSetting?.canDownload) { - const canDownloadMaterial = isPrivateTaskDetail(material as any) || await canUserDownloadMaterial( + const canDownloadMaterial = isRestrictedMaterial(material as any) || await canUserDownloadMaterial( userDepartment, userRole, managedDepartment, @@ -498,6 +500,7 @@ export async function GET( taskDetailRequesterName: materialWithUser.taskDetailRequesterName || null, taskDetailDemandType: materialWithUser.taskDetailDemandType || null, taskDetailPrivate: materialWithUser.taskDetailPrivate === true, + accessScope: materialWithUser.accessScope || 'general', renderer: materialWithUser.renderer, authorName: displayAuthorName, // 使用处理后的作者名 previewUrl: materialWithUser.previewUrl, @@ -642,6 +645,7 @@ export async function PUT( ...(formData.has('taskDetailSourceType') ? { taskDetailSourceType: formData.get('taskDetailSourceType') as string | null } : {}), + ...(formData.has('accessScope') ? { accessScope: formData.get('accessScope') as string } : {}), ...(formData.has('taskDetailRequesterUserId') ? { taskDetailRequesterUserId: formData.get('taskDetailRequesterUserId') as string | null } : {}), @@ -687,6 +691,7 @@ export async function PUT( taskDetailSourceType: (result.material as any).taskDetailSourceType || null, taskDetailRequesterUserId: (result.material as any).taskDetailRequesterUserId || null, taskDetailRequesterName: (result.material as any).taskDetailRequesterName || null, + accessScope: (result.material as any).accessScope || 'general', taskStatus: result.material.taskStatus, taskFetchedAt: result.material.taskFetchedAt, isFullSet: Boolean((result.material as any).isFullSet), diff --git a/app/api/materials/[id]/skus/[skuId]/route.ts b/app/api/materials/[id]/skus/[skuId]/route.ts index 97721071..cdc732d1 100644 --- a/app/api/materials/[id]/skus/[skuId]/route.ts +++ b/app/api/materials/[id]/skus/[skuId]/route.ts @@ -11,6 +11,7 @@ import { getWhiteBackgroundRelativeDirectory, } from '@/lib/standard-model-white-background' import { canManageSkuMaterial } from '../authorization' +import { canAccessMaterialPrivacy, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy' function normalizeSkuName(value: string): string { return String(value || '').replace(/[^a-zA-Z0-9\-_.]/g, '').toUpperCase().trim() @@ -43,6 +44,21 @@ export async function GET( try { const { id: materialId, skuId } = params + const material = await prisma.material.findUnique({ + where: { id: materialId, deletedAt: null }, + select: TASK_DETAIL_PRIVACY_SELECT, + }) + if (!material) { + return NextResponse.json({ error: '素材不存在' }, { status: 404 }) + } + const session = await getServerSession(authOptions) + if (!(await canAccessMaterialPrivacy(material, (session?.user as any)?.id))) { + return NextResponse.json({ error: '无权限访问此素材' }, { + status: session?.user ? 403 : 401, + headers: { 'Cache-Control': 'private, no-store' }, + }) + } + const sku = await prisma.materialSku.findFirst({ where: { id: skuId, @@ -77,7 +93,7 @@ export async function GET( whiteBackgroundUploader: uploader, createdAt: sku.createdAt, updatedAt: sku.updatedAt, - }) + }, { headers: { 'Cache-Control': 'private, no-store' } }) } catch (error) { console.error('获取 SKU 详情失败:', error) return NextResponse.json({ error: '获取 SKU 详情失败' }, { status: 500 }) @@ -101,6 +117,7 @@ export async function PUT( include: { material: { select: { + id: true, userId: true, }, }, @@ -238,6 +255,7 @@ export async function DELETE( include: { material: { select: { + id: true, userId: true, }, }, diff --git a/app/api/materials/[id]/skus/authorization.ts b/app/api/materials/[id]/skus/authorization.ts index 47071154..0fe02b61 100644 --- a/app/api/materials/[id]/skus/authorization.ts +++ b/app/api/materials/[id]/skus/authorization.ts @@ -3,6 +3,9 @@ import { isSuperAdmin, isSystemAdmin, } from '@/lib/department-permission' +import { prisma } from '@/lib/prisma' +import { canAccessMaterialPrivacy, TASK_DETAIL_PRIVACY_SELECT, type TaskDetailPrivacyMaterial } from '@/lib/task-detail-privacy' +import { isRestrictedMaterial } from '@/lib/material-access-scope' export interface SkuRouteSessionUser { id: string @@ -12,15 +15,18 @@ export interface SkuRouteSessionUser { isSuperAdmin?: boolean | null } -export interface SkuRouteMaterial { +export interface SkuRouteMaterial extends TaskDetailPrivacyMaterial { + id: string userId: string materialType: string } export async function canManageSkuMaterial( user: SkuRouteSessionUser, - material: Pick, + material: Pick & Partial, ): Promise { + const stored = await prisma.material.findUnique({ where: { id: material.id }, select: TASK_DETAIL_PRIVACY_SELECT }) + if (!stored || !(await canAccessMaterialPrivacy(stored, user.id))) return false if (material.userId === user.id || isSystemAdmin(user.role) || user.isSuperAdmin === true) { return true } @@ -32,6 +38,9 @@ export async function canDownloadSkuMaterial( user: SkuRouteSessionUser, material: SkuRouteMaterial, ): Promise { + const stored = await prisma.material.findUnique({ where: { id: material.id }, select: TASK_DETAIL_PRIVACY_SELECT }) + if (!stored || !(await canAccessMaterialPrivacy(stored, user.id))) return false + if (isRestrictedMaterial(stored)) return true return canUserDownloadMaterial( user.department, user.role || 'USER', diff --git a/app/api/materials/download/route.ts b/app/api/materials/download/route.ts index b1ff4cf8..4ae4bb21 100644 --- a/app/api/materials/download/route.ts +++ b/app/api/materials/download/route.ts @@ -1,3 +1,4 @@ +import { isRestrictedMaterial } from '@/lib/material-access-scope' /** * 简单的下载路由 - 直接返回已打包好的zip文件 */ @@ -27,7 +28,7 @@ import { userHasVideoEarlyAccess, } from '@/lib/video-download-policy'; import { nodeReadableToWebStream } from '@/lib/node-readable-stream'; -import { canAccessMaterialPrivacy, isPrivateTaskDetail, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'; +import { canAccessMaterialPrivacy, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'; function normalizeStoredLocalPath(filePath: string) { return String(filePath || '').replace(/\\/g, '/'); @@ -101,7 +102,7 @@ export async function GET(request: NextRequest) { ); } if (!(await canAccessMaterialPrivacy(material, userId))) { - return NextResponse.json(createDownloadError(DownloadErrorCode.NO_PERMISSION, '无权限下载该私密素材'), { status: 403, headers: { 'Cache-Control': 'private, no-store' } }); + return NextResponse.json(createDownloadError(DownloadErrorCode.NO_PERMISSION, '无权限下载此素材'), { status: 403, headers: { 'Cache-Control': 'private, no-store' } }); } const videoDownloadAvailability = getVideoDownloadAvailability( @@ -127,7 +128,7 @@ export async function GET(request: NextRequest) { // 超级管理员不受限制 const { isSuperAdmin } = await import('@/lib/department-permission'); if (!(await isSuperAdmin(userId))) { - const canDownload = isPrivateTaskDetail(material) || await canUserDownloadMaterial( + const canDownload = isRestrictedMaterial(material) || await canUserDownloadMaterial( userDepartment, userRole, managedDepartment, diff --git a/app/api/materials/facets/route.ts b/app/api/materials/facets/route.ts index f41fdb5e..21c7a969 100644 --- a/app/api/materials/facets/route.ts +++ b/app/api/materials/facets/route.ts @@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server' import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' import { prisma } from '@/lib/prisma' +import { getMaterialFacetsCache, setMaterialFacetsCache } from '@/lib/material-facets-cache' import { buildMaterialWhereFromSearchParams, createMaterialQueryContext, @@ -81,35 +82,13 @@ function toMaterialTypeItems(rows: any[]) { // ===== 服务端内存缓存 ===== // facets 的 7 条 SQL 在大库上可耗时 20 秒以上(尤其 loadMonths 的全表扫描)。 // 相同权限上下文 + 相同筛选参数的结果在 TTL 内直接返回缓存。 -const FACETS_CACHE_TTL_MS = 5 * 60 * 1000 // 5 分钟 -const facetsCache = new Map() -function buildFacetsCacheKey(searchParams: URLSearchParams, user: any): string { - // 以角色+部门+筛选参数为缓存键:同权限的人共享同一份结果 - const role = String(user?.role || 'USER') - const dept = String(user?.department || '') - const managed = String(user?.managedDepartment || '') - const filterKey = searchParams.toString() - return `${role}|${dept}|${managed}|${filterKey}` -} - -function getFacetsFromCache(key: string): any | null { - const entry = facetsCache.get(key) - if (!entry) return null - if (Date.now() > entry.expiresAt) { - facetsCache.delete(key) - return null - } - return entry.data -} - -function setFacetsCache(key: string, data: any) { - // 简单容量上限:最多保留 200 个不同筛选组合的缓存 - if (facetsCache.size > 200) { - const oldest = facetsCache.keys().next().value - if (oldest) facetsCache.delete(oldest) - } - facetsCache.set(key, { data, expiresAt: Date.now() + FACETS_CACHE_TTL_MS }) +function buildFacetsCacheKey(searchParams: URLSearchParams, user: any, context: Awaited>): string { + return JSON.stringify([ + user.id, context.isSuperAdmin, context.expandedViewableTypes, + context.canAccessPrivateTaskDetails === true, context.canAccessOperationsGMaterials === true, + searchParams.toString(), + ]) } export async function GET(request: NextRequest) { @@ -125,14 +104,13 @@ export async function GET(request: NextRequest) { const searchParams = request.nextUrl.searchParams const user = session.user as any - // 缓存命中:直接返回,跳过全部 7 条 SQL - const cacheKey = buildFacetsCacheKey(searchParams, user) - const cached = getFacetsFromCache(cacheKey) - if (cached) { - return NextResponse.json(cached) - } - + // 每次确认当前人员权限;仅复用该账号和权限范围内的聚合结果。 const context = await createMaterialQueryContext(searchParams, user) + const cacheKey = buildFacetsCacheKey(searchParams, user, context) + const cached = getMaterialFacetsCache(cacheKey) + if (cached) { + return NextResponse.json(cached, { headers: { 'Cache-Control': 'private, no-store' } }) + } const buildWhere = async (exclude?: MaterialFilterDimension) => buildMaterialWhereFromSearchParams(searchParams, user, { @@ -256,9 +234,9 @@ export async function GET(request: NextRequest) { } // 写入缓存,供同权限用户在 TTL 内复用 - setFacetsCache(cacheKey, responseData) + setMaterialFacetsCache(cacheKey, responseData) - return NextResponse.json(responseData) + return NextResponse.json(responseData, { headers: { 'Cache-Control': 'private, no-store' } }) } catch (error) { if (error instanceof MaterialQueryError) { return NextResponse.json( diff --git a/app/api/materials/like/route.ts b/app/api/materials/like/route.ts index b5077396..11e4d325 100644 --- a/app/api/materials/like/route.ts +++ b/app/api/materials/like/route.ts @@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; import { prisma } from '@/lib/prisma'; +import { canAccessMaterialPrivacy, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'; // POST - 点赞/取消点赞 export async function POST(request: NextRequest) { @@ -19,6 +20,12 @@ export async function POST(request: NextRequest) { } const userId = (session.user as any).id; + const material = await prisma.material.findFirst({ + where: { id: materialId, deletedAt: null }, select: TASK_DETAIL_PRIVACY_SELECT, + }); + if (!material || !(await canAccessMaterialPrivacy(material, userId))) { + return NextResponse.json({ error: '素材不存在或无权访问' }, { status: 403 }); + } // 检查是否已点赞 const existingLike = await prisma.materialLike.findFirst({ diff --git a/app/api/materials/restore/route.ts b/app/api/materials/restore/route.ts index 729e1252..33beea39 100644 --- a/app/api/materials/restore/route.ts +++ b/app/api/materials/restore/route.ts @@ -1,3 +1,5 @@ +import { invalidateMaterialFacetsCache } from '@/lib/material-facets-cache' +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; @@ -32,6 +34,10 @@ export async function POST(request: NextRequest) { return NextResponse.json({ error: '素材不存在' }, { status: 404 }); } + if (material.accessScope === 'operations_g' && !(await canAccessOperationsGMaterials((session.user as any).id))) { + return NextResponse.json({ error: '无权限操作运营中心 G 专属素材' }, { status: 403 }); + } + const restoredTaskNo = getOriginalTaskNo((material as any).taskNo); if (restoredTaskNo && restoredTaskNo !== (material as any).taskNo) { const existingMaterial = await prisma.material.findFirst({ @@ -44,12 +50,13 @@ export async function POST(request: NextRequest) { id: true, productModel: true, materialType: true, + accessScope: true, }, }); if (existingMaterial) { return NextResponse.json( - { error: `恢复失败:原任务号 ${restoredTaskNo} 已被素材 ${existingMaterial.productModel}(${existingMaterial.materialType})占用` }, + { error: existingMaterial.accessScope === 'operations_g' ? `恢复失败:原任务号 ${restoredTaskNo} 已被占用` : `恢复失败:原任务号 ${restoredTaskNo} 已被素材 ${existingMaterial.productModel}(${existingMaterial.materialType})占用` }, { status: 409 } ); } @@ -94,6 +101,7 @@ export async function POST(request: NextRequest) { material: { select: { productModel: true, + accessScope: true, }, }, }, @@ -102,7 +110,7 @@ export async function POST(request: NextRequest) { if (conflictingSkus.length > 0) { const conflictSummary = conflictingSkus - .map((item) => `${item.skuName}(${item.material.productModel})`) + .map((item) => item.material.accessScope === 'operations_g' ? item.skuName : `${item.skuName}(${item.material.productModel})`) .join('、'); return NextResponse.json( @@ -156,6 +164,7 @@ export async function POST(request: NextRequest) { }, }); + invalidateMaterialFacetsCache(); return NextResponse.json({ message: '恢复成功' }); } catch (error: any) { // 兼容旧版本数据库(没有 deletedAt 字段) diff --git a/app/api/materials/route.ts b/app/api/materials/route.ts index 0e4b2a6e..97f44a9e 100644 --- a/app/api/materials/route.ts +++ b/app/api/materials/route.ts @@ -1,4 +1,7 @@ -import { canAccessMaterialPrivacy, isPrivateTaskDetail, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'; +import { invalidateMaterialFacetsCache } from '@/lib/material-facets-cache' +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' +import { isRestrictedMaterial } from '@/lib/material-access-scope' +import { canAccessMaterialPrivacy, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'; import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; @@ -172,7 +175,7 @@ export async function GET(request: NextRequest) { return NextResponse.json({ material: null }); } if (!(await canAccessMaterialPrivacy(material, (session.user as any).id))) { - return NextResponse.json({ error: '无权限查看该私密素材' }, { status: 403, headers: { 'Cache-Control': 'private, no-store' } }); + return NextResponse.json({ error: '无权限查看此素材' }, { status: 403, headers: { 'Cache-Control': 'private, no-store' } }); } // 权限检查:分享页使用 /api/materials/share?id=...,普通素材接口不接受 share 参数绕过权限。 @@ -183,7 +186,7 @@ export async function GET(request: NextRequest) { // 超级管理员不受限制 const { isSuperAdmin, canUserViewMaterial } = await import('@/lib/department-permission'); - if (!isPrivateTaskDetail(material) && !(await isSuperAdmin(userId))) { + if (!isRestrictedMaterial(material) && !(await isSuperAdmin(userId))) { const canView = await canUserViewMaterial( userDepartment, userRole, @@ -947,6 +950,10 @@ export async function DELETE(request: NextRequest) { const userId = (session.user as any).id; + if (material.accessScope === 'operations_g' && !(await canAccessOperationsGMaterials(userId))) { + return NextResponse.json({ error: '无权限操作运营中心 G 专属素材' }, { status: 403 }); + } + // 软删除 if (!permanent) { const deletedAt = new Date(); @@ -992,6 +999,7 @@ export async function DELETE(request: NextRequest) { }, }); + invalidateMaterialFacetsCache(); return NextResponse.json({ message: '删除成功(可恢复),文件已保留' }); } diff --git a/app/api/materials/share/route.ts b/app/api/materials/share/route.ts index 2e6fe9a0..6d30799a 100644 --- a/app/api/materials/share/route.ts +++ b/app/api/materials/share/route.ts @@ -1,4 +1,5 @@ -import { canAccessMaterialPrivacy, isPrivateTaskDetail, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'; +import { isRestrictedMaterial } from '@/lib/material-access-scope' +import { canAccessMaterialPrivacy, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'; import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; @@ -168,7 +169,7 @@ export async function GET(request: NextRequest) { return NextResponse.json({ error: '素材不存在' }, { status: 404 }); } if (!(await canAccessMaterialPrivacy(material as any, userId))) { - return NextResponse.json({ error: '请登录有权限的账号查看该私密素材' }, { status: userId ? 403 : 401, headers: { 'Cache-Control': 'private, no-store' } }); + return NextResponse.json({ error: '请登录有权限的账号查看此素材' }, { status: userId ? 403 : 401, headers: { 'Cache-Control': 'private, no-store' } }); } const videoPreviewPolicy = getVideoPreviewPolicyFields( @@ -303,7 +304,7 @@ export async function GET(request: NextRequest) { if (hasSystemAdminPermission(currentUser.role, Boolean(currentUser.isSuperAdmin))) { canAccessSource = true; } else if (currentUser.canDownload) { - const canDownloadMaterial = isPrivateTaskDetail(material as any) || await canUserDownloadMaterial( + const canDownloadMaterial = isRestrictedMaterial(material as any) || await canUserDownloadMaterial( currentUser.department, currentUser.role, currentUser.managedDepartment, @@ -373,7 +374,7 @@ export async function GET(request: NextRequest) { isAiGenerated: Boolean((material as any).isAiGenerated), taskDetailSourceType: (material as any).taskDetailSourceType || null, taskDetailDemandType: (material as any).taskDetailDemandType || null, - taskDetailPrivate: isPrivateTaskDetail(material as any), + taskDetailPrivate: (material as any).taskDetailPrivate === true, zipFileSize: material.zipFileSize.toString(), displayImages: parseDisplayImages(material.displayImages || null), isLiked, diff --git a/app/api/materials/transcode/route.ts b/app/api/materials/transcode/route.ts index 4814dbd6..b0cc3ee0 100644 --- a/app/api/materials/transcode/route.ts +++ b/app/api/materials/transcode/route.ts @@ -1,3 +1,4 @@ +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' // 视频转码API - 完整版本(支持自动恢复) import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; @@ -37,6 +38,28 @@ function rateLimitResponse(retryAfter: number) { ); } +async function getOrganizationQueueStatus(canAccessG: boolean) { + const status = transcodeQueue.getStatus(); + if (canAccessG) return status; + const ids = [...status.waiting, ...status.processingIds]; + const materials = ids.length ? await prisma.material.findMany({ + where: { id: { in: ids }, accessScope: 'general' }, + select: { id: true }, + }) : []; + const visibleIds = new Set(materials.map((material) => material.id)); + const waiting = status.waiting.filter((id) => visibleIds.has(id)); + const processingIds = status.processingIds.filter((id) => visibleIds.has(id)); + return { + ...status, + waiting, + processingIds, + queueLength: waiting.length, + processingCount: processingIds.length, + progress: new Map(Array.from(status.progress).filter(([id]) => visibleIds.has(id))), + stages: new Map(Array.from(status.stages).filter(([id]) => visibleIds.has(id))), + }; +} + // GET - 查询转码状态 export async function GET(request: NextRequest) { try { @@ -71,6 +94,7 @@ export async function GET(request: NextRequest) { id: true, userId: true, materialType: true, + accessScope: true, videoProcessingStatus: true, videoPreview540Url: true, videoPreviewClipUrl: true, @@ -78,7 +102,7 @@ export async function GET(request: NextRequest) { videoDuration: true, transcodeLastError: true, transcodeAttempts: true, - } as any, + }, }); if (!material) { @@ -87,8 +111,12 @@ export async function GET(request: NextRequest) { { status: 404 } ); } + const canAccessG = await canAccessOperationsGMaterials(sessionUser.id); + if (material.accessScope === 'operations_g' && !canAccessG) { + return NextResponse.json({ error: '无权限访问此素材' }, { status: 403, headers: { 'Cache-Control': 'private, no-store' } }); + } - if (!isSystemAdministrator && (material as any).userId !== sessionUser.id) { + if (material.accessScope !== 'operations_g' && !isSystemAdministrator && material.userId !== sessionUser.id) { const canView = await canUserViewMaterial( sessionUser.department, sessionUser.role, @@ -102,7 +130,7 @@ export async function GET(request: NextRequest) { } // 获取转码队列状态 - const queueStatus = transcodeQueue.getStatus(); + const queueStatus = await getOrganizationQueueStatus(canAccessG); const isProcessing = queueStatus.processingIds.includes(materialId); const waitingIndex = queueStatus.waiting.findIndex(id => id === materialId); const waitingTotal = queueStatus.waiting.length; @@ -182,9 +210,10 @@ export async function POST(request: NextRequest) { videoCoverUrl: true, videoProcessingStatus: true, materialType: true, + accessScope: true, transcodeLeaseToken: true, transcodeLeaseExpiresAt: true, - } as any, + }, }); if (!material) { @@ -194,6 +223,11 @@ export async function POST(request: NextRequest) { ); } + const canAccessG = await canAccessOperationsGMaterials(sessionUser.id); + if (material.accessScope === 'operations_g' && !canAccessG) { + return NextResponse.json({ error: '无权限操作此素材' }, { status: 403 }); + } + if (!isSystemAdministrator && (material as any).userId !== String(sessionUser.id || '')) { return NextResponse.json({ error: '只能启动自己素材的转码任务' }, { status: 403 }); } @@ -252,7 +286,9 @@ export async function POST(request: NextRequest) { console.log(`[Transcode] Task queued for material ${normalizedMaterialId}`); - const queueStatus = transcodeQueue.getStatus(); + const queueStatus = isSystemAdministrator + ? await getOrganizationQueueStatus(canAccessG) + : transcodeQueue.getStatus(); return NextResponse.json({ message: '转码任务已进入后台队列', materialId: normalizedMaterialId, diff --git a/app/api/materials/update/route.ts b/app/api/materials/update/route.ts index 59aab30b..25f44636 100644 --- a/app/api/materials/update/route.ts +++ b/app/api/materials/update/route.ts @@ -69,6 +69,7 @@ export async function PUT(request: NextRequest) { ...(formData.has('taskDetailSourceType') ? { taskDetailSourceType: formData.get('taskDetailSourceType') as string | null } : {}), + ...(formData.has('accessScope') ? { accessScope: formData.get('accessScope') as string } : {}), ...(formData.has('taskDetailRequesterUserId') ? { taskDetailRequesterUserId: formData.get('taskDetailRequesterUserId') as string | null } : {}), @@ -120,6 +121,7 @@ export async function PUT(request: NextRequest) { taskDetailSourceType: (result.material as any).taskDetailSourceType || null, taskDetailRequesterUserId: (result.material as any).taskDetailRequesterUserId || null, taskDetailRequesterName: (result.material as any).taskDetailRequesterName || null, + accessScope: (result.material as any).accessScope || 'general', }; return NextResponse.json( diff --git a/app/api/materials/upload/3d-original/init/route.ts b/app/api/materials/upload/3d-original/init/route.ts index 4aee92c0..997e2f68 100644 --- a/app/api/materials/upload/3d-original/init/route.ts +++ b/app/api/materials/upload/3d-original/init/route.ts @@ -1,3 +1,4 @@ +import { MaterialAccessScopeError, resolveMaterialUploadAccessScope } from '@/lib/material-organization-access' import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; @@ -15,6 +16,7 @@ export async function POST(request: NextRequest) { } const body = await request.json(); + const accessScope = await resolveMaterialUploadAccessScope(body.accessScope, (session.user as any).id) const { taskNo, dingtalkApprovalNo, productModel, categoryName, sceneName, platformName, productCategoryName } = body; // 验证必填字段 @@ -36,12 +38,12 @@ export async function POST(request: NextRequest) { const existingMaterial = await prisma.material.findFirst({ where: { taskNo, deletedAt: null }, - select: { id: true, productModel: true, materialType: true }, + select: { id: true, productModel: true, materialType: true, accessScope: true }, }); if (existingMaterial) { return NextResponse.json( - { error: `任务号 ${taskNo} 已存在,对应素材:${existingMaterial.productModel}(${existingMaterial.materialType})` }, + { error: existingMaterial.accessScope === 'operations_g' ? `任务号 ${taskNo} 已存在` : `任务号 ${taskNo} 已存在,对应素材:${existingMaterial.productModel}(${existingMaterial.materialType})` }, { status: 400 } ); } @@ -69,6 +71,7 @@ export async function POST(request: NextRequest) { // 创建素材记录(使用临时预览图) const material = await prisma.material.create({ data: { + accessScope, materialType: '任务-3D原图', productModel, categoryName, @@ -91,6 +94,9 @@ export async function POST(request: NextRequest) { materialId: material.id, }); } catch (error: any) { + if (error instanceof MaterialAccessScopeError) { + return NextResponse.json({ error: error.message, success: false }, { status: error.status }) + } console.error('[3D Original Init Error]', error); // 捕获 Prisma 唯一约束错误(任务号重复) diff --git a/app/api/materials/upload/ai-original/init/route.ts b/app/api/materials/upload/ai-original/init/route.ts index e4e98838..e567896a 100644 --- a/app/api/materials/upload/ai-original/init/route.ts +++ b/app/api/materials/upload/ai-original/init/route.ts @@ -1,3 +1,4 @@ +import { MaterialAccessScopeError, resolveMaterialUploadAccessScope } from '@/lib/material-organization-access' import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; @@ -15,6 +16,7 @@ export async function POST(request: NextRequest) { } const body = await request.json(); + const accessScope = await resolveMaterialUploadAccessScope(body.accessScope, (session.user as any).id) const { taskNo, dingtalkApprovalNo, productModel, categoryName, sceneName, platformName, productCategoryName } = body; // 验证必填字段 @@ -40,12 +42,12 @@ export async function POST(request: NextRequest) { taskNo, deletedAt: null, // 只检查未删除的素材 }, - select: { id: true, productModel: true, materialType: true }, + select: { id: true, productModel: true, materialType: true, accessScope: true }, }); if (existingMaterial) { return NextResponse.json( - { error: `任务号 ${taskNo} 已存在,对应素材:${existingMaterial.productModel}(${existingMaterial.materialType})` }, + { error: existingMaterial.accessScope === 'operations_g' ? `任务号 ${taskNo} 已存在` : `任务号 ${taskNo} 已存在,对应素材:${existingMaterial.productModel}(${existingMaterial.materialType})` }, { status: 400 } ); } @@ -73,6 +75,7 @@ export async function POST(request: NextRequest) { // 创建素材记录(使用临时预览图) const material = await prisma.material.create({ data: { + accessScope, materialType: '任务-AI原图', productModel, categoryName, @@ -95,6 +98,9 @@ export async function POST(request: NextRequest) { materialId: material.id, }); } catch (error: any) { + if (error instanceof MaterialAccessScopeError) { + return NextResponse.json({ error: error.message, success: false }, { status: error.status }) + } console.error('[AI Original Init Error]', error); // 捕获 Prisma 唯一约束错误(任务号重复) diff --git a/app/api/materials/upload/certificate-report/complete/route.ts b/app/api/materials/upload/certificate-report/complete/route.ts index fe6b615b..3a1107fe 100644 --- a/app/api/materials/upload/certificate-report/complete/route.ts +++ b/app/api/materials/upload/certificate-report/complete/route.ts @@ -1,3 +1,7 @@ +import { invalidateMaterialFacetsCache } from '@/lib/material-facets-cache' +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' +import { deleteFileIfUnreferenced } from '@/lib/file-cleanup' +import { isRestrictedMaterial } from '@/lib/material-access-scope' import { NextRequest, NextResponse } from 'next/server' import { getServerSession } from 'next-auth' import { lookup as mimeTypeLookup } from 'mime-types' @@ -51,6 +55,7 @@ interface CertificateReportCompletionSnapshot { id: string userId: string materialType: string + accessScope?: string | null taskStatus: string | null previewUrl: string zipFileName: string @@ -133,6 +138,7 @@ async function readCertificateReportCompletionSnapshot( id: true, userId: true, materialType: true, + accessScope: true, taskStatus: true, previewUrl: true, zipFileName: true, @@ -260,6 +266,7 @@ export async function POST(request: NextRequest) { id: true, userId: true, materialType: true, + accessScope: true, deletedAt: true, }, }) @@ -269,6 +276,9 @@ export async function POST(request: NextRequest) { if (initialMaterial.userId !== userId) { return NextResponse.json({ error: '无权限操作此素材' }, { status: 403 }) } + if (initialMaterial.accessScope === 'operations_g' && !(await canAccessOperationsGMaterials(userId))) { + return NextResponse.json({ error: '无权限操作此素材' }, { status: 403 }) + } if (initialMaterial.materialType !== CERTIFICATE_REPORT_MATERIAL_TYPE) { return NextResponse.json({ error: '素材类型不匹配' }, { status: 400 }) } @@ -389,6 +399,7 @@ export async function POST(request: NextRequest) { targetRelativePath, contentType, item.actualSize, + isRestrictedMaterial(material) ? materialId : undefined, ) uploadedAssetUrls.push(uploadedUrl) assetRecords.push({ @@ -415,7 +426,7 @@ export async function POST(request: NextRequest) { 'preview', `report-preview-${Date.now()}-${safeFileName.replace(/\.pdf$/i, '.jpg')}`, ) - nextPreviewUrl = await uploadPublicDisplayToS3(previewBuffer, previewPath, 'image/jpeg') + nextPreviewUrl = await uploadPublicDisplayToS3(previewBuffer, previewPath, 'image/jpeg', isRestrictedMaterial(material) ? materialId : undefined) previewUrlToCleanup = nextPreviewUrl await unlink(previewResult.previewPath).catch(() => undefined) } @@ -455,6 +466,7 @@ export async function POST(request: NextRequest) { } }) materialCommitted = true + invalidateMaterialFacetsCache() // 只有 completed 事务确认后才消费源上传会话。清理失败不能反向删除正式资产。 await cleanupTempFiles(tempFiles, uploadIds).catch((cleanupError) => { diff --git a/app/api/materials/upload/certificate-report/init/route.ts b/app/api/materials/upload/certificate-report/init/route.ts index 00b6210e..697fe931 100644 --- a/app/api/materials/upload/certificate-report/init/route.ts +++ b/app/api/materials/upload/certificate-report/init/route.ts @@ -1,3 +1,4 @@ +import { MaterialAccessScopeError, resolveMaterialUploadAccessScope } from '@/lib/material-organization-access' import { NextRequest, NextResponse } from 'next/server' import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' @@ -13,6 +14,7 @@ export async function POST(request: NextRequest) { } const body = await request.json() + const accessScope = await resolveMaterialUploadAccessScope(body.accessScope, (session.user as any).id) const productModel = String(body.productModel || '').trim() const reportTitle = normalizeReportTitle(body.reportTitle) const productCategoryName = String(body.productCategoryName || '').trim() @@ -49,6 +51,7 @@ export async function POST(request: NextRequest) { const material = await prisma.material.create({ data: { + accessScope, materialType: CERTIFICATE_REPORT_MATERIAL_TYPE, productModel, reportTitle, @@ -73,6 +76,9 @@ export async function POST(request: NextRequest) { materialId: material.id, }) } catch (error: any) { + if (error instanceof MaterialAccessScopeError) { + return NextResponse.json({ error: error.message, success: false }, { status: error.status }) + } console.error('[Certificate Report Init Error]', error) return NextResponse.json({ error: error.message || '初始化失败' }, { status: 500 }) } diff --git a/app/api/materials/upload/product-package/abort/route.ts b/app/api/materials/upload/product-package/abort/route.ts index 7faf8ca5..1f06409b 100644 --- a/app/api/materials/upload/product-package/abort/route.ts +++ b/app/api/materials/upload/product-package/abort/route.ts @@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server' import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' import { prisma } from '@/lib/prisma' +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' import { getOwnedUploadSession, isSafeUploadId, @@ -93,6 +94,7 @@ export async function POST(req: NextRequest) { id: true, userId: true, materialType: true, + accessScope: true, }, }) @@ -103,6 +105,9 @@ export async function POST(req: NextRequest) { if (material.userId !== userId) { return NextResponse.json({ success: false, error: '无权限操作此素材' }, { status: 403 }) } + if (material.accessScope === 'operations_g' && !(await canAccessOperationsGMaterials(userId))) { + return NextResponse.json({ success: false, error: '无权限操作此素材' }, { status: 403 }) + } if (material.materialType !== '任务-详情') { return NextResponse.json({ success: true, deleted: false, reason: 'not_task_detail' }) diff --git a/app/api/materials/upload/product-package/complete/route.ts b/app/api/materials/upload/product-package/complete/route.ts index b994c316..6bdfb43f 100644 --- a/app/api/materials/upload/product-package/complete/route.ts +++ b/app/api/materials/upload/product-package/complete/route.ts @@ -1,3 +1,4 @@ +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' /** * 任务-详情上传完成接口(改造版) * POST - 打包文件、生成预览图、保存资产信息 @@ -65,6 +66,7 @@ export async function POST(request: NextRequest) { taskDetailSourceType: true, taskDetailDemandType: true, taskDetailPrivate: true, + accessScope: true, zipFilePath: true, _count: { select: { assets: true } }, }, @@ -77,6 +79,9 @@ export async function POST(request: NextRequest) { ) } + if (material.accessScope === 'operations_g' && !(await canAccessOperationsGMaterials((session.user as any).id))) { + return NextResponse.json({ success: false, error: '无权限操作此素材' }, { status: 403 }); + } if (material.userId !== (session.user as any).id) { return NextResponse.json( { success: false, error: '无权限操作此素材' }, @@ -109,6 +114,7 @@ export async function POST(request: NextRequest) { normalizeTaskDetailPrivacyFields({ taskDetailDemandType: material.taskDetailDemandType, taskDetailPrivate: material.taskDetailPrivate, + accessScope: material.accessScope, }) } catch (error) { return NextResponse.json( diff --git a/app/api/materials/upload/product-package/init/route.ts b/app/api/materials/upload/product-package/init/route.ts index feaa048a..2934c27e 100644 --- a/app/api/materials/upload/product-package/init/route.ts +++ b/app/api/materials/upload/product-package/init/route.ts @@ -1,3 +1,4 @@ +import { MaterialAccessScopeError, resolveMaterialUploadAccessScope } from '@/lib/material-organization-access' /** * 任务-详情上传初始化接口 * POST - 创建素材记录,返回上传配置 @@ -25,6 +26,7 @@ export async function POST(request: NextRequest) { } const body = await request.json(); + const accessScope = await resolveMaterialUploadAccessScope(body.accessScope, (session.user as any).id) const { taskNo, dingtalkApprovalNo, @@ -148,6 +150,7 @@ export async function POST(request: NextRequest) { // 创建素材记录(不写入taskNo,上传完成后再写入) const material: any = await prisma.material.create({ data: { + accessScope, // taskNo: 不写入,上传完成后再写入 productModel, categoryName, @@ -182,6 +185,9 @@ export async function POST(request: NextRequest) { }, }); } catch (error) { + if (error instanceof MaterialAccessScopeError) { + return NextResponse.json({ error: error.message, success: false }, { status: error.status }) + } console.error('[product-package/init] error:', error); const errorMessage = error instanceof Error ? error.message : String(error); const errorStack = error instanceof Error ? error.stack : undefined; diff --git a/app/api/materials/upload/real-photo/init/route.ts b/app/api/materials/upload/real-photo/init/route.ts index a602be19..2f51112e 100644 --- a/app/api/materials/upload/real-photo/init/route.ts +++ b/app/api/materials/upload/real-photo/init/route.ts @@ -1,3 +1,4 @@ +import { MaterialAccessScopeError, resolveMaterialUploadAccessScope } from '@/lib/material-organization-access' import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; @@ -15,6 +16,7 @@ export async function POST(request: NextRequest) { } const body = await request.json(); + const accessScope = await resolveMaterialUploadAccessScope(body.accessScope, (session.user as any).id) const { taskNo, dingtalkApprovalNo, productModel, categoryName, sceneName, platformName, productCategoryName } = body; // 验证必填字段 @@ -40,12 +42,12 @@ export async function POST(request: NextRequest) { taskNo, deletedAt: null, // 只检查未删除的素材 }, - select: { id: true, productModel: true, materialType: true }, + select: { id: true, productModel: true, materialType: true, accessScope: true }, }); if (existingMaterial) { return NextResponse.json( - { error: `任务号 ${taskNo} 已存在,对应素材:${existingMaterial.productModel}(${existingMaterial.materialType})` }, + { error: existingMaterial.accessScope === 'operations_g' ? `任务号 ${taskNo} 已存在` : `任务号 ${taskNo} 已存在,对应素材:${existingMaterial.productModel}(${existingMaterial.materialType})` }, { status: 400 } ); } @@ -73,6 +75,7 @@ export async function POST(request: NextRequest) { // 创建素材记录(使用临时预览图) const material = await prisma.material.create({ data: { + accessScope, materialType: '任务-实拍原图', productModel, categoryName, @@ -95,6 +98,9 @@ export async function POST(request: NextRequest) { materialId: material.id, }); } catch (error: any) { + if (error instanceof MaterialAccessScopeError) { + return NextResponse.json({ error: error.message, success: false }, { status: error.status }) + } console.error('[Real Photo Init Error]', error); // 捕获 Prisma 唯一约束错误(任务号重复) diff --git a/app/api/materials/upload/route.ts b/app/api/materials/upload/route.ts index 4ad2f2f5..9cdc8010 100644 --- a/app/api/materials/upload/route.ts +++ b/app/api/materials/upload/route.ts @@ -1,3 +1,5 @@ +import { MaterialAccessScopeError, resolveMaterialUploadAccessScope, canAccessOperationsGMaterials } from '@/lib/material-organization-access' +import { invalidateMaterialFacetsCache } from '@/lib/material-facets-cache' // 素材上传API - 支持多种素材类型 import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; @@ -251,7 +253,7 @@ function createUploadSuccessResponse(material: any, status = 201, replayed = fal } async function findOwnedMaterialByUploadId(uploadId: string, userId: string) { - return prisma.material.findFirst({ + const material = await prisma.material.findFirst({ // uploadId 的唯一性只覆盖未软删素材。隔离/软删记录不得被当成幂等 // 成功返回,否则用户会拿到已不可见或已判坏的旧记录。 where: { uploadId, userId, deletedAt: null }, @@ -261,6 +263,8 @@ async function findOwnedMaterialByUploadId(uploadId: string, userId: string) { }, }, }); + if (material?.accessScope === 'operations_g' && !(await canAccessOperationsGMaterials(userId))) return null; + return material; } function requiresCanonicalSourceValidation(materialType: unknown): boolean { @@ -449,6 +453,9 @@ export async function POST(request: NextRequest) { const formData = await request.formData(); // 必须在任何 arrayBuffer、Sharp、S3 或数据库写入前完成统一校验。 validateMaterialUploadFormData(formData); + const accessScope = await resolveMaterialUploadAccessScope(formData.get('accessScope'), (session.user as any).id); + attemptedMaterialId = randomUUID(); + const protectedMaterialId = accessScope === 'operations_g' ? attemptedMaterialId : undefined; const previewImage = formData.get('previewImage') as File | null; // 第一张预览图(主预览图) const previewImages = formData.getAll('previewImages') as File[]; // 其他预览图(作为展示图) const displayImage = formData.get('displayImage') as File | null; @@ -780,6 +787,7 @@ export async function POST(request: NextRequest) { compressedBuffer, buildMaterialPublicDisplayPath(filename), 'image/webp', + protectedMaterialId, ); uploadedFileUrls.push(previewUrl); // 记录已上传的文件,用于失败时清理 console.log('[Upload] Preview image uploaded:', previewUrl); @@ -821,6 +829,7 @@ export async function POST(request: NextRequest) { compressedBuffer, buildMaterialPublicDisplayPath(filename), 'image/webp', + protectedMaterialId, ); uploadedFileUrls.push(url); // 记录已上传的文件,用于失败时清理 console.log(`[Upload] Preview image ${index + 2} uploaded:`, url); @@ -846,6 +855,7 @@ export async function POST(request: NextRequest) { sliceBuffer, buildMaterialPublicDisplayPath(filename), 'image/webp', + protectedMaterialId, ); displayImages.push(url); uploadedFileUrls.push(url); // 记录已上传的文件,用于失败时清理 @@ -874,6 +884,7 @@ export async function POST(request: NextRequest) { buffer, buildMaterialPublicDisplayPath(filename), image.type, + protectedMaterialId, ); displayImages.push(url); uploadedFileUrls.push(url); // 记录已上传的文件,用于失败时清理 @@ -904,6 +915,7 @@ export async function POST(request: NextRequest) { buffer, buildMaterialPublicDisplayPath(filename), image.type, + protectedMaterialId, ); displayImages.push(url); uploadedFileUrls.push(url); // 记录已上传的文件,用于失败时清理 @@ -1060,7 +1072,7 @@ export async function POST(request: NextRequest) { console.log('[Upload] PDF文件路径:', zipFilePath); // 强制提取PDF预览图,即使已有previewUrl也要重新提取(确保是图片而不是PDF文件) - const pdfResult = await processPdfUpload(zipFilePath, ''); + const pdfResult = await processPdfUpload(zipFilePath, '', protectedMaterialId); console.log('[Upload] PDF预览图提取结果:', { success: pdfResult.success, @@ -1105,7 +1117,7 @@ export async function POST(request: NextRequest) { const pictureFormat = audioMetadata.picture.format || 'image/jpeg'; const pictureExt = pictureFormat.includes('png') ? '.png' : '.jpg'; const pictureFilename = generateUniqueFilename('audio-cover', pictureExt); - const pictureUrl = await uploadToS3(pictureBuffer, pictureFilename, pictureFormat); + const pictureUrl = await uploadToS3(pictureBuffer, pictureFilename, pictureFormat, protectedMaterialId); previewUrl = pictureUrl; uploadedFileUrls.push(pictureUrl); // 记录已上传的文件,用于失败时清理 console.log('[Upload] Audio cover image extracted and uploaded:', pictureUrl); @@ -1201,9 +1213,9 @@ export async function POST(request: NextRequest) { // 由应用端预先生成主键。这样即使数据库已经提交、但提交响应在网络中丢失, // catch 仍能按确定 ID 复查最终状态,而不是误删已经被数据库引用的文件。 - attemptedMaterialId = randomUUID(); const materialCreateData = { id: attemptedMaterialId, + accessScope, previewUrl, productModel, categoryName: resolvedCategoryName, @@ -1292,6 +1304,7 @@ export async function POST(request: NextRequest) { console.log('[Upload] Database record created:', material.id); materialId = material.id; // 保存materialId,用于失败时清理 + invalidateMaterialFacetsCache(); // 文件成功落盘后再写入任务关联字段,避免半成品占用任务号。 if (needsPostCreateTaskCompletion) { @@ -1422,6 +1435,9 @@ export async function POST(request: NextRequest) { return createUploadSuccessResponse(material); } catch (error) { + if (error instanceof MaterialAccessScopeError) { + return NextResponse.json({ error: error.message }, { status: error.status }); + } // 跨进程竞争或第一次成功响应丢失时,唯一索引会让其中一个 create // 返回 P2002;也可能在 loser 移动源文件前后出现 ENOENT。只要当前 // 用户的同一 uploadId 已有赢家,就返回赢家且不清理任何候选文件。 diff --git a/app/api/materials/upload/task-page/init/route.ts b/app/api/materials/upload/task-page/init/route.ts index 48447160..8e658fea 100644 --- a/app/api/materials/upload/task-page/init/route.ts +++ b/app/api/materials/upload/task-page/init/route.ts @@ -1,3 +1,4 @@ +import { MaterialAccessScopeError, resolveMaterialUploadAccessScope } from '@/lib/material-organization-access' import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; @@ -15,6 +16,7 @@ export async function POST(request: NextRequest) { } const body = await request.json(); + const accessScope = await resolveMaterialUploadAccessScope(body.accessScope, (session.user as any).id) const { taskNo, dingtalkApprovalNo, productModel, categoryName, sceneName, platformName, productCategoryName } = body; // 验证必填字段 @@ -40,12 +42,12 @@ export async function POST(request: NextRequest) { taskNo, deletedAt: null, // 只检查未删除的素材 }, - select: { id: true, productModel: true, materialType: true }, + select: { id: true, productModel: true, materialType: true, accessScope: true }, }); if (existingMaterial) { return NextResponse.json( - { error: `任务号 ${taskNo} 已存在,对应素材:${existingMaterial.productModel}(${existingMaterial.materialType})` }, + { error: existingMaterial.accessScope === 'operations_g' ? `任务号 ${taskNo} 已存在` : `任务号 ${taskNo} 已存在,对应素材:${existingMaterial.productModel}(${existingMaterial.materialType})` }, { status: 400 } ); } @@ -73,6 +75,7 @@ export async function POST(request: NextRequest) { // 创建素材记录(使用临时预览图) const material = await prisma.material.create({ data: { + accessScope, materialType: '任务-页面', productModel, categoryName, @@ -95,6 +98,9 @@ export async function POST(request: NextRequest) { materialId: material.id, }); } catch (error: any) { + if (error instanceof MaterialAccessScopeError) { + return NextResponse.json({ error: error.message, success: false }, { status: error.status }) + } console.error('[Task Page Init Error]', error); // 捕获 Prisma 唯一约束错误(任务号重复) diff --git a/app/api/materials/upload/video-screenshot/init/route.ts b/app/api/materials/upload/video-screenshot/init/route.ts index 688e0032..a01c62bc 100644 --- a/app/api/materials/upload/video-screenshot/init/route.ts +++ b/app/api/materials/upload/video-screenshot/init/route.ts @@ -1,3 +1,4 @@ +import { MaterialAccessScopeError, resolveMaterialUploadAccessScope } from '@/lib/material-organization-access' import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; @@ -15,6 +16,7 @@ export async function POST(request: NextRequest) { } const body = await request.json(); + const accessScope = await resolveMaterialUploadAccessScope(body.accessScope, (session.user as any).id) const { taskNo, dingtalkApprovalNo, productModel, categoryName, sceneName, platformName, productCategoryName } = body; // 验证必填字段 @@ -40,12 +42,12 @@ export async function POST(request: NextRequest) { taskNo, deletedAt: null, // 只检查未删除的素材 }, - select: { id: true, productModel: true, materialType: true }, + select: { id: true, productModel: true, materialType: true, accessScope: true }, }); if (existingMaterial) { return NextResponse.json( - { error: `任务号 ${taskNo} 已存在,对应素材:${existingMaterial.productModel}(${existingMaterial.materialType})` }, + { error: existingMaterial.accessScope === 'operations_g' ? `任务号 ${taskNo} 已存在` : `任务号 ${taskNo} 已存在,对应素材:${existingMaterial.productModel}(${existingMaterial.materialType})` }, { status: 400 } ); } @@ -73,6 +75,7 @@ export async function POST(request: NextRequest) { // 创建素材记录(使用临时预览图) const material = await prisma.material.create({ data: { + accessScope, materialType: '任务-视频截图', productModel, categoryName, @@ -95,6 +98,9 @@ export async function POST(request: NextRequest) { materialId: material.id, }); } catch (error: any) { + if (error instanceof MaterialAccessScopeError) { + return NextResponse.json({ error: error.message, success: false }, { status: error.status }) + } console.error('[Video Screenshot Init Error]', error); // 捕获 Prisma 唯一约束错误(任务号重复) diff --git a/app/api/performance/quick/route.ts b/app/api/performance/quick/route.ts index cb69f552..1d8c5760 100644 --- a/app/api/performance/quick/route.ts +++ b/app/api/performance/quick/route.ts @@ -7,6 +7,7 @@ import { prisma } from '@/lib/prisma' import { getNetworkSpeed } from '@/lib/network-bandwidth-monitor' import { authOptions } from '@/lib/auth' import { hasSystemAdminPermission } from '@/lib/department-permission' +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' import { classifyTranscodeMaterial, classifyUploadSession, @@ -92,6 +93,8 @@ export async function GET(request: NextRequest) { if (!hasSystemAdminPermission(user.role, Boolean(user.isSuperAdmin))) { return NextResponse.json({ error: '仅系统管理员可查看性能数据' }, { status: 403 }) } + const canAccessG = await canAccessOperationsGMaterials(user.id) + const organizationWhere = canAccessG ? {} : { accessScope: 'general' } const rateLimitKey = `${String(user.id || 'unknown')}:${request.headers.get('x-forwarded-for') || ''}` const retryAfter = consumeRateLimit(rateLimitKey) @@ -225,7 +228,7 @@ export async function GET(request: NextRequest) { } // 尝试通过uploadId查询已创建的material记录(获取materialType) - const uploadMaterialInfoMap = new Map() + const uploadMaterialInfoMap = new Map() if (uploadIds.size > 0) { try { const materials = await prisma.material.findMany({ @@ -236,12 +239,14 @@ export async function GET(request: NextRequest) { select: { uploadId: true, materialType: true, + accessScope: true, } as any, }) materials.forEach((m: any) => { if (m.uploadId) { uploadMaterialInfoMap.set(m.uploadId, { materialType: m.materialType || '未知类型', + accessScope: m.accessScope, }) } }) @@ -259,8 +264,13 @@ export async function GET(request: NextRequest) { materialType: materialInfo.materialType, } } - const uploadProcessingWithUsers = uploadProcessing.map(decorateUploadTask) - const uploadWaitingWithUsers = uploadWaiting.map(decorateUploadTask) + const canViewUploadTask = (task: any) => { + const scope = uploadMaterialInfoMap.get(task.uploadId)?.accessScope + if (scope === 'operations_g') return canAccessG + return canAccessG || task.userId === user.id || scope === 'general' + } + const uploadProcessingWithUsers = uploadProcessing.filter(canViewUploadTask).map(decorateUploadTask) + const uploadWaitingWithUsers = uploadWaiting.filter(canViewUploadTask).map(decorateUploadTask) const uploadQueue = { processing: uploadProcessingWithUsers, @@ -280,6 +290,7 @@ export async function GET(request: NextRequest) { const transcodeMaterials = await prisma.material.findMany({ where: { + ...organizationWhere, deletedAt: null, videoProcessingStatus: { in: ['pending', 'processing'] }, }, diff --git a/app/api/platforms/route.ts b/app/api/platforms/route.ts index 79120739..87c95183 100644 --- a/app/api/platforms/route.ts +++ b/app/api/platforms/route.ts @@ -1,3 +1,4 @@ +import { buildMaterialOrganizationWhere } from '@/lib/material-organization-access' import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; @@ -12,6 +13,8 @@ export async function GET(request: NextRequest) { return NextResponse.json({ error: '未登录' }, { status: 401 }); } + const scopeWhere = await buildMaterialOrganizationWhere((session.user as any).id); + const platforms = await prisma.platform.findMany({ orderBy: { createdAt: 'asc' }, }); @@ -23,6 +26,7 @@ export async function GET(request: NextRequest) { try { count = await prisma.material.count({ where: { + ...scopeWhere, platformName: platform.name, deletedAt: null, } as any, @@ -31,7 +35,7 @@ export async function GET(request: NextRequest) { // 兼容旧版本数据库(没有deletedAt字段) if (e?.meta?.column?.includes('deletedAt')) { count = await prisma.material.count({ - where: { platformName: platform.name }, + where: { ...scopeWhere, platformName: platform.name }, }); } else { throw e; diff --git a/app/api/product-categories/route.ts b/app/api/product-categories/route.ts index 543bb238..1fb1acf8 100644 --- a/app/api/product-categories/route.ts +++ b/app/api/product-categories/route.ts @@ -1,3 +1,4 @@ +import { buildMaterialOrganizationWhere } from '@/lib/material-organization-access' import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; @@ -11,6 +12,8 @@ export async function GET() { return NextResponse.json({ error: '未登录' }, { status: 401 }); } + const scopeWhere = await buildMaterialOrganizationWhere((session.user as any).id); + const categories = await prisma.productCategory.findMany({ orderBy: { name: 'asc' }, }); @@ -20,6 +23,7 @@ export async function GET() { categories.map(async (category) => { const count = await prisma.material.count({ where: { + ...scopeWhere, productCategoryName: category.name, deletedAt: null, }, diff --git a/app/api/rankings/route.ts b/app/api/rankings/route.ts index ae9d17f2..432d1879 100644 --- a/app/api/rankings/route.ts +++ b/app/api/rankings/route.ts @@ -5,34 +5,26 @@ import { prisma } from '@/lib/prisma'; export async function GET() { try { // 上传榜 - 按素材数量排序(只统计未删除的素材) - const contributors = await prisma.user.findMany({ - select: { - username: true, - _count: { - select: { - materials: { - where: { - deletedAt: null, - } as any, - }, - }, - }, - }, - orderBy: { - materials: { - _count: 'desc', - }, - }, - take: 10, + const contributorCounts = await prisma.material.groupBy({ + by: ['userId'], where: { deletedAt: null, accessScope: 'general' }, + _count: { id: true }, orderBy: { _count: { id: 'desc' } }, take: 10, }); - + const contributorUsers = await prisma.user.findMany({ + where: { id: { in: contributorCounts.map((row) => row.userId) } }, + select: { id: true, username: true }, + }); + const contributorNames = new Map(contributorUsers.map((user) => [user.id, user.username])); + const contributors = contributorCounts.map((row) => ({ + username: contributorNames.get(row.userId) || '未知用户', count: row._count.id, + })); + // 下载榜 - 按下载次数排序(只统计未删除的素材) let downloadRankings; try { downloadRankings = await prisma.material.groupBy({ by: ['userId'], where: { - deletedAt: null, + deletedAt: null, accessScope: 'general', } as any, _sum: { downloadCount: true, @@ -49,6 +41,7 @@ export async function GET() { if (e?.meta?.column?.includes('deletedAt')) { downloadRankings = await prisma.material.groupBy({ by: ['userId'], + where: { accessScope: 'general' }, _sum: { downloadCount: true, }, @@ -83,7 +76,7 @@ export async function GET() { likeRankings = await prisma.material.groupBy({ by: ['userId'], where: { - deletedAt: null, + deletedAt: null, accessScope: 'general', } as any, _sum: { likeCount: true, @@ -100,6 +93,7 @@ export async function GET() { if (e?.meta?.column?.includes('deletedAt')) { likeRankings = await prisma.material.groupBy({ by: ['userId'], + where: { accessScope: 'general' }, _sum: { likeCount: true, }, @@ -129,10 +123,7 @@ export async function GET() { ); return NextResponse.json({ - contributors: contributors.map((user) => ({ - username: user.username, - count: user._count.materials, - })), + contributors, downloads, likes, }); diff --git a/app/api/scenes/route.ts b/app/api/scenes/route.ts index d83e893f..5b3013be 100644 --- a/app/api/scenes/route.ts +++ b/app/api/scenes/route.ts @@ -1,3 +1,4 @@ +import { buildMaterialOrganizationWhere } from '@/lib/material-organization-access' import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; @@ -11,6 +12,8 @@ export async function GET(request: NextRequest) { return NextResponse.json({ error: '未登录' }, { status: 401 }); } + const scopeWhere = await buildMaterialOrganizationWhere((session.user as any).id); + const { searchParams } = new URL(request.url); const category = searchParams.get('category'); @@ -21,7 +24,7 @@ export async function GET(request: NextRequest) { // 统计每个场景的素材数量(只统计未删除的素材) const scenesWithCount = await Promise.all( scenes.map(async (scene) => { - const where: any = { sceneName: scene.name }; + const where: any = { ...scopeWhere, sceneName: scene.name }; if (category) { where.categoryName = category; } diff --git a/app/api/test-download/route.ts b/app/api/test-download/route.ts index abf00f10..d925b10e 100644 --- a/app/api/test-download/route.ts +++ b/app/api/test-download/route.ts @@ -29,7 +29,7 @@ export async function GET(request: NextRequest) { try { const material = await prisma.material.findUnique({ - where: { id: materialId, taskDetailPrivate: false }, + where: { id: materialId, taskDetailPrivate: false, accessScope: 'general' }, select: { id: true, productModel: true, diff --git a/app/api/uploads/[...path]/route.ts b/app/api/uploads/[...path]/route.ts index 467e06b6..34dd199e 100644 --- a/app/api/uploads/[...path]/route.ts +++ b/app/api/uploads/[...path]/route.ts @@ -1,3 +1,4 @@ +import { isRestrictedMaterial } from '@/lib/material-access-scope' // 文件访问API - 提供本地上传文件的访问 import { NextRequest } from 'next/server' import { getServerSession } from 'next-auth' @@ -15,7 +16,7 @@ import { DownloadErrorCode } from '@/lib/download-errors' import { is3DOriginalType, isProductPackageType } from '@/lib/material-type-mapper' import { findBlockedVideoPreviewByUrl, isVideoMediaPath } from '@/lib/video-preview-access' import { userHasVideoEarlyAccess } from '@/lib/video-download-policy' -import { canAccessMaterialPrivacy, isPrivateTaskDetail, TASK_DETAIL_PRIVACY_SELECT, type TaskDetailPrivacyMaterial } from '@/lib/task-detail-privacy' +import { canAccessMaterialPrivacy, TASK_DETAIL_PRIVACY_SELECT, type TaskDetailPrivacyMaterial } from '@/lib/task-detail-privacy' export const runtime = 'nodejs' export const dynamic = 'force-dynamic' @@ -149,7 +150,27 @@ async function resolveFileAccess( } const previewAsset = (assetMatches as any[]).find((asset) => isPreviewAssetType(asset.assetType)) - return previewAsset ? { kind: 'preview', material: previewAsset.material } : null + if (previewAsset) return { kind: 'preview', material: previewAsset.material } + const skus = await prisma.materialSku.findMany({ + where: { OR: [{ filePath: { in: candidates } }, { previewUrl: { in: candidates } }], material: { deletedAt: null } }, + select: { filePath: true, previewUrl: true, material: { select: { id: true, materialType: true, ...TASK_DETAIL_PRIVACY_SELECT } } }, + take: 20, + }) + for (const sku of skus) { + if (matchesCandidate(sku.filePath)) return { kind: 'source', material: sku.material } + if (matchesCandidate(sku.previewUrl)) return { kind: 'preview', material: sku.material } + } + // 白底图派生预览按素材目录归属,原件必须匹配当前源文件记录。 + const protectedPath = candidates.map(normalizeStoredPath).find((value) => /^uploads\/materials\/[^/]+\/protected-display\/white-background\//.test(value)) + if (protectedPath) { + const ownerId = protectedPath.split('/')[2] + const owner = await prisma.material.findFirst({ + where: { id: ownerId, deletedAt: null }, + select: { id: true, materialType: true, ...TASK_DETAIL_PRIVACY_SELECT }, + }) + if (owner) return { kind: 'preview', material: owner } + } + return null } async function authorizeSourceAccess( @@ -194,7 +215,7 @@ async function authorizeSourceAccess( ) } - const canDownload = isPrivateTaskDetail(material) || await canUserDownloadMaterial( + const canDownload = isRestrictedMaterial(material) || await canUserDownloadMaterial( user.department, user.role, user.managedDepartment, @@ -255,10 +276,10 @@ async function handleFileRequest( if (!access) { return new Response(headOnly ? null : 'Not Found', { status: 404 }) } - if (isPrivateTaskDetail(access.material)) { + if (isRestrictedMaterial(access.material)) { const session = await getServerSession(authOptions) if (!(await canAccessMaterialPrivacy(access.material, (session?.user as any)?.id))) { - return new Response(headOnly ? null : '无权限访问该私密素材', { + return new Response(headOnly ? null : '无权限访问此素材', { status: session?.user ? 403 : 401, headers: { 'Cache-Control': 'private, no-store', Vary: 'Cookie' }, }) @@ -313,7 +334,7 @@ async function handleFileRequest( const contentType = mimeTypeLookup(path.extname(filePath)) || 'application/octet-stream' const cacheControl = - access.kind === 'source' || isPrivateTaskDetail(access.material) ? 'private, no-store' : 'public, max-age=31536000, immutable' + access.kind === 'source' || isRestrictedMaterial(access.material) ? 'private, no-store' : 'public, max-age=31536000, immutable' if (headOnly) { return new Response(null, { diff --git a/app/api/user/favorites/route.ts b/app/api/user/favorites/route.ts index 6354f765..db287d19 100644 --- a/app/api/user/favorites/route.ts +++ b/app/api/user/favorites/route.ts @@ -57,6 +57,7 @@ export async function GET(request: NextRequest) { previewUrl: true, displayImages: true, materialType: true, + accessScope: true, categoryName: true, sceneName: true, platformName: true, diff --git a/app/api/user/materials/route.ts b/app/api/user/materials/route.ts index 0e3a21ef..f6cfd668 100644 --- a/app/api/user/materials/route.ts +++ b/app/api/user/materials/route.ts @@ -53,6 +53,7 @@ export async function GET(request: NextRequest) { previewUrl: true, displayImages: true, materialType: true, + accessScope: true, categoryName: true, sceneName: true, platformName: true, @@ -115,6 +116,7 @@ export async function GET(request: NextRequest) { previewUrl: true, displayImages: true, materialType: true, + accessScope: true, categoryName: true, sceneName: true, platformName: true, diff --git a/app/edit/[id]/page.tsx b/app/edit/[id]/page.tsx index b2cb766e..7e051eee 100644 --- a/app/edit/[id]/page.tsx +++ b/app/edit/[id]/page.tsx @@ -1,5 +1,7 @@ 'use client' +import MaterialAccessScopeField from '@/components/upload/MaterialAccessScopeField' +import type { MaterialAccessScope } from '@/lib/material-access-scope' import Select from '@/components/ui/Select' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' @@ -34,6 +36,8 @@ import { getDingtalkApprovalNoError } from '@/lib/dingtalk-approval-no' import { parseFetchError } from '@/lib/error-handler' interface Material { + accessScope?: MaterialAccessScope + id: string userId: string productModel: string @@ -126,6 +130,7 @@ export default function EditMaterialPage({ params }: { params: { id: string } }) const [platformName, setPlatformName] = useState('') const [productCategoryName, setProductCategoryName] = useState('') const [materialType, setMaterialType] = useState('') + const [accessScope, setAccessScope] = useState('general') const [renderer, setRenderer] = useState('') const [authorName, setAuthorName] = useState('') const [userId, setUserId] = useState('') @@ -174,6 +179,7 @@ export default function EditMaterialPage({ params }: { params: { id: string } }) platformName, productCategoryName, materialType, + accessScope, renderer, authorName, userId, @@ -186,6 +192,7 @@ export default function EditMaterialPage({ params }: { params: { id: string } }) categoryName, dingtalkApprovalNo, materialType, + accessScope, platformName, previewImage, productCategoryName, @@ -321,6 +328,7 @@ export default function EditMaterialPage({ params }: { params: { id: string } }) setPlatformName(data.platformName || '') setProductCategoryName(data.productCategoryName || '') setMaterialType(data.materialType || '') + setAccessScope(data.accessScope || 'general') setRenderer(data.renderer || '') setAuthorName(data.authorName || '') setUserId(data.userId || '') @@ -360,6 +368,7 @@ export default function EditMaterialPage({ params }: { params: { id: string } }) platformName: data.platformName || '', productCategoryName: data.productCategoryName || '', materialType: data.materialType || '', + accessScope: data.accessScope || 'general', renderer: data.renderer || '', authorName: data.authorName || '', userId: data.userId || '', @@ -610,6 +619,7 @@ export default function EditMaterialPage({ params }: { params: { id: string } }) formData.append('platformName', platformName) formData.append('productCategoryName', productCategoryName) formData.append('materialType', materialType) + formData.append('accessScope', accessScope) formData.append('renderer', renderer) formData.append('authorName', authorName) formData.append('userId', userId) @@ -920,6 +930,13 @@ export default function EditMaterialPage({ params }: { params: { id: string } }) + + {showCategoryScene && ( <>
diff --git a/app/share/[id]/page.tsx b/app/share/[id]/page.tsx index 1bd39e5e..c545b0e1 100644 --- a/app/share/[id]/page.tsx +++ b/app/share/[id]/page.tsx @@ -33,6 +33,8 @@ import { chunkUpload } from '@/lib/chunk-upload' import { TASK_DETAIL_UPLOAD_LIMITS } from '@/lib/task-detail-upload-policy' interface Material { + accessScope?: string + id: string userId: string previewUrl: string @@ -1580,6 +1582,7 @@ export default function SharePage() { ('general') + const [dedicatedUploading, setDedicatedUploading] = useState(false) // 可见的素材类型列表(从API动态加载) const [availableMaterialTypes, setAvailableMaterialTypes] = useState([]) @@ -235,7 +240,7 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = { const isTaskOtherMaterial = materialType === '任务-其他' const usesDedicatedUploader = SPECIAL_UPLOAD_TYPES.includes(materialType as typeof SPECIAL_UPLOAD_TYPES[number]) - const interactionLocked = uploading || previewProcessingCount > 0 + const interactionLocked = dedicatedUploading || uploading || previewProcessingCount > 0 const previewInputRef = useRef(null) const zipInputRef = useRef(null) @@ -977,7 +982,7 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = { try { const results = await uploadBatchMusic(batchMusicFiles, platformName, renderer, (progress) => { setUploadProgress(progress) - }) + }, accessScope) // 检查是否有失败的文件 const failedFiles = results.filter(r => r.status === 'failed') @@ -1126,6 +1131,7 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = { try { // 构建每个文件的元数据 const metadata: any = { + accessScope, materialType, productModel: item.productModel, categoryName: shouldAutoFillGeneral(materialType) @@ -1275,6 +1281,7 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = { formData.append('platformName', metadata.platformName) formData.append('productCategoryName', metadata.productCategoryName) formData.append('materialType', materialType) + formData.append('accessScope', accessScope) if (metadata.renderer) { formData.append('renderer', metadata.renderer) } @@ -1446,7 +1453,7 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = { try { const results = await uploadBatchVideo(batchVideoFiles, platformName, renderer, productCategoryName, (progress) => { setUploadProgress(progress) - }) + }, accessScope) // 检查是否有失败的文件 const failedFiles = results.filter(r => r.status === 'failed') @@ -1484,7 +1491,7 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = { try { const results = await uploadBatch3D(batch3DFiles, categoryName, sceneName, platformName, renderer, (progress) => { setUploadProgress(progress) - }) + }, accessScope) // 检查是否有失败的文件 const failedFiles = results.filter(r => r.status === 'failed') @@ -1519,7 +1526,7 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = { try { const results = await uploadBatchBuyerShow(batchBuyerShowFiles, categoryName, sceneName, platformName, renderer, (progress) => { setUploadProgress(progress) - }) + }, accessScope) // 检查是否有失败的文件 const failedFiles = results.filter(r => r.status === 'failed') @@ -1554,7 +1561,7 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = { try { const results = await uploadBatchXiaohongshu(batchXiaohongshuFiles, categoryName, sceneName, platformName, renderer, (progress) => { setUploadProgress(progress) - }) + }, accessScope) // 检查是否有失败的文件 const failedFiles = results.filter(r => r.status === 'failed') @@ -1589,7 +1596,7 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = { try { const results = await uploadBatchBrandVI(batchBrandVIFiles, productCategoryName, (progress) => { setUploadProgress(progress) - }) + }, accessScope) // 检查是否有失败的文件 const failedFiles = results.filter(r => r.status === 'failed') @@ -1864,6 +1871,7 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = { } const formData = buildFormData({ + accessScope, previewImages, displayImage, modelImages, @@ -2048,13 +2056,20 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = { value={materialType} onChange={setMaterialType} disabled={interactionLocked} - options={availableMaterialTypes.length > 0 + options={accessScope === 'operations_g' ? [...MATERIAL_TYPE_OPTIONS] : availableMaterialTypes.length > 0 ? availableMaterialTypes : MATERIAL_TYPE_OPTIONS.filter((type) => !SPECIAL_UPLOAD_TYPES.includes(type as typeof SPECIAL_UPLOAD_TYPES[number]))} counts={materialTypeCounts} />
+ + {!usesDedicatedUploader && ( { onSuccess(); onClose(); @@ -2090,6 +2107,8 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = { {materialType === '任务-视频截图' && (
{ onSuccess(); onClose(); @@ -2109,6 +2128,8 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = { {materialType === '任务-页面' && (
{ onSuccess(); onClose(); @@ -2128,6 +2149,8 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = { {materialType === '证书-检测报告' && (
{ onSuccess(); onClose(); diff --git a/components/UploadModal.video-preview.test.tsx b/components/UploadModal.video-preview.test.tsx index cc881d07..ab81e744 100644 --- a/components/UploadModal.video-preview.test.tsx +++ b/components/UploadModal.video-preview.test.tsx @@ -189,7 +189,7 @@ describe('UploadModal - 视频预览图处理状态', () => { expect(await screen.findByText('批量上传模式(2 个文件)')).toBeInTheDocument() - const firstMetadataSelects = screen.getAllByRole('combobox').filter((control) => control.id !== 'upload-material-type') + const firstMetadataSelects = screen.getAllByRole('combobox').filter((control) => control.id !== 'upload-material-type' && control.id !== 'upload-access-scope') await selectOption(firstMetadataSelects[0], '通用') await selectOption(firstMetadataSelects[1], '通用') @@ -206,7 +206,7 @@ describe('UploadModal - 视频预览图处理状态', () => { const previewInputs = await screen.findAllByLabelText(/^视频预览图/) expect(previewInputs).toHaveLength(2) const secondPreviewInput = previewInputs[1] as HTMLInputElement - const secondMetadataSelects = screen.getAllByRole('combobox').filter((control) => control.id !== 'upload-material-type') + const secondMetadataSelects = screen.getAllByRole('combobox').filter((control) => control.id !== 'upload-material-type' && control.id !== 'upload-access-scope') await selectOption(secondMetadataSelects[2], '通用') await selectOption(secondMetadataSelects[3], '通用') await waitFor(() => expect(secondPreviewInput).not.toBeDisabled()) diff --git a/components/detail/MaterialDetailHeader.tsx b/components/detail/MaterialDetailHeader.tsx index 072ed143..36af1237 100644 --- a/components/detail/MaterialDetailHeader.tsx +++ b/components/detail/MaterialDetailHeader.tsx @@ -16,6 +16,7 @@ export type MaterialDetailCapabilities = { type MaterialDetailHeaderProps = { title: string materialType: string + accessScope?: string materialId: string isFavorited: boolean capabilities: MaterialDetailCapabilities @@ -70,6 +71,7 @@ function ActionButton({ export default function MaterialDetailHeader({ title, materialType, + accessScope, materialId, isFavorited, capabilities, @@ -104,8 +106,8 @@ export default function MaterialDetailHeader({

{title}

-

- {materialType} +

+ {accessScope === 'operations_g' ? `${materialType} · 运营中心 G 专属` : materialType} ID {materialId}

diff --git a/components/detail/ProductPackageDetail.tsx b/components/detail/ProductPackageDetail.tsx index 03c2517a..b0e0b5a5 100644 --- a/components/detail/ProductPackageDetail.tsx +++ b/components/detail/ProductPackageDetail.tsx @@ -45,6 +45,7 @@ interface ProductPackageDetailProps { taskDetailSourceType?: string | null; taskDetailDemandType?: string | null; taskDetailPrivate?: boolean; + accessScope?: string; isFullSet?: boolean; taskStatus: string; taskFetchedAt?: string; @@ -506,7 +507,7 @@ export default function ProductPackageDetail({ {material.taskDetailDemandType && (

需求类型 / 可见范围

-

{material.taskDetailDemandType} · {material.taskDetailPrivate ? '私密' : '公开'}

+

{material.taskDetailDemandType} · {material.accessScope === 'operations_g' ? '中心内共享' : material.taskDetailPrivate ? '私密' : '公开'}

)}
diff --git a/components/home/MaterialCard.tsx b/components/home/MaterialCard.tsx index 72b9b59c..8735c7cf 100644 --- a/components/home/MaterialCard.tsx +++ b/components/home/MaterialCard.tsx @@ -15,6 +15,8 @@ import { // 素材类型定义 export interface Material { + accessScope?: string + id: string productModel: string reportTitle?: string | null @@ -593,6 +595,9 @@ export default function MaterialCard({
+ {material.accessScope === 'operations_g' && ( +

运营中心 G 专属

+ )}

{materialDisplayTitle}

diff --git a/components/upload/CertificateReportUploader.tsx b/components/upload/CertificateReportUploader.tsx index 495d3fab..58b07fb7 100644 --- a/components/upload/CertificateReportUploader.tsx +++ b/components/upload/CertificateReportUploader.tsx @@ -1,8 +1,9 @@ 'use client' +import type { MaterialAccessScope } from '@/lib/material-access-scope' import Select from '@/components/ui/Select' -import { useMemo, useRef, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import { CERTIFICATE_REPORT_KIND, CERTIFICATE_REPORT_MATERIAL_TYPE, @@ -22,6 +23,9 @@ interface CategoryItem { } interface CertificateReportUploaderProps { + accessScope?: MaterialAccessScope + onBusyChange?: (busy: boolean) => void + onSuccess: () => void onCancel: () => void productCategories: CategoryItem[] @@ -35,6 +39,8 @@ interface ReportFileItem { } export default function CertificateReportUploader({ + accessScope = 'general', + onBusyChange, onSuccess, onCancel, productCategories, @@ -51,6 +57,11 @@ export default function CertificateReportUploader({ const [platformName, setPlatformName] = useState('') const [files, setFiles] = useState([]) const [uploading, setUploading] = useState(false) + useEffect(() => { + onBusyChange?.(uploading) + return () => onBusyChange?.(false) + }, [uploading, onBusyChange]) + const [uploadProgress, setUploadProgress] = useState(0) const [processingStep, setProcessingStep] = useState('') const [error, setError] = useState('') @@ -163,6 +174,7 @@ export default function CertificateReportUploader({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ + accessScope, productModel: submittedProductModel, reportTitle: reportTitle.trim(), reportKind, diff --git a/components/upload/MaterialAccessScopeField.test.tsx b/components/upload/MaterialAccessScopeField.test.tsx new file mode 100644 index 00000000..691bbd5e --- /dev/null +++ b/components/upload/MaterialAccessScopeField.test.tsx @@ -0,0 +1,33 @@ +import { useState } from 'react' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import MaterialAccessScopeField from './MaterialAccessScopeField' +import type { MaterialAccessScope } from '@/lib/material-access-scope' + +test('使用范围默认通用,切换专属时提交稳定值并解释组织共享', async () => { + const changed = jest.fn() + function Form() { + const [value, setValue] = useState('general') + return { changed(next); setValue(next) }} /> + } + const user = userEvent.setup() + render(
) + const field = screen.getByRole('combobox', { name: '使用范围 *' }) + expect(field).toHaveTextContent('通用素材') + await user.click(field) + await user.click(screen.getByRole('option', { name: '运营中心 G 专属' })) + expect(changed).toHaveBeenCalledWith('operations_g') + expect(field).toHaveTextContent('运营中心 G 专属') + expect(screen.getByText('仅运营中心 G 及其下属部门成员可见,中心内共享。')).toBeInTheDocument() + expect(field).toHaveFocus() +}) + +test('上传期间禁止更改使用范围', async () => { + const changed = jest.fn() + render() + const field = screen.getByRole('combobox', { name: '使用范围 *' }) + expect(field).toBeDisabled() + await userEvent.click(field) + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() + expect(changed).not.toHaveBeenCalled() +}) diff --git a/components/upload/MaterialAccessScopeField.tsx b/components/upload/MaterialAccessScopeField.tsx new file mode 100644 index 00000000..f7b4dbbd --- /dev/null +++ b/components/upload/MaterialAccessScopeField.tsx @@ -0,0 +1,45 @@ +'use client' + +import Select from '@/components/ui/Select' +import { + MATERIAL_ACCESS_SCOPES, + MATERIAL_ACCESS_SCOPE_LABELS, + type MaterialAccessScope, +} from '@/lib/material-access-scope' +import { fieldControlClass, fieldHintClass, fieldLabelClass } from './upload-field-styles' + +export default function MaterialAccessScopeField({ + id, + value, + onChange, + disabled = false, +}: { + id: string + value: MaterialAccessScope + onChange: (value: MaterialAccessScope) => void + disabled?: boolean +}) { + return ( +
+ + +

+ {value === 'operations_g' + ? '仅运营中心 G 及其下属部门成员可见,中心内共享。' + : '按现有素材权限使用。'} +

+
+ ) +} diff --git a/components/upload/ProductPackageUploader.tsx b/components/upload/ProductPackageUploader.tsx index 0659dc7d..d6270ee8 100644 --- a/components/upload/ProductPackageUploader.tsx +++ b/components/upload/ProductPackageUploader.tsx @@ -5,6 +5,7 @@ 'use client'; +import type { MaterialAccessScope } from '@/lib/material-access-scope' import Select from '@/components/ui/Select' import { useCallback, useEffect, useRef, useState } from 'react'; @@ -95,6 +96,9 @@ function splitEmptyFiles(files: FileList | File[] | null): { } interface ProductPackageUploaderProps { + accessScope?: MaterialAccessScope + onBusyChange?: (busy: boolean) => void + onSuccess: () => void; onCancel: () => void; categories: Array<{ id: string; name: string }>; @@ -360,6 +364,8 @@ function AssetThumbnail({ } export default function ProductPackageUploader({ + accessScope = 'general', + onBusyChange, onSuccess, onCancel, categories, @@ -380,6 +386,9 @@ export default function ProductPackageUploader({ const [taskDetailSourceType, setTaskDetailSourceType] = useState(''); const [taskDetailDemandType, setTaskDetailDemandType] = useState('新品'); const [taskDetailPrivate, setTaskDetailPrivate] = useState(false); + useEffect(() => { + if (accessScope === 'operations_g') setTaskDetailPrivate(false) + }, [accessScope]); const [taskDetailRequesterUserId, setTaskDetailRequesterUserId] = useState(''); const [users, setUsers] = useState>([]); const [usersLoading, setUsersLoading] = useState(true); @@ -400,6 +409,11 @@ export default function ProductPackageUploader({ // 上传状态 const [noBarcodes, setNoBarcodes] = useState(false); const [uploading, setUploading] = useState(false); + useEffect(() => { + onBusyChange?.(uploading) + return () => onBusyChange?.(false) + }, [uploading, onBusyChange]) + const [uploadProgress, setUploadProgress] = useState(0); const [processingStep, setProcessingStep] = useState(''); const [error, setError] = useState(''); @@ -554,9 +568,11 @@ export default function ProductPackageUploader({ }); }, [updateAssetPreview]); - const isOptimizationDemand = taskDetailDemandType === '优化'; - const taskDetailVisibilityValue = taskDetailPrivate ? 'private' : 'public'; - const taskDetailPrivacyHint = isOptimizationDemand + const isOptimizationDemand = taskDetailDemandType === '优化' && accessScope !== 'operations_g'; + const taskDetailVisibilityValue = accessScope === 'operations_g' ? 'public' : (taskDetailPrivate ? 'private' : 'public'); + const taskDetailPrivacyHint = accessScope === 'operations_g' + ? '运营中心 G 内部共享,其他部门不可见。' + : isOptimizationDemand ? '私密仅所选需求运营及已授权权限组可访问,上传人不自动放行。' : '新品固定公开,仅优化需求支持私密;若设为私密,仅所选需求运营及已授权权限组可访问,上传人不自动放行。'; @@ -968,6 +984,7 @@ export default function ProductPackageUploader({ let taskDetailPrivacyFields: ReturnType; try { taskDetailPrivacyFields = normalizeTaskDetailPrivacyFields({ + accessScope, taskDetailDemandType, taskDetailPrivate, }); @@ -1078,6 +1095,7 @@ export default function ProductPackageUploader({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ + accessScope, taskNo, dingtalkApprovalNo: dingtalkApprovalNo.trim() || undefined, productModel, @@ -1508,13 +1526,13 @@ export default function ProductPackageUploader({
diff --git a/components/upload/TaskPageUploader.tsx b/components/upload/TaskPageUploader.tsx index c68dfbf5..fa2b565f 100644 --- a/components/upload/TaskPageUploader.tsx +++ b/components/upload/TaskPageUploader.tsx @@ -1,5 +1,6 @@ 'use client' +import type { MaterialAccessScope } from '@/lib/material-access-scope' import Select from '@/components/ui/Select' import { useState, useRef, useEffect } from 'react'; @@ -27,6 +28,9 @@ interface CategoryItem { } interface TaskPageUploaderProps { + accessScope?: MaterialAccessScope + onBusyChange?: (busy: boolean) => void + onSuccess: () => void; onCancel: () => void; categories: CategoryItem[]; @@ -38,6 +42,8 @@ interface TaskPageUploaderProps { } export default function TaskPageUploader({ + accessScope = 'general', + onBusyChange, onSuccess, onCancel, categories, @@ -62,6 +68,11 @@ export default function TaskPageUploader({ // 上传状态 const [uploading, setUploading] = useState(false); + useEffect(() => { + onBusyChange?.(uploading) + return () => onBusyChange?.(false) + }, [uploading, onBusyChange]) + const [uploadProgress, setUploadProgress] = useState(0); const [processingStep, setProcessingStep] = useState(''); const [error, setError] = useState(''); @@ -231,6 +242,7 @@ export default function TaskPageUploader({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ + accessScope, taskNo, dingtalkApprovalNo: dingtalkApprovalNo.trim() || undefined, productModel, diff --git a/components/upload/VideoScreenshotUploader.tsx b/components/upload/VideoScreenshotUploader.tsx index 91925ba2..8f59193f 100644 --- a/components/upload/VideoScreenshotUploader.tsx +++ b/components/upload/VideoScreenshotUploader.tsx @@ -1,5 +1,6 @@ 'use client' +import type { MaterialAccessScope } from '@/lib/material-access-scope' import Select from '@/components/ui/Select' import { useState, useRef, useEffect } from 'react'; @@ -27,6 +28,9 @@ interface CategoryItem { } interface VideoScreenshotUploaderProps { + accessScope?: MaterialAccessScope + onBusyChange?: (busy: boolean) => void + onSuccess: () => void; onCancel: () => void; categories: CategoryItem[]; @@ -38,6 +42,8 @@ interface VideoScreenshotUploaderProps { } export default function VideoScreenshotUploader({ + accessScope = 'general', + onBusyChange, onSuccess, onCancel, categories, @@ -62,6 +68,11 @@ export default function VideoScreenshotUploader({ // 上传状态 const [uploading, setUploading] = useState(false); + useEffect(() => { + onBusyChange?.(uploading) + return () => onBusyChange?.(false) + }, [uploading, onBusyChange]) + const [uploadProgress, setUploadProgress] = useState(0); const [processingStep, setProcessingStep] = useState(''); const [error, setError] = useState(''); @@ -245,6 +256,7 @@ export default function VideoScreenshotUploader({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ + accessScope, taskNo: taskNo || undefined, dingtalkApprovalNo: dingtalkApprovalNo.trim() || undefined, productModel, diff --git a/components/upload/file-upload-handlers.ts b/components/upload/file-upload-handlers.ts index a5f5bc55..87d12458 100644 --- a/components/upload/file-upload-handlers.ts +++ b/components/upload/file-upload-handlers.ts @@ -1,3 +1,4 @@ +import type { MaterialAccessScope } from '@/lib/material-access-scope' /** * 文件上传处理函数 * 包括单文件上传、表单提交等 @@ -17,6 +18,7 @@ export type CompletedChunkUploadReference = { * 构建表单数据 */ export function buildFormData(params: { + accessScope?: MaterialAccessScope previewImages: File[] displayImage: File | null modelImages: File[] @@ -37,6 +39,7 @@ export function buildFormData(params: { livePlatform?: string }): FormData { const { + accessScope = 'general', previewImages, displayImage, modelImages, @@ -90,6 +93,7 @@ export function buildFormData(params: { formData.append('platformName', platformName || '') formData.append('productCategoryName', productCategoryName || '') formData.append('materialType', materialType) + formData.append('accessScope', accessScope) // 任务号(可选) if (taskNo) { diff --git a/components/upload/special-batch-uploaders.ts b/components/upload/special-batch-uploaders.ts index 4067fe76..aa16d963 100644 --- a/components/upload/special-batch-uploaders.ts +++ b/components/upload/special-batch-uploaders.ts @@ -1,3 +1,4 @@ +import type { MaterialAccessScope } from '@/lib/material-access-scope' /** * 特殊类型的批量上传处理函数 * 包括:音乐、淘系-逛逛视频、3D场景、品牌VI、买家秀、小红书 @@ -313,6 +314,7 @@ export async function completeBatchUpload(uploadId: string, metadata: Record, platformName: string, renderer: string, - onProgress: (progress: number) => void + onProgress: (progress: number) => void, + accessScope: MaterialAccessScope = 'general', ) { const baseMetadata = { + accessScope, materialType: '音乐', categoryName: '通用', sceneName: '通用', @@ -459,9 +463,11 @@ export async function uploadBatchVideo( platformName: string, renderer: string, productCategoryName: string, - onProgress: (progress: number) => void + onProgress: (progress: number) => void, + accessScope: MaterialAccessScope = 'general', ) { const baseMetadata = { + accessScope, materialType: TAOXI_GUANGGUANG_VIDEO_TYPE, categoryName: '通用', sceneName: '通用', @@ -552,9 +558,11 @@ export async function uploadBatch3D( sceneName: string, platformName: string, renderer: string, - onProgress: (progress: number) => void + onProgress: (progress: number) => void, + accessScope: MaterialAccessScope = 'general', ) { const baseMetadata = { + accessScope, materialType: '3D场景', categoryName: categoryName || '通用', sceneName: sceneName || '通用', @@ -635,9 +643,11 @@ export async function uploadBatchBuyerShow( sceneName: string, platformName: string, renderer: string, - onProgress: (progress: number) => void + onProgress: (progress: number) => void, + accessScope: MaterialAccessScope = 'general', ) { const baseMetadata = { + accessScope, materialType: '买家秀图片', categoryName: categoryName || '通用', sceneName: sceneName || '通用', @@ -671,6 +681,7 @@ export async function uploadBatchBuyerShow( formData.append('productCategoryName', metadata.productCategoryName || '') const materialType = metadata.materialType formData.append('materialType', materialType) + formData.append('accessScope', metadata.accessScope || 'general') // 统一处理renderer字段:根据素材类型判断是否需要传递 const rendererInfo = shouldPassRenderer(materialType, metadata.renderer) @@ -731,9 +742,11 @@ export async function uploadBatchXiaohongshu( sceneName: string, platformName: string, renderer: string, - onProgress: (progress: number) => void + onProgress: (progress: number) => void, + accessScope: MaterialAccessScope = 'general', ) { const baseMetadata = { + accessScope, materialType: '小红书种草', categoryName: categoryName || '通用', sceneName: sceneName || '通用', @@ -767,6 +780,7 @@ export async function uploadBatchXiaohongshu( formData.append('productCategoryName', metadata.productCategoryName || '') const materialType = metadata.materialType formData.append('materialType', materialType) + formData.append('accessScope', metadata.accessScope || 'general') // 统一处理renderer字段:根据素材类型判断是否需要传递 const rendererInfo = shouldPassRenderer(materialType, metadata.renderer) @@ -824,9 +838,11 @@ export async function uploadBatchXiaohongshu( export async function uploadBatchBrandVI( files: Array<{ file: File; productModel: string }>, productCategoryName: string, - onProgress: (progress: number) => void + onProgress: (progress: number) => void, + accessScope: MaterialAccessScope = 'general', ) { const baseMetadata = { + accessScope, materialType: '品牌VI灵感', categoryName: '通用', sceneName: '通用', diff --git a/docs/material-access-scope.md b/docs/material-access-scope.md new file mode 100644 index 00000000..030f9f24 --- /dev/null +++ b/docs/material-access-scope.md @@ -0,0 +1,22 @@ +# 素材使用范围 + +素材在原有素材库中按 `accessScope` 区分使用范围,适用于全部素材类型。 + +| 值 | 界面名称 | 使用规则 | +|---|---|---| +| `general` | 通用素材 | 沿用原有素材类型、私密与操作权限 | +| `operations_g` | 运营中心 G 专属 | 整个运营中心 G 及其下属部门共享,组织外账号不可访问 | + +历史记录默认 `general`。专属素材不设置自动开放期限,也不能叠加个人私密。 + +组织资格复用正式账号与人员绑定、当前组织任职路径;运营中心 G 绑定 HR 部门编号 `911666246`。部门改名读取当前节点路径,账号调出或人员离职后不再获得专属资格。上传者、需求运营及管理员身份均不提供组织外访问例外。 + +上传与编辑提供“使用范围”字段。专属素材的预览、图片、视频派生产物使用本地鉴权存储;列表、搜索、统计、详情、分享、下载、导出、日志和回收站按同一组织范围处理。下载开关、源文件下载和编辑权限继续沿用原有规则。外部 API 与对外通知仅提供通用素材。 + +性能监控中的素材任务遵循相同范围。上传会话尚未关联素材时,仅上传者和 G 内管理员可查看文件名。 + +通用素材改为专属时,当前公开存储中的文件先复制到鉴权存储,再一起保存素材、资产及 SKU 地址,最后清理不再引用的公开对象。视频仍在生成预览时,须等待处理结束再更改使用范围。 + +数据库变更位于 `prisma/migrations/20261106110000_material_access_scope/migration.sql`。发布时先执行迁移,再整体切换应用版本;旧版本不识别组织范围,回滚前须处理已创建的专属素材。 + +生产迁移复用 `scripts/safe-production-migrate.mjs`:备份与隔离恢复验证通过后执行,审计同时核对字段默认值、索引、范围枚举约束及中心内共享约束。 diff --git a/docs/生产数据库安全增量迁移SOP-2026-08-12.md b/docs/生产数据库安全增量迁移SOP-2026-08-12.md index fdb8b8c1..50a9d883 100644 --- a/docs/生产数据库安全增量迁移SOP-2026-08-12.md +++ b/docs/生产数据库安全增量迁移SOP-2026-08-12.md @@ -2,7 +2,9 @@ ## 结论 -当前应用发布工具验证四十份目标 migration。普通部署脚本**只读验证,不会自动修改数据库**。只有独立 migrator 在同时拿到精确 Git 提交、数据库身份和备份凭证后,才允许执行 `prisma migrate deploy`。目标名称以该精确提交的 `TARGET_MIGRATIONS` 为准,不能沿用历史批次的数量或凭证。 +当前应用发布工具验证四十一份目标 migration。普通部署脚本**只读验证,不会自动修改数据库**。只有独立 migrator 在同时拿到精确 Git 提交、数据库身份和备份凭证后,才允许执行 `prisma migrate deploy`。目标名称以该精确提交的 `TARGET_MIGRATIONS` 为准,不能沿用历史批次的数量或凭证。 + +`20261106110000_material_access_scope` 为所有素材增加默认 `general` 的使用范围,新增索引,并限制专属素材为运营中心 G 内共享。迁移不改变现有素材的可见范围;审计同时验证范围枚举和禁止叠加个人私密的数据库约束。 目标 migration: @@ -46,6 +48,7 @@ - `20261020120000_desktop_creation_tasks` - `20261020150000_desktop_project_deletion` - `20261023130000_personnel_salary_base` +- `20261106110000_material_access_scope` `20261012_detail_generator` 仅新增个人详情页项目、私有文件、持久任务和品牌风格草案四张表及其约束/索引,不回填素材库或修改用户权限。正式验收前,启用配置仍只开放给当前有效超级管理员;私有文件目录独立持久挂载。 @@ -90,7 +93,7 @@ 1. 构建并固定同一 exact SHA/digest 的 runner 与 migrator; 2. legacy bootstrap `Audit`; 3. legacy bootstrap `Apply`,外部验收 503,确认旧容器停止且保留; -4. 在同一维护窗内运行本文的真实备份、隔离恢复、四十条目标 migration 和迁移后审计; +4. 在同一维护窗内运行本文的真实备份、隔离恢复、四十一条目标 migration 和迁移后审计; 5. 仅在所有门禁通过后,运行普通同 SHA 应用部署。 顺序不得改为“先 migration,后 bootstrap”。本文备份工具的生产前后摘要若有变化,说明维护窗内仍可能存在写入,会直接失败且不生成 receipt。 @@ -416,7 +419,7 @@ docker run --rm \ "$MIGRATOR_IMAGE" --apply ``` -工具会在修改数据库前先验证审计目录可执行“新建→原子改名→删除”,再依次完成:核对镜像 SHA、配置端口与数据库实际端口、核对机器生成的 receipt 和完整备份产物、拒绝未知待执行/失败 migration、执行 `prisma migrate deploy`,最后核对四十条目标 migration 的数据库 checksum、完成状态、关键人员组织表、素材空壳标记、钉钉流程快照表及需求类型和表单字段、员工花名册历史快照表、业绩转化经营数据快照及同步状态表、字段类型与可空性、检测报告原五个可空字段和独立检测日期字段、`api_keys` 三个可空加密列、`api_key_reveal_audits` 关键列、租约/需求类型/API Key reveal 审计索引的精确列顺序、`materials_uploadId_key` 的唯一性/btree/单列/有效就绪状态/active-only 谓词、Logo 默认值,以及 `materials.task_detail_demand_type` 无默认值、`materials.task_detail_private` / `material_permission_pack_items.can_access_private` 默认值为 `false`,并用稳定语义核对 `materials_private_optimization_check`,确认私密任务详情仍被精确限制在“任务-详情 + 优化”条件下,同时确认品牌知识预览切片列为非空文本数组且默认空数组;AI 模型五表、能力证据及用途验证约束/索引也须通过前述结构检查,最后原子写审计 JSON。 +工具会在修改数据库前先验证审计目录可执行“新建→原子改名→删除”,再依次完成:核对镜像 SHA、配置端口与数据库实际端口、核对机器生成的 receipt 和完整备份产物、拒绝未知待执行/失败 migration、执行 `prisma migrate deploy`,最后核对四十一条目标 migration 的数据库 checksum、完成状态、关键人员组织表、素材空壳标记、钉钉流程快照表及需求类型和表单字段、员工花名册历史快照表、业绩转化经营数据快照及同步状态表、字段类型与可空性、检测报告原五个可空字段和独立检测日期字段、`api_keys` 三个可空加密列、`api_key_reveal_audits` 关键列、租约/需求类型/API Key reveal 审计索引的精确列顺序、`materials_uploadId_key` 的唯一性/btree/单列/有效就绪状态/active-only 谓词、Logo 默认值,以及 `materials.task_detail_demand_type` 无默认值、`materials.task_detail_private` / `material_permission_pack_items.can_access_private` 默认值为 `false`,并用稳定语义核对 `materials_private_optimization_check`,确认私密任务详情仍被精确限制在“任务-详情 + 优化”条件下,同时确认品牌知识预览切片列为非空文本数组且默认空数组;AI 模型五表、能力证据及用途验证约束/索引也须通过前述结构检查,最后原子写审计 JSON。 apply 成功后立即固定审计文件本身;后续“迁移批次部署”读取这一个文件,不能手工重写: diff --git a/lib/__tests__/material-access-scope-storage.test.ts b/lib/__tests__/material-access-scope-storage.test.ts new file mode 100644 index 00000000..46c9af3d --- /dev/null +++ b/lib/__tests__/material-access-scope-storage.test.ts @@ -0,0 +1,58 @@ +/** @jest-environment node */ + +import { mkdtemp, readFile, rm, writeFile } from 'fs/promises' +import os from 'os' +import path from 'path' +import { existsSync } from 'fs' +import { prepareOperationsGMaterialFiles } from '@/lib/material-access-scope-storage' +import { downloadS3ObjectToFile } from '@/lib/s3' +import { resolveStoredUploadPath } from '@/lib/upload-paths' + +jest.mock('@/lib/s3', () => ({ downloadS3ObjectToFile: jest.fn(), uploadToS3: jest.fn(), uploadFileToS3: jest.fn() })) + +let root: string +const prior = { upload: process.env.UPLOAD_DIR, domain: process.env.S3_PUBLIC_DOMAIN, prefix: process.env.S3_FILE_PATH } +beforeEach(async () => { + root = await mkdtemp(path.join(os.tmpdir(), 'material-scope-storage-')) + process.env.UPLOAD_DIR = root + process.env.S3_PUBLIC_DOMAIN = 'https://storage.scope.local' + process.env.S3_FILE_PATH = 'scope' + jest.clearAllMocks() + ;(downloadS3ObjectToFile as jest.Mock).mockImplementation(async (url: string, destination: string) => { + await writeFile(destination, Buffer.from(`object:${url}`)) + }) +}) +afterEach(async () => { + for (const [key, value] of Object.entries({ UPLOAD_DIR: prior.upload, S3_PUBLIC_DOMAIN: prior.domain, S3_FILE_PATH: prior.prefix })) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } + expect(root.startsWith(path.join(os.tmpdir(), 'material-scope-storage-'))).toBe(true) + await rm(root, { recursive: true, force: true }) +}) + +test('更改范围时复制公开原件与预览,素材、资产和 SKU 共享同一份受保护文件', async () => { + const preview = 'https://storage.scope.local/scope/preview.webp' + const source = 'https://storage.scope.local/scope/source.zip' + const result = await prepareOperationsGMaterialFiles({ + id: 'material-1', previewUrl: preview, zipFilePath: source, zipFileName: 'source.zip', displayImages: [preview], + }, [{ id: 'asset-1', fileUrl: preview }], [{ id: 'sku-1', filePath: source, previewUrl: preview }]) + expect(downloadS3ObjectToFile).toHaveBeenCalledTimes(2) + expect(result.assetFiles[0].fileUrl).toBe(result.materialFiles.previewUrl) + expect(result.skuFiles[0].previewUrl).toBe(result.materialFiles.previewUrl) + expect(result.skuFiles[0].filePath).toBe(result.materialFiles.zipFilePath) + expect(result.publicUrls).toEqual([preview, source]) + const stored = result.materialFiles.previewUrl as string + expect(stored).toMatch(/^uploads\/materials\/material-1\/protected-display\//) + expect(await readFile(resolveStoredUploadPath(stored), 'utf8')).toBe(`object:${preview}`) +}) + +test('白底图的派生预览迁入可按原图定位的鉴权目录', async () => { + const result = await prepareOperationsGMaterialFiles({ id: 'material-1' }, [{ + id: 'asset-1', fileUrl: 'uploads/materials/material-1/white-background/sku-1/front.webp', + }]) + const expected = 'uploads/materials/material-1/protected-display/white-background/material-1/sku-1/front.webp' + expect(existsSync(resolveStoredUploadPath(expected))).toBe(true) + expect(result.publicUrls).toEqual(['https://storage.scope.local/scope/public-display/white-background/material-1/sku-1/front.webp']) + expect(result.assetFiles).toEqual([]) +}) diff --git a/lib/__tests__/material-access-scope.test.ts b/lib/__tests__/material-access-scope.test.ts new file mode 100644 index 00000000..d9585c6c --- /dev/null +++ b/lib/__tests__/material-access-scope.test.ts @@ -0,0 +1,118 @@ +/** @jest-environment node */ + +import { prisma } from '@/lib/prisma' +import { getEmployeeByUserId, getEmployeeOrganizationPathsByUserId } from '@/lib/employee-directory' +import { canUserAccessPrivateTaskDetail } from '@/lib/user-permission-inherit' +import { canAccessOperationsGMaterials, resolveMaterialUploadAccessScope, OPERATIONS_G_SOURCE_DEPT_ID } from '@/lib/material-organization-access' +import { canAccessMaterialPrivacy, buildMaterialPrivacyWhere } from '@/lib/task-detail-privacy' +import { buildMaterialWhereFromSearchParams } from '@/lib/material-query' +import { normalizeTaskDetailPrivacyFields } from '@/lib/task-detail-privacy-fields' + +jest.mock('@/lib/prisma', () => ({ prisma: { organizationUnit: { findUnique: jest.fn() } } })) +jest.mock('@/lib/employee-directory', () => ({ + getEmployeeByUserId: jest.fn(), getEmployeeOrganizationPathsByUserId: jest.fn(), +})) +jest.mock('@/lib/user-permission-inherit', () => ({ canUserAccessPrivateTaskDetail: jest.fn() })) +jest.mock('@/lib/department-permission', () => ({ + isSuperAdmin: jest.fn(), isSystemAdmin: jest.fn(), getUserViewableMaterialTypes: jest.fn(), +})) + +const root = '江苏简尚品牌管理有限公司/运营中心G' +const exclusive = { accessScope: 'operations_g', userId: 'uploader', taskDetailRequesterUserId: 'requester', taskDetailPrivate: false } + +beforeEach(() => { + jest.clearAllMocks() + ;(prisma.organizationUnit.findUnique as jest.Mock).mockResolvedValue({ path: root, isActive: true }) + ;(getEmployeeByUserId as jest.Mock).mockResolvedValue({ employmentState: 'ACTIVE' }) + ;(getEmployeeOrganizationPathsByUserId as jest.Mock).mockResolvedValue([`${root}/运营七部(HZ)/设计组`]) + ;(canUserAccessPrivateTaskDetail as jest.Mock).mockResolvedValue(false) +}) + +test.each([root, `${root}/运营七部(HZ)/设计组`, `${root}/运营一部(CZ)/京东一组`])( + '整个中心及其下属部门可以访问:%s', async (memberPath) => { + ;(getEmployeeOrganizationPathsByUserId as jest.Mock).mockResolvedValue([memberPath]) + expect(await canAccessOperationsGMaterials('member')).toBe(true) + expect(prisma.organizationUnit.findUnique).toHaveBeenCalledWith({ + where: { sourceDeptId: OPERATIONS_G_SOURCE_DEPT_ID }, select: { path: true, isActive: true }, + }) + }, +) + +test.each([{ paths: [] }, { paths: ['江苏简尚品牌管理有限公司/运营中心A'] }, { paths: [`${root}二部/设计组`] }])( + '其他中心、无绑定及相似名称不能获得专属权限:%j', async ({ paths }) => { + ;(getEmployeeOrganizationPathsByUserId as jest.Mock).mockResolvedValue(paths) + expect(await canAccessOperationsGMaterials('other')).toBe(false) + }, +) + +test('离职成员和失效组织均失去专属资格', async () => { + ;(getEmployeeByUserId as jest.Mock).mockResolvedValue({ employmentState: 'RESIGNED' }) + expect(await canAccessOperationsGMaterials('member')).toBe(false) + ;(getEmployeeByUserId as jest.Mock).mockResolvedValue({ employmentState: 'ACTIVE' }) + ;(prisma.organizationUnit.findUnique as jest.Mock).mockResolvedValue({ path: root, isActive: false }) + expect(await canAccessOperationsGMaterials('member')).toBe(false) +}) + +test('保留现有组织成员口径,已绑定成员的未知在职状态不等同于离职', async () => { + ;(getEmployeeByUserId as jest.Mock).mockResolvedValue({ employmentState: 'UNKNOWN' }) + expect(await canAccessOperationsGMaterials('member')).toBe(true) +}) + +test('稳定部门编号绑定当前组织路径,组织改名后仍使用当前边界', async () => { + const renamed = '江苏简尚品牌管理有限公司/运营中心G新名称' + ;(prisma.organizationUnit.findUnique as jest.Mock).mockResolvedValue({ path: renamed, isActive: true }) + ;(getEmployeeOrganizationPathsByUserId as jest.Mock).mockResolvedValue([`${renamed}/设计组`]) + expect(await canAccessOperationsGMaterials('member')).toBe(true) +}) + +test('专属素材在中心内共享,无需个人私密授权', async () => { + expect(await canAccessMaterialPrivacy(exclusive, 'any-g-member')).toBe(true) + expect(canUserAccessPrivateTaskDetail).not.toHaveBeenCalled() +}) + +test.each(['requester', 'uploader', 'super-admin'])('中心外不能凭需求人、上传者或管理员身份访问:%s', async (userId) => { + ;(getEmployeeOrganizationPathsByUserId as jest.Mock).mockResolvedValue(['江苏简尚品牌管理有限公司/品牌中心']) + ;(canUserAccessPrivateTaskDetail as jest.Mock).mockResolvedValue(true) + expect(await canAccessMaterialPrivacy(exclusive, userId)).toBe(false) + expect(canUserAccessPrivateTaskDetail).not.toHaveBeenCalled() +}) + +test('匿名访问专属素材被拒绝,通用素材保留原有准入', async () => { + expect(await canAccessMaterialPrivacy(exclusive, null)).toBe(false) + expect(await canAccessMaterialPrivacy({ accessScope: 'general' }, null)).toBe(true) +}) + +test('上传校验拒绝非法范围和中心外专属上传', async () => { + await expect(resolveMaterialUploadAccessScope('any-department', 'member')).rejects.toMatchObject({ status: 400 }) + ;(getEmployeeOrganizationPathsByUserId as jest.Mock).mockResolvedValue([]) + await expect(resolveMaterialUploadAccessScope('operations_g', 'other')).rejects.toMatchObject({ status: 403 }) + expect(await resolveMaterialUploadAccessScope(undefined, 'other')).toBe('general') +}) + +test('专属素材不能叠加个人私密,不受新品或优化限制', () => { + expect(() => normalizeTaskDetailPrivacyFields({ accessScope: 'operations_g', taskDetailPrivate: true })).toThrow('不能设为个人私密') + for (const taskDetailDemandType of ['新品', '优化']) { + expect(normalizeTaskDetailPrivacyFields({ accessScope: 'operations_g', taskDetailDemandType }).taskDetailPrivate).toBe(false) + } +}) + +test('中心内可浏览各类型专属素材,通用素材继续遵守原类型权限', async () => { + const result = await buildMaterialWhereFromSearchParams(new URLSearchParams('materialType=视频&search=SPU'), { id: 'member' }, { + context: { canAccessDeleted: false, expandedViewableTypes: ['任务-详情'], isSuperAdmin: false, + canAccessOperationsGMaterials: true, searchOrConditions: [{ productModel: { contains: 'SPU' } }] }, + }) + expect(result.empty).toBe(false) + expect(result.where.AND[0].OR).toEqual(expect.arrayContaining([ + { accessScope: 'general', taskDetailPrivate: false, materialType: { in: ['任务-详情'] } }, + { accessScope: 'operations_g' }, + ])) + expect(result.where.OR).toEqual([{ productModel: { contains: 'SPU' } }]) +}) + +test('列表、收藏、月份计数的共用过滤不向中心外泄露专属条目', async () => { + ;(getEmployeeOrganizationPathsByUserId as jest.Mock).mockResolvedValue([]) + const outside = await buildMaterialPrivacyWhere('other') + expect(outside.OR.every((branch: any) => branch.accessScope === 'general')).toBe(true) + ;(getEmployeeOrganizationPathsByUserId as jest.Mock).mockResolvedValue([root]) + expect((await buildMaterialPrivacyWhere('member')).OR).toContainEqual({ accessScope: 'operations_g' }) +}) diff --git a/lib/__tests__/material-query.test.ts b/lib/__tests__/material-query.test.ts index 901a7655..88cf7d76 100644 --- a/lib/__tests__/material-query.test.ts +++ b/lib/__tests__/material-query.test.ts @@ -1,3 +1,4 @@ +jest.mock('@/lib/material-organization-access', () => ({ canAccessOperationsGMaterials: jest.fn().mockResolvedValue(false) })) import { prisma } from '@/lib/prisma' import { SPECIAL_INIT_MATERIAL_TYPES, diff --git a/lib/__tests__/material-update.test.ts b/lib/__tests__/material-update.test.ts index 7b9978dc..49cddbe9 100644 --- a/lib/__tests__/material-update.test.ts +++ b/lib/__tests__/material-update.test.ts @@ -1122,6 +1122,7 @@ describe('material-update shared rules', () => { Buffer.from('compressed'), expect.stringMatching(/^materials\/preview-\d+-[0-9a-f-]{36}-cover\.png$/), 'image/webp', + undefined, ) expect(uploadToS3).not.toHaveBeenCalled() expect(deleteFileIfUnreferenced).toHaveBeenCalledWith( diff --git a/lib/__tests__/materials-facets-route.test.ts b/lib/__tests__/materials-facets-route.test.ts index e3e8b34e..93768446 100644 --- a/lib/__tests__/materials-facets-route.test.ts +++ b/lib/__tests__/materials-facets-route.test.ts @@ -1,4 +1,9 @@ /** @jest-environment node */ +jest.mock('@/lib/material-organization-access', () => ({ + ...jest.requireActual('@/lib/material-organization-access'), + canAccessOperationsGMaterials: jest.fn().mockResolvedValue(false), +})) + import { getServerSession } from 'next-auth' import { prisma } from '@/lib/prisma' @@ -82,8 +87,8 @@ describe('materials facets route', () => { expect(createMaterialQueryContext).toHaveBeenCalledTimes(1) expect(buildMaterialWhereFromSearchParams).toHaveBeenCalledTimes(7) expect(prisma.material.count).toHaveBeenCalledTimes(1) - expect(prisma.material.groupBy).toHaveBeenCalledTimes(5) - expect(prisma.material.findMany).toHaveBeenCalledTimes(1) + expect(prisma.material.groupBy).toHaveBeenCalledTimes(6) + expect(prisma.material.findMany).not.toHaveBeenCalled() expect(maxActiveQueries).toBeLessThanOrEqual(3) const context = (createMaterialQueryContext as jest.Mock).mock.results[0].value @@ -103,6 +108,7 @@ describe('materials facets route', () => { .mockResolvedValueOnce([{ sceneName: '室内', _count: { _all: 3 } }]) .mockResolvedValueOnce([{ platformName: '站内', _count: { _all: 4 } }]) .mockResolvedValueOnce([{ productCategoryName: '桌类', _count: { _all: 5 } }]) + .mockResolvedValueOnce([{ createdAt: new Date('2026-07-01T00:00:00.000Z'), _count: { _all: 2 } }]) .mockResolvedValueOnce([{ materialType: '任务-详情', _count: { _all: 6 } }]) ;(prisma.material.findMany as jest.Mock).mockResolvedValue([ { createdAt: new Date('2026-07-01T00:00:00.000Z') }, @@ -125,4 +131,30 @@ describe('materials facets route', () => { month: 2, }) }) + + test('同角色同旧部门的不同账号不能共享专属素材统计缓存', async () => { + ;(prisma.material.groupBy as jest.Mock).mockResolvedValue([]) + ;(prisma.material.count as jest.Mock).mockResolvedValueOnce(9).mockResolvedValueOnce(1) + const request = { nextUrl: { searchParams: new URLSearchParams('cache-case=organization-users') } } as any + ;(getServerSession as jest.Mock).mockResolvedValue({ user: { id: 'g-member', role: 'ADMIN', department: '运营中心' } }) + const first = await GET(request) + ;(getServerSession as jest.Mock).mockResolvedValue({ user: { id: 'outside-member', role: 'ADMIN', department: '运营中心' } }) + const second = await GET(request) + expect((await first.json()).total).toBe(9) + expect((await second.json()).total).toBe(1) + expect(second.headers.get('cache-control')).toContain('no-store') + }) + + test('同一账号调出运营中心 G 后不会命中原来的专属统计缓存', async () => { + ;(prisma.material.groupBy as jest.Mock).mockResolvedValue([]) + ;(prisma.material.count as jest.Mock).mockResolvedValueOnce(9).mockResolvedValueOnce(1) + const context = { canAccessDeleted: false, expandedViewableTypes: ['任务-详情'], isSuperAdmin: false } + ;(createMaterialQueryContext as jest.Mock) + .mockResolvedValueOnce({ ...context, canAccessOperationsGMaterials: true }) + .mockResolvedValueOnce({ ...context, canAccessOperationsGMaterials: false }) + const request = { nextUrl: { searchParams: new URLSearchParams('cache-case=organization-transfer') } } as any + expect((await (await GET(request)).json()).total).toBe(9) + expect((await (await GET(request)).json()).total).toBe(1) + expect(createMaterialQueryContext).toHaveBeenCalledTimes(2) + }) }) diff --git a/lib/__tests__/materials-route-ai-generated.test.ts b/lib/__tests__/materials-route-ai-generated.test.ts index cb7846ea..1dfb9945 100644 --- a/lib/__tests__/materials-route-ai-generated.test.ts +++ b/lib/__tests__/materials-route-ai-generated.test.ts @@ -1,4 +1,9 @@ /** @jest-environment node */ +jest.mock('@/lib/material-organization-access', () => ({ + ...jest.requireActual('@/lib/material-organization-access'), + canAccessOperationsGMaterials: jest.fn().mockResolvedValue(false), +})) + import { NextRequest } from 'next/server' import { getServerSession } from 'next-auth' @@ -226,8 +231,8 @@ describe('materials route ai generated', () => { expect(body.totalCount).toBe(0) expect(prisma.material.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: expect.objectContaining({ AND: [{ OR: [ - { taskDetailPrivate: false, materialType: { in: ['买家秀图片'] } }, - { materialType: '任务-详情', taskDetailPrivate: true, taskDetailRequesterUserId: 'user-1' }, + { taskDetailPrivate: false, accessScope: 'general', materialType: { in: ['买家秀图片'] } }, + { materialType: '任务-详情', taskDetailPrivate: true, accessScope: 'general', taskDetailRequesterUserId: 'user-1' }, ] }] }), })) }) diff --git a/lib/__tests__/product-package-abort-route-security.test.ts b/lib/__tests__/product-package-abort-route-security.test.ts index 077cda13..af1b8c7d 100644 --- a/lib/__tests__/product-package-abort-route-security.test.ts +++ b/lib/__tests__/product-package-abort-route-security.test.ts @@ -5,6 +5,9 @@ import { getServerSession } from 'next-auth' import { prisma } from '@/lib/prisma' import { getOwnedUploadSession } from '@/lib/upload-sessions' import { safelyCleanupMaterialUploadSession } from '@/lib/temp-cleanup' +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' + +jest.mock('@/lib/material-organization-access', () => ({ canAccessOperationsGMaterials: jest.fn() })) jest.mock('next-auth', () => ({ getServerSession: jest.fn(), @@ -42,6 +45,19 @@ jest.mock('@/lib/temp-cleanup', () => ({ })) describe('product-package abort route security', () => { + test('调出运营中心 G 的上传者不能撤销专属素材', async () => { + ;(prisma.material.findUnique as jest.Mock).mockResolvedValue({ + id: 'material-1', userId: 'user-1', materialType: '任务-详情', accessScope: 'operations_g', + }) + ;(canAccessOperationsGMaterials as jest.Mock).mockResolvedValue(false) + const response = await POST(new Request('http://localhost/api/materials/upload/product-package/abort', { + method: 'POST', body: JSON.stringify({ materialId: 'material-1', uploadIds: [] }), + }) as any) + expect(response.status).toBe(403) + expect(prisma.material.delete).not.toHaveBeenCalled() + expect(safelyCleanupMaterialUploadSession).not.toHaveBeenCalled() + }) + beforeEach(() => { jest.clearAllMocks() ;(getServerSession as jest.Mock).mockResolvedValue({ diff --git a/lib/__tests__/product-package-task-no-lock.test.ts b/lib/__tests__/product-package-task-no-lock.test.ts index 39a60eb1..4519c990 100644 --- a/lib/__tests__/product-package-task-no-lock.test.ts +++ b/lib/__tests__/product-package-task-no-lock.test.ts @@ -56,6 +56,15 @@ describe('任务号完成写入并发锁', () => { expect(lockName).toBe('task-no:TASK202604230001') }) + test('任务号冲突不暴露专属素材型号', async () => { + ;(prisma.material.findFirst as jest.Mock).mockResolvedValue({ + id: 'g-material', productModel: 'G-PRIVATE-SPU', materialType: '任务-详情', accessScope: 'operations_g', + }) + await expect(assignTaskNoOnComplete('material-a', 'TASK202604230001')) + .rejects.toEqual(new Error('任务号 TASK202604230001 已存在')) + expect(prisma.$transaction).not.toHaveBeenCalled() + }) + test('两个素材并发完成同一任务号时只能一个写入成功', async () => { let assignedMaterialId: string | null = null let transactionTail = Promise.resolve() diff --git a/lib/__tests__/sku-route-authorization.test.ts b/lib/__tests__/sku-route-authorization.test.ts index 9149953b..59897436 100644 --- a/lib/__tests__/sku-route-authorization.test.ts +++ b/lib/__tests__/sku-route-authorization.test.ts @@ -13,6 +13,9 @@ import { POST as uploadSku } from '@/app/api/materials/[id]/skus/upload/route' import { PUT as reorderSkus } from '@/app/api/materials/[id]/skus/reorder/route' import { GET as downloadSku } from '@/app/api/materials/[id]/skus/[skuId]/download/route' import { POST as batchDownloadSkus } from '@/app/api/materials/[id]/skus/batch-download/route' +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' + +jest.mock('@/lib/material-organization-access', () => ({ canAccessOperationsGMaterials: jest.fn().mockResolvedValue(false) })) jest.mock('next-auth', () => ({ getServerSession: jest.fn() })) jest.mock('@/lib/auth', () => ({ authOptions: {} })) @@ -67,6 +70,7 @@ describe('SKU routes object authorization', () => { ;(canManageSkuMaterial as jest.Mock).mockResolvedValue(false) ;(canDownloadSkuMaterial as jest.Mock).mockResolvedValue(false) ;(prisma.user.findUnique as jest.Mock).mockResolvedValue({ canDownload: true }) + ;(prisma.material.findUnique as jest.Mock).mockResolvedValue(material) }) test.each([ @@ -131,6 +135,17 @@ describe('SKU routes object authorization', () => { })) }) + test.each([null, { user: { id: 'outside-admin', role: 'ADMIN', isSuperAdmin: true } }])( + '匿名与中心外管理员不能读取专属 SKU 详情:%j', async (actor) => { + ;(getServerSession as jest.Mock).mockResolvedValue(actor) + ;(prisma.material.findUnique as jest.Mock).mockResolvedValue({ ...material, accessScope: 'operations_g' }) + ;(canAccessOperationsGMaterials as jest.Mock).mockResolvedValue(false) + const response = await getSku({} as any, { params: { id: 'material-1', skuId: 'sku-1' } }) + expect(response.status).toBe(actor ? 403 : 401) + expect(prisma.materialSku.findFirst).not.toHaveBeenCalled() + }, + ) + test('无素材下载权限时单个和批量下载均在读文件前拒绝', async () => { ;(prisma.material.findFirst as jest.Mock).mockResolvedValue(material) diff --git a/lib/__tests__/task-detail-privacy.test.ts b/lib/__tests__/task-detail-privacy.test.ts index 2444c06f..e5598ae4 100644 --- a/lib/__tests__/task-detail-privacy.test.ts +++ b/lib/__tests__/task-detail-privacy.test.ts @@ -1,4 +1,5 @@ /** @jest-environment node */ +jest.mock('@/lib/material-organization-access', () => ({ canAccessOperationsGMaterials: jest.fn().mockResolvedValue(false) })) import { mkdtemp, mkdir, writeFile, rm } from 'fs/promises' import os from 'os' @@ -6,6 +7,7 @@ import path from 'path' import { NextRequest } from 'next/server' import { getServerSession } from 'next-auth' import { prisma } from '@/lib/prisma' +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' import { canUserAccessPrivateTaskDetail } from '@/lib/user-permission-inherit' import { canAccessMaterialPrivacy, isPrivateTaskDetail } from '@/lib/task-detail-privacy' import { buildMaterialWhereFromSearchParams } from '@/lib/material-query' @@ -25,6 +27,7 @@ jest.mock('@/lib/path-security', () => ({ jest.mock('@/lib/prisma', () => ({ prisma: { material: { findMany: jest.fn(), findFirst: jest.fn(), findUnique: jest.fn() }, materialAsset: { findMany: jest.fn() }, + materialSku: { findMany: jest.fn().mockResolvedValue([]) }, user: { findUnique: jest.fn() }, } })) jest.mock('@/lib/user-permission-inherit', () => ({ canUserAccessPrivateTaskDetail: jest.fn(), canUserEditTaskDetailAssets: jest.fn().mockResolvedValue(false) })) @@ -45,6 +48,7 @@ const material = { beforeEach(() => { jest.clearAllMocks() + ;(canAccessOperationsGMaterials as jest.Mock).mockResolvedValue(false) ;(canUserAccessPrivateTaskDetail as jest.Mock).mockResolvedValue(false) ;(prisma.material.findFirst as jest.Mock).mockResolvedValue({ ...material, zipFileSize: BigInt(0), assets: [] }) ;(prisma.material.findUnique as jest.Mock).mockResolvedValue(material) @@ -106,7 +110,7 @@ test.each([false, true])('列表在搜索和分页前叠加私密过滤,超管 expect(result.where.materialType).toEqual({ in: ['任务-详情', '产品全案'] }) expect(result.where.OR).toEqual([{ productModel: { contains: 'SPU' } }]) expect(result.where.AND[0].OR[0].taskDetailPrivate).toBe(false) - expect(result.where.AND[0].OR[1]).toEqual({ materialType: '任务-详情', taskDetailPrivate: true, taskDetailRequesterUserId: 'requester' }) + expect(result.where.AND[0].OR[1]).toEqual({ materialType: '任务-详情', taskDetailPrivate: true, accessScope: 'general', taskDetailRequesterUserId: 'requester' }) }) test('私密权限组无需按需求运营过滤,公开类型权限仍在', async () => { @@ -114,8 +118,8 @@ test('私密权限组无需按需求运营过滤,公开类型权限仍在', as context: { canAccessDeleted: false, expandedViewableTypes: ['视频'], isSuperAdmin: false, canAccessPrivateTaskDetails: true }, }) expect(result.where.AND[0].OR).toEqual([ - { taskDetailPrivate: false, materialType: { in: ['视频'] } }, - { materialType: '任务-详情', taskDetailPrivate: true }, + { taskDetailPrivate: false, accessScope: 'general', materialType: { in: ['视频'] } }, + { materialType: '任务-详情', taskDetailPrivate: true, accessScope: 'general' }, ]) }) @@ -149,6 +153,28 @@ describe('私密预览真实文件入口', () => { expect(response.headers.get('cache-control')).toBe('private, no-store') expect(await response.text()).toBe('private-image-bytes') }) + + test('未被源文件记录引用的旧原件不能按派生预览放行', async () => { + const sourceSegments = ['materials', 'private-one', 'protected-display', 'source.zip'] + await mkdir(path.join(root, ...sourceSegments.slice(0, -1)), { recursive: true }) + await writeFile(path.join(root, ...sourceSegments), 'source-bytes') + ;(prisma.material.findMany as jest.Mock).mockResolvedValue([]) + const response = await GET(new NextRequest(`https://example.com/api/uploads/${sourceSegments.join('/')}`), { params: { path: sourceSegments } }) + expect(response.status).toBe(404) + }) + + test('中心内成员可读取独立生成的专属白底预览', async () => { + const previewSegments = ['materials', 'private-one', 'protected-display', 'white-background', 'private-one', 'sku-1', 'front.webp'] + await mkdir(path.join(root, ...previewSegments.slice(0, -1)), { recursive: true }) + await writeFile(path.join(root, ...previewSegments), 'white-background-preview') + ;(prisma.material.findMany as jest.Mock).mockResolvedValue([]) + ;(prisma.material.findFirst as jest.Mock).mockResolvedValue({ ...material, accessScope: 'operations_g', taskDetailPrivate: false }) + ;(canAccessOperationsGMaterials as jest.Mock).mockResolvedValue(true) + const response = await GET(new NextRequest(`https://example.com/api/uploads/${previewSegments.join('/')}`), { params: { path: previewSegments } }) + expect(response.status).toBe(200) + expect(response.headers.get('cache-control')).toContain('no-store') + expect(await response.text()).toBe('white-background-preview') + }) test.each(['requester', 'group-member'])('私密准入者可下载实际文件且不缓存:%s', async (userId) => { ;(getServerSession as jest.Mock).mockResolvedValue({ user: { id: userId, role: 'USER' } }) ;(canUserAccessPrivateTaskDetail as jest.Mock).mockResolvedValue(userId === 'group-member') @@ -169,3 +195,9 @@ describe('私密预览真实文件入口', () => { } }) }) + + +test('有效外部下载 token 不能绕过运营中心 G 的组织范围', async () => { + ;(prisma.material.findFirst as jest.Mock).mockResolvedValue({ ...material, accessScope: 'operations_g', taskDetailPrivate: false }) + expect((await getExternalDownload(new NextRequest('https://example.com/api/external/download?token=valid-old-token'))).status).toBe(404) +}) diff --git a/lib/__tests__/task-material-processor.test.ts b/lib/__tests__/task-material-processor.test.ts index 1bc57176..ca5ff003 100644 --- a/lib/__tests__/task-material-processor.test.ts +++ b/lib/__tests__/task-material-processor.test.ts @@ -91,6 +91,7 @@ describe('task-material-processor', () => { Buffer.from('compressed-image'), expect.stringMatching(/^materials\/preview-1711111111111-0-[a-z0-9]+\.webp$/), 'image/webp', + undefined, ) expect(readBoundedRegularFile).toHaveBeenCalledWith( '/tmp/uploaded/image.png', diff --git a/lib/__tests__/transcode-route-authorization.test.ts b/lib/__tests__/transcode-route-authorization.test.ts index e9ebe82e..6f55e0a5 100644 --- a/lib/__tests__/transcode-route-authorization.test.ts +++ b/lib/__tests__/transcode-route-authorization.test.ts @@ -6,6 +6,9 @@ import { POST } from '@/app/api/materials/transcode/route' import { prisma } from '@/lib/prisma' import { hasSystemAdminPermission } from '@/lib/department-permission' import { transcodeQueue } from '@/lib/video-transcode-queue' +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' + +jest.mock('@/lib/material-organization-access', () => ({ canAccessOperationsGMaterials: jest.fn() })) jest.mock('next-auth', () => ({ getServerSession: jest.fn(), @@ -20,6 +23,7 @@ jest.mock('@/lib/prisma', () => ({ material: { count: jest.fn(), findFirst: jest.fn(), + findMany: jest.fn(), }, }, })) @@ -60,6 +64,7 @@ function createRequest() { describe('transcode route authorization', () => { beforeEach(() => { jest.clearAllMocks() + ;(canAccessOperationsGMaterials as jest.Mock).mockResolvedValue(true) ;(transcodeQueue.add as jest.Mock).mockResolvedValue(undefined) ;(getServerSession as jest.Mock).mockResolvedValue({ user: { id: 'owner-1', role: 'USER', isSuperAdmin: false }, @@ -151,4 +156,36 @@ describe('transcode route authorization', () => { expect(response.status).toBe(409) expect(transcodeQueue.add).not.toHaveBeenCalled() }) + + test('调出运营中心 G 的上传者不能重试专属视频,管理员也不能越过组织范围', async () => { + ;(getServerSession as jest.Mock).mockResolvedValue({ user: { id: 'moved-owner', role: 'ADMIN' } }) + ;(hasSystemAdminPermission as jest.Mock).mockReturnValue(true) + ;(canAccessOperationsGMaterials as jest.Mock).mockResolvedValue(false) + ;(prisma.material.findFirst as jest.Mock).mockResolvedValue({ + id: 'material-1', userId: 'moved-owner', accessScope: 'operations_g', + materialType: '淘系-主图视频', videoSourceUrl: 'uploads/video.mp4', videoProcessingStatus: 'failed', + }) + expect((await POST(createRequest())).status).toBe(403) + expect(transcodeQueue.add).not.toHaveBeenCalled() + }) + + test('中心外管理员的转码队列只返回通用素材', async () => { + ;(getServerSession as jest.Mock).mockResolvedValue({ user: { id: 'outside-admin', role: 'ADMIN' } }) + ;(hasSystemAdminPermission as jest.Mock).mockReturnValue(true) + ;(canAccessOperationsGMaterials as jest.Mock).mockResolvedValue(false) + ;(prisma.material.findMany as jest.Mock).mockResolvedValue([{ id: 'material-1' }]) + ;(transcodeQueue.getStatus as jest.Mock).mockReturnValueOnce({ + waiting: ['g-video'], processingIds: ['material-1'], maxConcurrent: 1, + progress: new Map([['g-video', 20]]), stages: new Map([['g-video', 'processing']]), + }) + const response = await POST(createRequest()) + expect(response.status).toBe(200) + const body = await response.json() + expect(body.queueStatus.waiting).toEqual([]) + expect(body.queueStatus.processingIds).toEqual(['material-1']) + expect(body.queueStatus.queueLength).toBe(0) + expect(prisma.material.findMany).toHaveBeenCalledWith(expect.objectContaining({ + where: { id: { in: ['g-video', 'material-1'] }, accessScope: 'general' }, + })) + }) }) diff --git a/lib/__tests__/white-background-upload-route.test.ts b/lib/__tests__/white-background-upload-route.test.ts index 65846c18..6f3a7a34 100644 --- a/lib/__tests__/white-background-upload-route.test.ts +++ b/lib/__tests__/white-background-upload-route.test.ts @@ -197,6 +197,7 @@ describe('white-background upload route', () => { /^white-background\/material-1\/sku-1\/XG014799-鞋柜-右前45°--[0-9a-f-]{36}\.webp$/, ), 'image/webp', + undefined, ) expect(fsPromises.open).toHaveBeenCalledWith( expect.stringMatching( diff --git a/lib/admin-material-stats.ts b/lib/admin-material-stats.ts index e1e5d3f7..347703ab 100644 --- a/lib/admin-material-stats.ts +++ b/lib/admin-material-stats.ts @@ -1,6 +1,7 @@ import { prisma } from '@/lib/prisma' export interface MaterialStatsFilters { + accessWhere?: { accessScope?: string } startDate?: string | null endDate?: string | null departmentKey?: string | null @@ -223,8 +224,9 @@ export async function getMaterialUploadStats( createdAtFilter.lte = toDateEnd(filters.endDate) } - const materialWhere: { deletedAt: null; createdAt?: { gte?: Date; lte?: Date } } = { + const materialWhere: { deletedAt: null; accessScope?: string; createdAt?: { gte?: Date; lte?: Date } } = { deletedAt: null, + ...(filters.accessWhere || { accessScope: 'general' }), } if (createdAtFilter.gte || createdAtFilter.lte) { @@ -366,6 +368,7 @@ export async function getMaterialUploadStats( where: { deletedAt: null, userId: { in: selectedUserIds }, + ...(filters.accessWhere || { accessScope: 'general' }), ...(materialWhere.createdAt ? { createdAt: materialWhere.createdAt } : {}), }, select: { diff --git a/lib/external-auto-listing.ts b/lib/external-auto-listing.ts index 0f0fd14d..a2782cf0 100644 --- a/lib/external-auto-listing.ts +++ b/lib/external-auto-listing.ts @@ -525,6 +525,7 @@ export async function updateExternalNotificationTarget( } export async function listExternalNotificationDeliveries(options?: { + canAccessOperationsG?: boolean status?: string targetId?: string materialId?: string @@ -534,6 +535,10 @@ export async function listExternalNotificationDeliveries(options?: { const conditions = ['1 = 1'] const params: any[] = [] + if (!options?.canAccessOperationsG) { + conditions.push(`NOT EXISTS (SELECT 1 FROM materials m WHERE m.id = d.material_id AND m.access_scope = 'operations_g')`) + conditions.push(`NOT EXISTS (SELECT 1 FROM material_purge_jobs p WHERE p.material_id = d.material_id AND p.material_snapshot->>'accessScope' = 'operations_g')`) + } if (options?.status) { params.push(String(options.status).trim()) @@ -762,7 +767,7 @@ async function buildTaskDetailNotificationPayload(materialId: string) { id: materialId, deletedAt: null, materialType: '任务-详情', - taskDetailPrivate: false, + taskDetailPrivate: false, accessScope: 'general', isFullSet: true, }, select: { @@ -841,7 +846,7 @@ async function buildTaskDetailBarcodeNotificationPayload(materialId: string, ass id: materialId, deletedAt: null, materialType: '任务-详情', - taskDetailPrivate: false, + taskDetailPrivate: false, accessScope: 'general', }, select: { id: true, @@ -905,7 +910,7 @@ async function buildTaskDetailBarcodeNotificationPayload(materialId: string, ass material: { deletedAt: null, materialType: '任务-详情', - taskDetailPrivate: false, + taskDetailPrivate: false, accessScope: 'general', }, }, }, @@ -1146,6 +1151,17 @@ export async function processExternalNotificationDelivery( let requestError: string | null = null try { + const materialId = (claimed.payload as { materialId?: string } | null)?.materialId + if (materialId && !(await prisma.material.findFirst({ + where: { id: materialId, deletedAt: null, accessScope: 'general', taskDetailPrivate: false }, + select: { id: true }, + }))) { + await executeRaw( + `UPDATE "${DELIVERY_TABLE}" SET status = $2, last_error = $3, next_retry_at = NULL, completed_at = NOW(), updated_at = NOW() WHERE id = $1`, + deliveryId, AUTO_LISTING_DELIVERY_STATUS.EXHAUSTED, '素材已不可对外提供', + ) + return { success: false, status: AUTO_LISTING_DELIVERY_STATUS.EXHAUSTED } + } const response = await fetch(claimed.target.callbackUrl, { method: 'POST', headers: buildNotificationHeaders(claimed.target), diff --git a/lib/external-certificate-reports.ts b/lib/external-certificate-reports.ts index b17e0348..dff6e79b 100644 --- a/lib/external-certificate-reports.ts +++ b/lib/external-certificate-reports.ts @@ -53,7 +53,7 @@ export function certificateExpiryStatus(expires: Date | null, today: Date): 'une } const assetTypes = (kind: CertificateReportQuery['fileKind']) => kind === 'pdf' ? ['report-pdf'] : kind === 'image' ? ['report-image'] : ['report-pdf', 'report-image'] export function buildCertificateReportWhere(query: CertificateReportQuery, today = certificateToday()): Prisma.MaterialWhereInput { - const where: Prisma.MaterialWhereInput = { materialType: CERTIFICATE_REPORT_MATERIAL_TYPE, deletedAt: null, isIncompleteShell: false, taskDetailPrivate: false } + const where: Prisma.MaterialWhereInput = { materialType: CERTIFICATE_REPORT_MATERIAL_TYPE, deletedAt: null, isIncompleteShell: false, taskDetailPrivate: false, accessScope: 'general' } if (query.materialId) where.id = query.materialId if (query.search) where.reportTitle = { contains: query.search, mode: 'insensitive' } if (query.reportKind) where.reportKind = query.reportKind @@ -84,8 +84,8 @@ export function reportFileKind(asset: ReportFile): 'pdf' | 'image' | null { return null } /** Only new report-source tokens use this resolver. Recheck current visibility and membership. */ -export function resolveCertificateReportSource(material: { materialType: string; deletedAt?: Date | null; isIncompleteShell?: boolean; taskDetailPrivate?: boolean; assets?: ReportFile[] }, assetId?: string) { - if (material.materialType !== CERTIFICATE_REPORT_MATERIAL_TYPE || material.deletedAt || material.isIncompleteShell || material.taskDetailPrivate || !assetId) return null +export function resolveCertificateReportSource(material: { materialType: string; deletedAt?: Date | null; isIncompleteShell?: boolean; taskDetailPrivate?: boolean; accessScope?: string; assets?: ReportFile[] }, assetId?: string) { + if (material.materialType !== CERTIFICATE_REPORT_MATERIAL_TYPE || material.deletedAt || material.isIncompleteShell || material.accessScope === 'operations_g' || material.taskDetailPrivate || !assetId) return null const asset = material.assets?.find(a => a.id === assetId) return asset && reportFileKind(asset) ? asset : null } diff --git a/lib/external-image-assets.ts b/lib/external-image-assets.ts index 64a2019f..9247a6c5 100644 --- a/lib/external-image-assets.ts +++ b/lib/external-image-assets.ts @@ -51,7 +51,7 @@ export function parseExternalImageQuery(params: URLSearchParams): ExternalImageQ resourceType: resourceType as ExternalImageQuery['resourceType'], page: integer('page', 1, 10000), pageSize: integer('pageSize', 20, 50) } } -const VISIBLE: Prisma.MaterialWhereInput = { deletedAt: null, isIncompleteShell: false, taskDetailPrivate: false } +const VISIBLE: Prisma.MaterialWhereInput = { deletedAt: null, isIncompleteShell: false, taskDetailPrivate: false, accessScope: 'general' } const equal = (value: string) => ({ equals: value, mode: 'insensitive' as const }) async function resolveProduct(query: ExternalImageQuery) { @@ -107,11 +107,11 @@ export interface ExternalImageResource { /** Only the new image-source token reaches this resolver; old callers do not. */ export async function resolveExternalImageDownloadSource(material: { - id: string; materialType: string; deletedAt?: Date | null; taskDetailPrivate?: boolean; isIncompleteShell?: boolean; + id: string; materialType: string; deletedAt?: Date | null; taskDetailPrivate?: boolean; accessScope?: string; isIncompleteShell?: boolean; zipFilePath?: string; zipFileName?: string; assets?: Array<{ id: string; assetType: string; fileUrl: string; fileName?: string | null }>; }, assetId?: string) { const allowed = Object.values(EXTERNAL_IMAGE_RESOURCE_TYPES).flat() as readonly string[] - if (material.deletedAt || material.taskDetailPrivate || material.isIncompleteShell || !allowed.includes(material.materialType)) return null + if (material.deletedAt || material.accessScope === 'operations_g' || material.taskDetailPrivate || material.isIncompleteShell || !allowed.includes(material.materialType)) return null if (assetId) { const asset = material.assets?.find(a => a.id === assetId) if (!asset?.fileUrl.trim()) return null diff --git a/lib/external-standard-model-white-background-by-barcode.ts b/lib/external-standard-model-white-background-by-barcode.ts index ce1fffd7..907d1241 100644 --- a/lib/external-standard-model-white-background-by-barcode.ts +++ b/lib/external-standard-model-white-background-by-barcode.ts @@ -344,6 +344,7 @@ export async function resolveStandardModelSkuByBarcode( const matches = await (prisma as any).materialSkuBarcode.findMany({ where: { barcode: normalizedBarcode, + sku: { material: { accessScope: 'general' } }, deletedAt: null, }, select: { diff --git a/lib/material-access-scope-storage.ts b/lib/material-access-scope-storage.ts new file mode 100644 index 00000000..a72c5a1d --- /dev/null +++ b/lib/material-access-scope-storage.ts @@ -0,0 +1,64 @@ +import { randomUUID } from 'crypto' +import { mkdir } from 'fs/promises' +import path from 'path' +import { downloadS3ObjectToFile } from '@/lib/s3' +import { resolveStoredUploadPath } from '@/lib/upload-paths' +import { buildPublicDisplayUrl, buildWhiteBackgroundPublicDisplayPathFromAssetPath } from '@/lib/public-display' +import { existsSync } from 'fs' + +const MATERIAL_FILE_FIELDS = [ + 'previewUrl', 'zipFilePath', 'zipFileName', 'videoSourceUrl', + 'videoPreview540Url', 'videoPreviewClipUrl', 'videoCoverUrl', +] as const + +/** 将已公开的存储对象改为受素材访问权限保护的独立文件。 */ +export async function prepareOperationsGMaterialFiles( + material: Record, + assets: Array<{ id: string; fileUrl: string }>, + skus: Array<{ id: string; filePath: string; previewUrl: string | null }> = [], +) { + const replacements = new Map() + const copyUrl = async (url: string) => { + if (!/^https?:\/\//i.test(url)) return url + const existing = replacements.get(url) + if (existing) return existing + const fileName = `${randomUUID()}${path.posix.extname(new URL(url).pathname)}` + const storedPath = path.posix.join('uploads', 'materials', material.id, 'protected-display', fileName) + const destination = resolveStoredUploadPath(storedPath) + await mkdir(path.dirname(destination), { recursive: true }) + await downloadS3ObjectToFile(url, destination) + replacements.set(url, storedPath) + return storedPath + } + const materialFiles: Record = {} + for (const field of MATERIAL_FILE_FIELDS) { + if (material[field]) materialFiles[field] = await copyUrl(material[field]) + } + if (Array.isArray(material.displayImages)) { + materialFiles.displayImages = [] + for (const url of material.displayImages) materialFiles.displayImages.push(await copyUrl(url)) + } + const assetFiles = [] + for (const asset of assets) { + const fileUrl = await copyUrl(asset.fileUrl) + if (fileUrl !== asset.fileUrl) assetFiles.push({ id: asset.id, fileUrl }) + const previewPath = buildWhiteBackgroundPublicDisplayPathFromAssetPath(asset.fileUrl) + const publicPreview = previewPath && /\.webp$/i.test(previewPath) ? buildPublicDisplayUrl(previewPath) : null + if (previewPath && publicPreview) { + const storedPath = path.posix.join('uploads', 'materials', material.id, 'protected-display', previewPath) + const destination = resolveStoredUploadPath(storedPath) + if (!existsSync(destination)) { + await mkdir(path.dirname(destination), { recursive: true }) + await downloadS3ObjectToFile(publicPreview, destination) + } + replacements.set(publicPreview, storedPath) + } + } + const skuFiles = [] + for (const sku of skus) { + const filePath = await copyUrl(sku.filePath) + const previewUrl = sku.previewUrl ? await copyUrl(sku.previewUrl) : sku.previewUrl + if (filePath !== sku.filePath || previewUrl !== sku.previewUrl) skuFiles.push({ id: sku.id, filePath, previewUrl }) + } + return { materialFiles, assetFiles, skuFiles, publicUrls: Array.from(replacements.keys()) } +} diff --git a/lib/material-access-scope.ts b/lib/material-access-scope.ts new file mode 100644 index 00000000..78113c90 --- /dev/null +++ b/lib/material-access-scope.ts @@ -0,0 +1,25 @@ +export const MATERIAL_ACCESS_SCOPES = ['general', 'operations_g'] as const + +export type MaterialAccessScope = (typeof MATERIAL_ACCESS_SCOPES)[number] + +export const MATERIAL_ACCESS_SCOPE_LABELS: Record = { + general: '通用素材', + operations_g: '运营中心 G 专属', +} + +export function normalizeMaterialAccessScope(value: unknown): MaterialAccessScope { + if (value == null || value === '') return 'general' + if (value === 'general' || value === 'operations_g') return value + throw new Error('使用范围只能是通用素材或运营中心 G 专属') +} + +export function isOperationsGMaterial(material: { accessScope?: string | null }): boolean { + return material.accessScope === 'operations_g' +} + +export function isRestrictedMaterial(material: { + accessScope?: string | null + taskDetailPrivate?: boolean | null +}): boolean { + return isOperationsGMaterial(material) || material.taskDetailPrivate === true +} diff --git a/lib/material-authorization.ts b/lib/material-authorization.ts index e928c0ae..99a5254c 100644 --- a/lib/material-authorization.ts +++ b/lib/material-authorization.ts @@ -62,7 +62,7 @@ export async function canManageMaterial( material: MaterialAuthorizationTarget, ): Promise { let privacyMaterial: TaskDetailPrivacyMaterial = material - if (material.taskDetailPrivate === undefined && material.id) { + if ((material.taskDetailPrivate === undefined || material.accessScope === undefined) && material.id) { const stored = await prisma.material.findUnique({ where: { id: material.id }, select: TASK_DETAIL_PRIVACY_SELECT, diff --git a/lib/material-facets-cache.ts b/lib/material-facets-cache.ts new file mode 100644 index 00000000..076aa97b --- /dev/null +++ b/lib/material-facets-cache.ts @@ -0,0 +1,26 @@ +type CacheEntry = { data: any; expiresAt: number } +const shared = globalThis as typeof globalThis & { __materialFacetsCache?: Map } +const cache = shared.__materialFacetsCache ||= new Map() +const TTL_MS = 5 * 60 * 1000 + +export function getMaterialFacetsCache(key: string): any | null { + const entry = cache.get(key) + if (!entry) return null + if (Date.now() > entry.expiresAt) { + cache.delete(key) + return null + } + return entry.data +} + +export function setMaterialFacetsCache(key: string, data: any) { + if (cache.size > 200) { + const oldest = cache.keys().next().value + if (oldest) cache.delete(oldest) + } + cache.set(key, { data, expiresAt: Date.now() + TTL_MS }) +} + +export function invalidateMaterialFacetsCache() { + cache.clear() +} diff --git a/lib/material-organization-access.ts b/lib/material-organization-access.ts new file mode 100644 index 00000000..b55885ad --- /dev/null +++ b/lib/material-organization-access.ts @@ -0,0 +1,60 @@ +import { prisma } from '@/lib/prisma' +import { getEmployeeByUserId, getEmployeeOrganizationPathsByUserId } from '@/lib/employee-directory' +import { isUnderOrganizationPath } from '@/lib/organization-material-permissions' +import { normalizeMaterialAccessScope, type MaterialAccessScope } from '@/lib/material-access-scope' + +// HR 组织树中运营中心 G 的稳定部门编号。 +export const OPERATIONS_G_SOURCE_DEPT_ID = 911666246 + +export async function canAccessOperationsGMaterials(userId?: string | null): Promise { + if (!userId) return false + const [employee, paths, organization] = await Promise.all([ + getEmployeeByUserId(userId), + getEmployeeOrganizationPathsByUserId(userId), + prisma.organizationUnit.findUnique({ + where: { sourceDeptId: OPERATIONS_G_SOURCE_DEPT_ID }, + select: { path: true, isActive: true }, + }), + ]) + return employee != null && employee.employmentState !== 'RESIGNED' + && organization?.isActive === true + && paths.some((path) => isUnderOrganizationPath(path, organization.path)) +} + +export class MaterialAccessScopeError extends Error { + constructor(message: string, readonly status = 400) { + super(message) + this.name = 'MaterialAccessScopeError' + } +} + +export async function resolveMaterialUploadAccessScope( + value: unknown, + userId: string, +): Promise { + let scope: MaterialAccessScope + try { + scope = normalizeMaterialAccessScope(value) + } catch (error) { + throw new MaterialAccessScopeError((error as Error).message) + } + if (scope === 'operations_g' && !(await canAccessOperationsGMaterials(userId))) { + throw new MaterialAccessScopeError('仅运营中心 G 成员可以上传或设置专属素材', 403) + } + return scope +} + +export async function buildMaterialOrganizationWhere(userId?: string | null) { + return await canAccessOperationsGMaterials(userId) ? {} : { accessScope: 'general' } +} + +export async function getOperationsGMaterialIds(): Promise { + const [materials, purges] = await Promise.all([ + prisma.material.findMany({ where: { accessScope: 'operations_g' }, select: { id: true } }), + prisma.materialPurgeJob.findMany({ + where: { materialSnapshot: { path: ['accessScope'], equals: 'operations_g' } }, + select: { materialId: true }, + }), + ]) + return Array.from(new Set([...materials.map((row) => row.id), ...purges.map((row) => row.materialId)])) +} diff --git a/lib/material-protected-storage.ts b/lib/material-protected-storage.ts new file mode 100644 index 00000000..62353347 --- /dev/null +++ b/lib/material-protected-storage.ts @@ -0,0 +1,35 @@ +import { mkdir, writeFile, copyFile, stat } from 'fs/promises' +import path from 'path' +import { resolveStoredUploadPath } from '@/lib/upload-paths' + +function protectedDisplayPath(materialId: string, fileName: string) { + return path.posix.join('uploads', 'materials', materialId, 'protected-display', fileName.replace(/\\/g, '/')) +} + +export async function saveProtectedMaterialDisplay( + materialId: string, + fileName: string, + buffer: Buffer, +): Promise { + const storedPath = protectedDisplayPath(materialId, fileName) + const destination = resolveStoredUploadPath(storedPath) + await mkdir(path.dirname(destination), { recursive: true }) + await writeFile(destination, buffer) + return storedPath +} + +export async function saveProtectedMaterialDisplayFile( + materialId: string, + fileName: string, + source: string, + expectedSize?: number, +): Promise { + const storedPath = protectedDisplayPath(materialId, fileName) + const destination = resolveStoredUploadPath(storedPath) + await mkdir(path.dirname(destination), { recursive: true }) + await copyFile(source, destination) + if (expectedSize != null && (await stat(destination)).size !== expectedSize) { + throw new Error('专属素材文件复制不完整') + } + return storedPath +} diff --git a/lib/material-purge.ts b/lib/material-purge.ts index 51e46a44..885f5a88 100644 --- a/lib/material-purge.ts +++ b/lib/material-purge.ts @@ -1,6 +1,8 @@ +import { invalidateMaterialFacetsCache } from '@/lib/material-facets-cache' import { randomUUID } from 'crypto' import { Prisma, type MaterialPurgeJob } from '@prisma/client' import { prisma } from '@/lib/prisma' +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' import { collectPurgeFiles, findPurgeFileReferences, purgeFileIdentity, removePurgeFile, type PurgeFile } from '@/lib/material-purge-files' export class MaterialPurgeError extends Error { @@ -38,12 +40,16 @@ async function lock(tx: Prisma.TransactionClient, name: string) { /** 清单、审计和素材记录删除必须一起提交;请求路径不做物理删除。 */ export async function enqueueMaterialPurge(input: unknown, operatorUserId: string) { const ids = validatePurgeIds(input) - return prisma.$transaction(async tx => { + const result = await prisma.$transaction(async tx => { await lock(tx, 'material-purge-enqueue') await lock(tx, 'product-package-upload-create') await lock(tx, 'product-package-upload-worker') await tx.$queryRaw`SELECT 1 AS locked FROM pg_advisory_xact_lock(193582731)` const jobs = await tx.materialPurgeJob.findMany({ where: { materialId: { in: ids } } }) + if (jobs.some((job) => (job.materialSnapshot as { accessScope?: string }).accessScope === 'operations_g') + && !(await canAccessOperationsGMaterials(operatorUserId))) { + throw new MaterialPurgeError('无权限操作运营中心 G 专属素材', 403) + } const newIds = ids.filter(id => !jobs.some(job => job.materialId === id)) if (!newIds.length) return jobs.map(toPurgeJobView) await tx.$queryRaw`SELECT id FROM materials WHERE id IN (${Prisma.join(newIds)}) ORDER BY id FOR UPDATE` @@ -51,6 +57,10 @@ export async function enqueueMaterialPurge(input: unknown, operatorUserId: strin where: { id: { in: newIds } }, include: { assets: true, skus: true }, }) if (materials.length !== newIds.length) throw new MaterialPurgeError('部分素材已不存在,请刷新后重试', 404) + if (materials.some((material) => material.accessScope === 'operations_g') + && !(await canAccessOperationsGMaterials(operatorUserId))) { + throw new MaterialPurgeError('无权限操作运营中心 G 专属素材', 403) + } if (materials.some(material => !material.deletedAt)) throw new MaterialPurgeError('只能彻底删除回收站中的素材') const uploading = await tx.productPackageUploadJob.count({ where: { materialId: { in: newIds }, status: { in: ['queued', 'processing'] } } }) const applying = await tx.taskDetailChangeRequest.count({ where: { materialId: { in: newIds }, status: 'applying' } }) @@ -63,6 +73,7 @@ export async function enqueueMaterialPurge(input: unknown, operatorUserId: strin throw new MaterialPurgeError(`${material.productModel || '素材'}:${error.message}`) } const snapshot = { + accessScope: material.accessScope || 'general', id: material.id, productModel: material.productModel, materialType: material.materialType, taskNo: material.taskNo, ownerUserId: material.userId, deletedAt: material.deletedAt!.toISOString(), } @@ -85,6 +96,8 @@ export async function enqueueMaterialPurge(input: unknown, operatorUserId: strin } return jobs.map(toPurgeJobView) }, { timeout: 30_000 }) + invalidateMaterialFacetsCache() + return result } async function claimJob() { @@ -172,6 +185,11 @@ export async function processNextMaterialPurge(): Promise { export async function retryMaterialPurge(jobId: string, operatorUserId: string) { if (typeof jobId !== 'string' || !UUID.test(jobId)) throw new MaterialPurgeError('清理任务无效', 400) + const job = await prisma.materialPurgeJob.findUnique({ where: { id: jobId } }) + if ((job?.materialSnapshot as { accessScope?: string } | undefined)?.accessScope === 'operations_g' + && !(await canAccessOperationsGMaterials(operatorUserId))) { + throw new MaterialPurgeError('无权限操作运营中心 G 专属素材', 403) + } return prisma.$transaction(async tx => { const result = await tx.materialPurgeJob.updateMany({ where: { id: jobId, status: 'failed' }, data: { status: 'queued', attempts: 0, errorMessage: null, nextAttemptAt: new Date(), diff --git a/lib/material-query.ts b/lib/material-query.ts index 548aef00..f21e014f 100644 --- a/lib/material-query.ts +++ b/lib/material-query.ts @@ -13,6 +13,7 @@ import { import type { Prisma } from '@prisma/client' import { canUserAccessPrivateTaskDetail } from './user-permission-inherit' import { privateTaskDetailAccessWhere } from './task-detail-privacy' +import { canAccessOperationsGMaterials } from './material-organization-access' export type MaterialFilterDimension = | 'materialType' @@ -40,6 +41,7 @@ export interface MaterialQueryContext { expandedViewableTypes: string[] isSuperAdmin: boolean canAccessPrivateTaskDetails?: boolean + canAccessOperationsGMaterials?: boolean searchOrConditions?: any[] } @@ -330,10 +332,11 @@ export async function createMaterialQueryContext( const requestedDeleted = isDeletedMaterialRequest(searchParams) const search = searchParams.get('search') || '' - const [superAdmin, searchOrConditions, canAccessPrivateTaskDetails] = await Promise.all([ + const [superAdmin, searchOrConditions, canAccessPrivateTaskDetails, canAccessOperationsG] = await Promise.all([ isSessionUserSuperAdmin(user), buildMaterialSearchOrConditions(search), canUserAccessPrivateTaskDetail(user.id), + canAccessOperationsGMaterials(user.id), ]) const canAccessDeleted = superAdmin || isSystemAdmin(user.role || '') @@ -347,6 +350,7 @@ export async function createMaterialQueryContext( expandedViewableTypes: [], isSuperAdmin: true, canAccessPrivateTaskDetails, + canAccessOperationsGMaterials: canAccessOperationsG, searchOrConditions, } } @@ -363,6 +367,7 @@ export async function createMaterialQueryContext( expandedViewableTypes: expandCompatibleMaterialTypes(viewableTypes), isSuperAdmin: false, canAccessPrivateTaskDetails, + canAccessOperationsGMaterials: canAccessOperationsG, searchOrConditions, } } @@ -450,19 +455,20 @@ export async function buildMaterialWhereFromSearchParams( where.materialType = materialTypeWhere(requestedTypes) } - if (!context.isSuperAdmin && requestedTypes.length > 0 && !requestedTypes.includes('任务-详情')) { + if (!context.isSuperAdmin && !context.canAccessOperationsGMaterials && requestedTypes.length > 0 && !requestedTypes.includes('任务-详情')) { const allowed = requestedTypes.filter((type) => context.expandedViewableTypes.includes(type)) if (allowed.length === 0) return { where, empty: true } where.materialType = materialTypeWhere(allowed) } const publicScope = context.isSuperAdmin - ? { taskDetailPrivate: false } - : { taskDetailPrivate: false, materialType: { in: context.expandedViewableTypes } } + ? { taskDetailPrivate: false, accessScope: 'general' } + : { taskDetailPrivate: false, accessScope: 'general', materialType: { in: context.expandedViewableTypes } } // 私密准入按人员/权限组授予,管理员和上传者不隐式豁免;公开素材仍用原有类型权限。 where.AND = [{ OR: [ publicScope, privateTaskDetailAccessWhere(user.id, context.canAccessPrivateTaskDetails === true), + ...(context.canAccessOperationsGMaterials ? [{ accessScope: 'operations_g' }] : []), ] }] return { where, empty: false } } diff --git a/lib/material-update.ts b/lib/material-update.ts index 4841a674..82c9db9e 100644 --- a/lib/material-update.ts +++ b/lib/material-update.ts @@ -1,4 +1,8 @@ import { randomUUID } from 'crypto' +import { invalidateMaterialFacetsCache } from '@/lib/material-facets-cache' +import { MaterialAccessScopeError, resolveMaterialUploadAccessScope } from '@/lib/material-organization-access' +import { isRestrictedMaterial } from '@/lib/material-access-scope' +import { prepareOperationsGMaterialFiles } from '@/lib/material-access-scope-storage' import { prisma } from '@/lib/prisma' import { createMaterialLog } from '@/lib/material-log' @@ -38,6 +42,7 @@ import { } from '@/lib/material-transfer' export interface MaterialUpdateInput { + accessScope?: string | null productModel: string reportTitle?: string | null reportKind?: string | null @@ -156,6 +161,7 @@ async function resolvePreviewUrl( previewImage: File | null | undefined, materialType: string, currentPreviewUrl: string, + protectedMaterialId?: string, ) { if (!previewImage || previewImage.size <= 0) { return currentPreviewUrl @@ -178,6 +184,7 @@ async function resolvePreviewUrl( compressedBuffer, buildMaterialPublicDisplayPath(fileName), 'image/webp', + protectedMaterialId, ) return nextPreviewUrl @@ -192,6 +199,19 @@ async function updateMaterialWithSharedRulesLocked(options: UpdateMaterialOption } const material = editable.material as any + let accessScope = material.accessScope || 'general' + if (Object.prototype.hasOwnProperty.call(input, 'accessScope')) { + try { + accessScope = await resolveMaterialUploadAccessScope(input.accessScope, operatorUserId) + } catch (error) { + if (error instanceof MaterialAccessScopeError) return { error: error.message, status: error.status } + throw error + } + } + const changingToOperationsG = accessScope === 'operations_g' && material.accessScope !== 'operations_g' + if (changingToOperationsG && ['pending', 'processing'].includes(material.videoProcessingStatus)) { + return { error: '视频预览处理中,请完成后再更改使用范围', status: 409 as const } + } const hasReportTitleField = Object.prototype.hasOwnProperty.call(input, 'reportTitle') const hasReportKindField = Object.prototype.hasOwnProperty.call(input, 'reportKind') const hasCertificateTestedOnField = Object.prototype.hasOwnProperty.call(input, 'certificateTestedOn') @@ -367,9 +387,17 @@ async function updateMaterialWithSharedRulesLocked(options: UpdateMaterialOption nextTaskDetailRequesterName = requester.realName || requester.username } - let previewUrl = material.previewUrl + const scopeFiles = changingToOperationsG + ? await prepareOperationsGMaterialFiles(material, await prisma.materialAsset.findMany({ + where: { materialId }, select: { id: true, fileUrl: true }, + }), await prisma.materialSku.findMany({ + where: { materialId }, select: { id: true, filePath: true, previewUrl: true }, + })) + : null + let previewUrl = scopeFiles?.materialFiles.previewUrl as string || material.previewUrl try { - previewUrl = await resolvePreviewUrl(previewImage, materialType, material.previewUrl) + previewUrl = await resolvePreviewUrl(previewImage, materialType, previewUrl, + isRestrictedMaterial({ ...material, accessScope }) ? materialId : undefined) } catch (error) { return { error: error instanceof Error ? error.message : '预览图更新失败', @@ -378,6 +406,9 @@ async function updateMaterialWithSharedRulesLocked(options: UpdateMaterialOption } const updateData: Record = { + ...scopeFiles?.materialFiles, + accessScope, + ...(accessScope === 'operations_g' ? { taskDetailPrivate: false } : {}), previewUrl, productModel: isCertificateReportMaterialType(materialType) && certificateReportMetadata @@ -451,10 +482,20 @@ async function updateMaterialWithSharedRulesLocked(options: UpdateMaterialOption : null let updatedMaterial: any try { - updatedMaterial = await prisma.material.update({ - where: { id: materialId }, - data: updateData as any, + const persist = (db: typeof prisma) => db.material.update({ + where: { id: materialId }, data: updateData as any, }) + updatedMaterial = scopeFiles && (scopeFiles.assetFiles.length || scopeFiles.skuFiles.length) + ? await prisma.$transaction(async (tx) => { + for (const asset of scopeFiles.assetFiles) { + await tx.materialAsset.update({ where: { id: asset.id }, data: { fileUrl: asset.fileUrl } }) + } + for (const sku of scopeFiles.skuFiles) { + await tx.materialSku.update({ where: { id: sku.id }, data: { filePath: sku.filePath, previewUrl: sku.previewUrl } }) + } + return persist(tx as typeof prisma) + }) + : await persist(prisma) } catch (error) { if (!uploadedPreviewUrl) throw error @@ -480,6 +521,7 @@ async function updateMaterialWithSharedRulesLocked(options: UpdateMaterialOption } } + invalidateMaterialFacetsCache() if (uploadedPreviewUrl && material.previewUrl && material.previewUrl !== uploadedPreviewUrl) { await deleteFileIfUnreferenced(material.previewUrl, { excludeMaterialIds: [materialId], @@ -488,6 +530,12 @@ async function updateMaterialWithSharedRulesLocked(options: UpdateMaterialOption }) } + for (const url of scopeFiles?.publicUrls || []) { + await deleteFileIfUnreferenced(url).catch((error) => { + console.error('[material-update] 清理已迁移的公开对象失败:', error) + }) + } + if (isOwnershipTransfer && nextUserId) { // 归属变更已随素材更新一并落库。流水写入失败不回滚归属本身——素材上的 // originalOwnerId / transferredAt / transferredBy / transferNote 已完整记下了 diff --git a/lib/pdf-upload-handler.ts b/lib/pdf-upload-handler.ts index 0bc22dcd..bd93ac99 100644 --- a/lib/pdf-upload-handler.ts +++ b/lib/pdf-upload-handler.ts @@ -37,7 +37,8 @@ export interface PdfUploadResult { */ export async function processPdfUpload( pdfFilePath: string, - existingPreviewUrl?: string + existingPreviewUrl?: string, + protectedMaterialId?: string, ): Promise { try { // 如果已经有预览图,直接返回 @@ -85,7 +86,7 @@ export async function processPdfUpload( // 读取预览图并上传到S3 const previewBuffer = await fs.readFile(pdfPreviewResult.previewPath) const previewFilename = generateUniqueFilename('pdf-preview', '.jpg') - const previewUrl = await uploadToS3(previewBuffer, previewFilename, 'image/jpeg') + const previewUrl = await uploadToS3(previewBuffer, previewFilename, 'image/jpeg', protectedMaterialId) console.log('[PDF Upload] PDF preview extracted and uploaded:', previewUrl) diff --git a/lib/product-package-completion.ts b/lib/product-package-completion.ts index 2f846843..6f1cb13d 100644 --- a/lib/product-package-completion.ts +++ b/lib/product-package-completion.ts @@ -1,3 +1,4 @@ +import { isRestrictedMaterial } from '@/lib/material-access-scope' import { prisma } from '@/lib/prisma' import { validateTaskNo } from '@/lib/product-package' import { @@ -1379,7 +1380,7 @@ export async function completeProductPackageUpload(input: CompleteProductPackage mainEntryNames, uploadedPreviewUrls, privatePreviewPaths, - Boolean(material.taskDetailPrivate), + isRestrictedMaterial(material), assembledFiles, tempFiles, uploadIds, @@ -1391,7 +1392,7 @@ export async function completeProductPackageUpload(input: CompleteProductPackage skuEntryNames, uploadedPreviewUrls, privatePreviewPaths, - Boolean(material.taskDetailPrivate), + isRestrictedMaterial(material), assembledFiles, tempFiles, uploadIds, @@ -1403,7 +1404,7 @@ export async function completeProductPackageUpload(input: CompleteProductPackage detailEntryNames, uploadedPreviewUrls, privatePreviewPaths, - Boolean(material.taskDetailPrivate), + isRestrictedMaterial(material), assembledFiles, tempFiles, uploadIds, diff --git a/lib/product-package.ts b/lib/product-package.ts index 8d73a84e..5bb2ab29 100644 --- a/lib/product-package.ts +++ b/lib/product-package.ts @@ -117,7 +117,7 @@ export async function updateTaskStatus( */ export async function getMaterialByTaskNo(taskNo: string) { return prisma.material.findFirst({ - where: { taskNo, deletedAt: null, taskDetailPrivate: false }, + where: { taskNo, deletedAt: null, taskDetailPrivate: false, accessScope: 'general' }, include: { assets: { orderBy: { sortOrder: 'asc' }, @@ -263,7 +263,7 @@ export async function softDeleteByTaskNo(taskNo: string) { export async function getMaterialById(materialId: string) { return prisma.material.findFirst({ - where: { id: materialId, deletedAt: null, taskDetailPrivate: false }, + where: { id: materialId, deletedAt: null, taskDetailPrivate: false, accessScope: 'general' }, include: { assets: { orderBy: { sortOrder: 'asc' }, @@ -470,12 +470,13 @@ export async function finalizeTaskMaterialOnComplete(input: { id: true, productModel: true, materialType: true, + accessScope: true, }, }); if (existingMaterial) { throw new Error( - `任务号 ${normalizedTaskNo} 已存在,对应素材:${existingMaterial.productModel}(${existingMaterial.materialType})` + existingMaterial.accessScope === 'operations_g' ? `任务号 ${normalizedTaskNo} 已存在` : `任务号 ${normalizedTaskNo} 已存在,对应素材:${existingMaterial.productModel}(${existingMaterial.materialType})` ); } @@ -492,11 +493,12 @@ export async function finalizeTaskMaterialOnComplete(input: { id: true, productModel: true, materialType: true, + accessScope: true, }, }); if (concurrentOwner) { throw new Error( - `任务号 ${normalizedTaskNo} 已存在,对应素材:${concurrentOwner.productModel}(${concurrentOwner.materialType})` + concurrentOwner.accessScope === 'operations_g' ? `任务号 ${normalizedTaskNo} 已存在` : `任务号 ${normalizedTaskNo} 已存在,对应素材:${concurrentOwner.productModel}(${concurrentOwner.materialType})` ); } @@ -560,11 +562,12 @@ export async function createTaskMaterialOnComplete(input: { id: true, productModel: true, materialType: true, + accessScope: true, }, }); if (concurrentOwner) { throw new Error( - `任务号 ${normalizedTaskNo} 已存在,对应素材:${concurrentOwner.productModel}(${concurrentOwner.materialType})`, + concurrentOwner.accessScope === 'operations_g' ? `任务号 ${normalizedTaskNo} 已存在` : `任务号 ${normalizedTaskNo} 已存在,对应素材:${concurrentOwner.productModel}(${concurrentOwner.materialType})`, ); } } diff --git a/lib/public-display.ts b/lib/public-display.ts index c4eeed02..1cd11bc2 100644 --- a/lib/public-display.ts +++ b/lib/public-display.ts @@ -55,7 +55,12 @@ export async function uploadPublicDisplayToS3( file: Buffer, relativePath: string, contentType: string, + protectedMaterialId?: string, ): Promise { + if (protectedMaterialId) { + const { saveProtectedMaterialDisplay } = await import('@/lib/material-protected-storage') + return saveProtectedMaterialDisplay(protectedMaterialId, relativePath, file) + } return uploadToS3(file, buildPublicDisplayObjectPath(relativePath), contentType) } @@ -64,7 +69,12 @@ export async function uploadPublicDisplayFileToS3( relativePath: string, contentType: string, expectedSize?: number, + protectedMaterialId?: string, ): Promise { + if (protectedMaterialId) { + const { saveProtectedMaterialDisplayFile } = await import('@/lib/material-protected-storage') + return saveProtectedMaterialDisplayFile(protectedMaterialId, relativePath, filePath, expectedSize) + } return uploadFileToS3( filePath, buildPublicDisplayObjectPath(relativePath), diff --git a/lib/s3.ts b/lib/s3.ts index 33186bb1..002b4eb3 100644 --- a/lib/s3.ts +++ b/lib/s3.ts @@ -1,7 +1,8 @@ import { S3Client, PutObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand } from '@aws-sdk/client-s3' -import { createReadStream } from 'fs' +import { createReadStream, createWriteStream } from 'fs' import { lstat } from 'fs/promises' import { Readable } from 'stream' +import { pipeline } from 'stream/promises' /** * 从 S3 公网 URL 或 MinIO path-style URL 中提取对象 Key。 @@ -183,8 +184,13 @@ const s3Client = new S3Client({ export async function uploadToS3( file: Buffer, fileName: string, - contentType: string + contentType: string, + protectedMaterialId?: string, ): Promise { + if (protectedMaterialId) { + const { saveProtectedMaterialDisplay } = await import('@/lib/material-protected-storage') + return saveProtectedMaterialDisplay(protectedMaterialId, fileName, file) + } // 确保 S3_FILE_PATH 以 / 结尾,fileName 不以 / 开头 const s3FilePath = (process.env.S3_FILE_PATH || '').trim() const normalizedPath = s3FilePath && !s3FilePath.endsWith('/') ? `${s3FilePath}/` : s3FilePath @@ -251,7 +257,12 @@ export async function uploadFileToS3( fileName: string, contentType: string, expectedSize?: number, + protectedMaterialId?: string, ): Promise { + if (protectedMaterialId) { + const { saveProtectedMaterialDisplayFile } = await import('@/lib/material-protected-storage') + return saveProtectedMaterialDisplayFile(protectedMaterialId, fileName, filePath, expectedSize) + } const fileStats = await lstat(filePath) if (fileStats.isSymbolicLink() || !fileStats.isFile() || fileStats.size <= 0) { throw new Error('待上传文件无效') @@ -320,6 +331,18 @@ export async function downloadFromS3(fileUrl: string): Promise { } } +export async function downloadS3ObjectToFile(fileUrl: string, destination: string): Promise { + const response = await s3Client.send(new GetObjectCommand({ + Bucket: process.env.S3_BUCKET!, + Key: getTrustedS3MutationKey(fileUrl), + })) + if (!(response.Body instanceof Readable)) throw new Error('素材存储没有返回文件内容') + await pipeline(response.Body, createWriteStream(destination)) + if (response.ContentLength != null && (await lstat(destination)).size !== response.ContentLength) { + throw new Error('专属素材文件迁移不完整') + } +} + export async function deleteFromS3(fileUrl: string): Promise { try { const key = getTrustedS3MutationKey(fileUrl) diff --git a/lib/standard-model-white-background-service.ts b/lib/standard-model-white-background-service.ts index abeed10a..0fcf6647 100644 --- a/lib/standard-model-white-background-service.ts +++ b/lib/standard-model-white-background-service.ts @@ -286,6 +286,7 @@ async function uploadStandardModelWhiteBackgroundLocked( select: { id: true, materialType: true, + accessScope: true, productCategoryName: true, categoryName: true, }, @@ -383,6 +384,7 @@ async function uploadStandardModelWhiteBackgroundLocked( preview, buildWhiteBackgroundPublicDisplayPath(input.materialId, input.skuId, diskFileName), 'image/webp', + material.accessScope === 'operations_g' ? input.materialId : undefined, ) uploadedPreviewUrls.push(previewUrl) if (view.key === 'rightFront45') { @@ -416,6 +418,7 @@ async function uploadStandardModelWhiteBackgroundLocked( preview, buildWhiteBackgroundPublicDisplayPath(input.materialId, input.skuId, diskFileName), 'image/webp', + material.accessScope === 'operations_g' ? input.materialId : undefined, ) uploadedPreviewUrls.push(previewUrl) @@ -568,7 +571,7 @@ async function uploadStandardModelWhiteBackgroundLocked( for (const previewUrl of uploadedPreviewUrls) { try { - await deleteFromS3(previewUrl) + await (previewUrl.startsWith('uploads/materials/') ? deleteFileIfUnreferenced(previewUrl) : deleteFromS3(previewUrl)) } catch { // ignore cleanup failure } diff --git a/lib/task-detail-asset-edit.ts b/lib/task-detail-asset-edit.ts index 48bec58c..30b37baa 100644 --- a/lib/task-detail-asset-edit.ts +++ b/lib/task-detail-asset-edit.ts @@ -1,3 +1,4 @@ +import { isRestrictedMaterial } from '@/lib/material-access-scope' import { prisma } from '@/lib/prisma' import { canManageMaterial, @@ -99,6 +100,7 @@ interface EditContext { materialId: string materialType: string taskDetailPrivate: boolean + accessScope?: string | null productModel: string | null authorName: string | null categoryName: string | null @@ -682,6 +684,7 @@ async function loadEditContext(options: { materialId: material.id, materialType: material.materialType, taskDetailPrivate: Boolean(material.taskDetailPrivate), + accessScope: material.accessScope, productModel: material.productModel, authorName: material.authorName, categoryName: material.categoryName, @@ -769,6 +772,7 @@ async function loadEditContext(options: { materialId: material.id, materialType: material.materialType, taskDetailPrivate: Boolean(material.taskDetailPrivate), + accessScope: material.accessScope, productModel: material.productModel, authorName: material.authorName, categoryName: material.categoryName, @@ -1588,7 +1592,7 @@ async function planPreviewRowChanges( replacementSource, group, context.materialId, - context.taskDetailPrivate, + isRestrictedMaterial(context), stripExtension(finalEntryName), targetEntryIndex, workspaceDir, @@ -1862,7 +1866,7 @@ async function replaceDetailSliceInBatchRun(options: { entryName: topSource.entryName, group: 'detail', materialId: options.context.materialId, - isPrivate: options.context.taskDetailPrivate, + isPrivate: isRestrictedMaterial(options.context), entryIndex: options.runIndex, workspaceDir: options.workspaceDir, generatedPreviewLocations: options.generatedPreviewLocations, @@ -1877,7 +1881,7 @@ async function replaceDetailSliceInBatchRun(options: { entryName: options.finalEntryName, group: 'detail', materialId: options.context.materialId, - isPrivate: options.context.taskDetailPrivate, + isPrivate: isRestrictedMaterial(options.context), entryIndex: options.runIndex + replacementRuns.length, workspaceDir: options.workspaceDir, generatedPreviewLocations: options.generatedPreviewLocations, @@ -1890,7 +1894,7 @@ async function replaceDetailSliceInBatchRun(options: { entryName: bottomSource.entryName, group: 'detail', materialId: options.context.materialId, - isPrivate: options.context.taskDetailPrivate, + isPrivate: isRestrictedMaterial(options.context), entryIndex: options.runIndex + replacementRuns.length, workspaceDir: options.workspaceDir, generatedPreviewLocations: options.generatedPreviewLocations, @@ -2132,7 +2136,7 @@ async function executeBatchRebuild( entryName, group, materialId: context.materialId, - isPrivate: context.taskDetailPrivate, + isPrivate: isRestrictedMaterial(context), entryIndex: finalRuns.length, workspaceDir: workspace.dir, generatedPreviewLocations, @@ -2166,7 +2170,7 @@ async function executeBatchRebuild( entryName: insertedEntryName, group, materialId: context.materialId, - isPrivate: context.taskDetailPrivate, + isPrivate: isRestrictedMaterial(context), entryIndex: boundaryIndex, workspaceDir: workspace.dir, generatedPreviewLocations, @@ -2188,7 +2192,7 @@ async function executeBatchRebuild( entryName: insertedEntryName, group, materialId: context.materialId, - isPrivate: context.taskDetailPrivate, + isPrivate: isRestrictedMaterial(context), entryIndex: seam.afterRunIndex + 1, workspaceDir: workspace.dir, generatedPreviewLocations, @@ -2208,7 +2212,7 @@ async function executeBatchRebuild( entryName: insertedEntryName, group, materialId: context.materialId, - isPrivate: context.taskDetailPrivate, + isPrivate: isRestrictedMaterial(context), entryIndex: seam.afterRunIndex + 1, workspaceDir: workspace.dir, generatedPreviewLocations, @@ -2246,7 +2250,7 @@ async function executeBatchRebuild( entryName: splitSources.top.entryName, group, materialId: context.materialId, - isPrivate: context.taskDetailPrivate, + isPrivate: isRestrictedMaterial(context), entryIndex: seam.afterRunIndex, workspaceDir: workspace.dir, generatedPreviewLocations, @@ -2257,7 +2261,7 @@ async function executeBatchRebuild( entryName: insertedEntryName, group, materialId: context.materialId, - isPrivate: context.taskDetailPrivate, + isPrivate: isRestrictedMaterial(context), entryIndex: seam.afterRunIndex + 1, workspaceDir: workspace.dir, generatedPreviewLocations, @@ -2267,7 +2271,7 @@ async function executeBatchRebuild( entryName: splitSources.bottom.entryName, group, materialId: context.materialId, - isPrivate: context.taskDetailPrivate, + isPrivate: isRestrictedMaterial(context), entryIndex: seam.afterRunIndex + 2, workspaceDir: workspace.dir, generatedPreviewLocations, @@ -2341,7 +2345,7 @@ async function executeBatchRebuild( entryName: finalEntryName, group, materialId: context.materialId, - isPrivate: context.taskDetailPrivate, + isPrivate: isRestrictedMaterial(context), entryIndex: located.runIndex, workspaceDir: workspace.dir, generatedPreviewLocations, diff --git a/lib/task-detail-privacy-fields.ts b/lib/task-detail-privacy-fields.ts index 22f532ce..0b50828d 100644 --- a/lib/task-detail-privacy-fields.ts +++ b/lib/task-detail-privacy-fields.ts @@ -3,6 +3,7 @@ export const TASK_DETAIL_DEMAND_TYPE_OPTIONS = ['新品', '优化'] as const export type TaskDetailDemandType = (typeof TASK_DETAIL_DEMAND_TYPE_OPTIONS)[number] export interface TaskDetailPrivacyFieldInput { + accessScope?: unknown taskDetailDemandType?: unknown taskDetailPrivate?: unknown } @@ -21,6 +22,9 @@ export function normalizeTaskDetailPrivacyFields( ): NormalizedTaskDetailPrivacyFields { const rawDemandType = input?.taskDetailDemandType const rawPrivate = input?.taskDetailPrivate + if (input.accessScope === 'operations_g' && rawPrivate === true) { + throw new Error('运营中心 G 专属素材在中心内共享,不能设为个人私密') + } let taskDetailDemandType: TaskDetailDemandType = '新品' if (rawDemandType != null) { diff --git a/lib/task-detail-privacy.ts b/lib/task-detail-privacy.ts index f7e8ab60..ef9f8baf 100644 --- a/lib/task-detail-privacy.ts +++ b/lib/task-detail-privacy.ts @@ -1,15 +1,19 @@ import { canUserAccessPrivateTaskDetail } from '@/lib/user-permission-inherit' +import { isOperationsGMaterial } from '@/lib/material-access-scope' +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' export const TASK_DETAIL_PRIVACY_SELECT = { taskDetailPrivate: true, taskDetailDemandType: true, taskDetailRequesterUserId: true, + accessScope: true, } as const export interface TaskDetailPrivacyMaterial { materialType?: string | null taskDetailPrivate?: boolean | null taskDetailRequesterUserId?: string | null + accessScope?: string | null } export function isPrivateTaskDetail(material: TaskDetailPrivacyMaterial): boolean { @@ -21,6 +25,7 @@ export async function canAccessMaterialPrivacy( material: TaskDetailPrivacyMaterial, userId?: string | null, ): Promise { + if (isOperationsGMaterial(material)) return canAccessOperationsGMaterials(userId) if (!isPrivateTaskDetail(material)) return true if (!userId) return false if (material.taskDetailRequesterUserId === userId) return true @@ -31,13 +36,19 @@ export function privateTaskDetailAccessWhere(userId: string, canAccessAll: boole return { materialType: '任务-详情', taskDetailPrivate: true, + accessScope: 'general', ...(canAccessAll ? {} : { taskDetailRequesterUserId: userId }), } } export async function buildMaterialPrivacyWhere(userId: string) { + const [canAccessPrivate, canAccessOperationsG] = await Promise.all([ + canUserAccessPrivateTaskDetail(userId), + canAccessOperationsGMaterials(userId), + ]) return { OR: [ - { taskDetailPrivate: false }, - privateTaskDetailAccessWhere(userId, await canUserAccessPrivateTaskDetail(userId)), + { taskDetailPrivate: false, accessScope: 'general' }, + privateTaskDetailAccessWhere(userId, canAccessPrivate), + ...(canAccessOperationsG ? [{ accessScope: 'operations_g' }] : []), ] } } diff --git a/lib/task-detail-upload-jobs.ts b/lib/task-detail-upload-jobs.ts index e3cdee64..e9056f32 100644 --- a/lib/task-detail-upload-jobs.ts +++ b/lib/task-detail-upload-jobs.ts @@ -1,3 +1,4 @@ +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' import type { Prisma } from '@prisma/client' import { randomUUID } from 'crypto' import { prisma } from '@/lib/prisma' @@ -742,18 +743,21 @@ export async function createTaskDetailUploadJob(input: CreateTaskDetailUploadJob export async function getTaskDetailUploadJobStatus(jobId: string, operatorUserId: string) { await ensureProductPackageUploadJobTable() const job = await prisma.productPackageUploadJob.findFirst({ + include: { material: { select: { accessScope: true } } }, where: { id: jobId, operatorUserId, }, }) + if (job?.material?.accessScope === 'operations_g' && !(await canAccessOperationsGMaterials(operatorUserId))) return null return job ? toStatusView(job) : null } export async function getLatestTaskDetailUploadJobStatus(materialId: string, operatorUserId: string) { await ensureProductPackageUploadJobTable() const job = await prisma.productPackageUploadJob.findFirst({ + include: { material: { select: { accessScope: true } } }, where: { materialId, operatorUserId, @@ -761,6 +765,7 @@ export async function getLatestTaskDetailUploadJobStatus(materialId: string, ope orderBy: { createdAt: 'desc' }, }) + if (job?.material?.accessScope === 'operations_g' && !(await canAccessOperationsGMaterials(operatorUserId))) return null return job ? toStatusView(job) : null } diff --git a/lib/task-image-material-completion.ts b/lib/task-image-material-completion.ts index 9860f9e5..e7a1b1d4 100644 --- a/lib/task-image-material-completion.ts +++ b/lib/task-image-material-completion.ts @@ -1,3 +1,5 @@ +import { canAccessOperationsGMaterials } from '@/lib/material-organization-access' +import { isRestrictedMaterial } from '@/lib/material-access-scope' import { prisma } from '@/lib/prisma'; import { createMaterialLog } from '@/lib/material-log'; import { @@ -86,6 +88,8 @@ export async function completeTaskImageMaterial( id: true, userId: true, materialType: true, + accessScope: true, + taskDetailPrivate: true, taskStatus: true, deletedAt: true, }, @@ -93,6 +97,9 @@ export async function completeTaskImageMaterial( if (!initialMaterial || initialMaterial.deletedAt) { throwCompletionError('素材不存在', 404); } + if (initialMaterial.accessScope === 'operations_g' && !(await canAccessOperationsGMaterials(input.userId))) { + throwCompletionError('无权限操作此素材', 403); + } if (initialMaterial.userId !== input.userId) { throwCompletionError('无权限操作此素材', 403); } @@ -109,6 +116,8 @@ export async function completeTaskImageMaterial( id: true, userId: true, materialType: true, + accessScope: true, + taskDetailPrivate: true, productModel: true, taskStatus: true, previewUrl: true, @@ -179,6 +188,7 @@ export async function completeTaskImageMaterial( input.materialType, input.compressOptions, (previewUrl) => uploadedPreviewUrls.push(previewUrl), + isRestrictedMaterial(material) ? materialId : undefined, ); if (uploadedPreviewUrls.length === 0) { uploadedPreviewUrls.push(...previewUrls); diff --git a/lib/task-material-processor.ts b/lib/task-material-processor.ts index 75cf532c..5a728838 100644 --- a/lib/task-material-processor.ts +++ b/lib/task-material-processor.ts @@ -1,3 +1,5 @@ +import { invalidateMaterialFacetsCache } from '@/lib/material-facets-cache' +import { deleteFileIfUnreferenced } from '@/lib/file-cleanup' /** * 任务类型素材的通用处理逻辑 * 用于:任务-3D原图、任务-AI原图、任务-实拍原图、任务-视频截图、任务-详情 @@ -559,6 +561,7 @@ export async function generatePreviewImages( maxSizeKB?: number; }, onPreviewUploaded?: (previewUrl: string) => void, + protectedMaterialId?: string, ): Promise { if (!uploadIds || uploadIds.length === 0) { return []; @@ -623,6 +626,7 @@ export async function generatePreviewImages( compressedBuffer, buildMaterialPublicDisplayPath(fileName), 'image/webp', + protectedMaterialId, ); uploadedPreviewUrls.push(previewUrl); onPreviewUploaded?.(previewUrl); @@ -708,7 +712,8 @@ export async function cleanupOnError( console.log(`[Cleanup] Cleaning up ${uploadedPreviewUrls.length} S3 preview images...`); for (const fileUrl of uploadedPreviewUrls) { try { - await deleteFromS3(fileUrl); + if (fileUrl.startsWith('uploads/materials/')) await deleteFileIfUnreferenced(fileUrl); + else await deleteFromS3(fileUrl); console.log(`[Cleanup] Deleted S3 file: ${fileUrl}`); } catch (cleanupError) { console.error(`[Cleanup] Failed to delete S3 file ${fileUrl}:`, cleanupError); @@ -878,6 +883,7 @@ export async function saveTaskMaterialAssetsAndComplete(input: { ); }, }); + invalidateMaterialFacetsCache(); console.log( `[Database] Atomically completed task material with ${input.previewUrls.length + (input.zipInfo ? 1 : 0)} assets`, @@ -1136,5 +1142,6 @@ export async function saveProductPackageAssetsAndComplete(input: { }); console.log('[Database] Atomically completed product package'); + invalidateMaterialFacetsCache(); return saveResult; } diff --git a/lib/url-rewrite.ts b/lib/url-rewrite.ts index c5493477..90359d3e 100644 --- a/lib/url-rewrite.ts +++ b/lib/url-rewrite.ts @@ -163,7 +163,7 @@ export function rewriteStorageUrlForClient(url?: string | null, request?: NextRe if (!trimmed) return null // 私密预览只能从当前应用的鉴权路由读取,不能变成相对页面地址或 CDN 直链。 - if (/^uploads\/materials\/[^/]+\/private-previews\//.test(trimmed)) { + if (/^uploads\/materials\/[^/]+\/(?:private-previews|protected-display)\//.test(trimmed)) { return `/api/${trimmed.split('/').map(encodeURIComponent).join('/')}` } diff --git a/lib/video-processor.ts b/lib/video-processor.ts index 4110ccf9..03b5ce1a 100644 --- a/lib/video-processor.ts +++ b/lib/video-processor.ts @@ -1,3 +1,4 @@ +import { deleteFileIfUnreferenced } from '@/lib/file-cleanup' /** * 视频处理工具库 * @@ -49,6 +50,7 @@ export const TRANSCODE_CONFIG = { } interface VideoTranscodeOptions { + protectedMaterialId?: string inputPath: string // 输入视频路径(S3 URL 或本地路径) outputDir: string // 输出目录 materialId: string // 素材ID,用于生成唯一文件名 @@ -101,7 +103,7 @@ function createByteLimitTransform(maxBytes: number): Transform { export async function cleanupUploadedTranscodeObjects(uploadedUrls: readonly string[]): Promise { const cleanupResults = await Promise.allSettled( Array.from(new Set(uploadedUrls.filter((url): url is string => Boolean(url?.trim())))) - .map((url) => deleteFromS3(url)), + .map((url) => url.startsWith('uploads/materials/') ? deleteFileIfUnreferenced(url) : deleteFromS3(url)), ) for (const cleanupResult of cleanupResults) { @@ -664,7 +666,7 @@ export async function processVideoTranscode( }, abortSignal) const preview540FileName = `video-preview-${TRANSCODE_CONFIG.previewResolution}p-${materialId}-${outputIdentity}.mp4` onProgress?.(55, 'preview') // 上传开始 - const preview540Url = await uploadFileToS3(previewPath, preview540FileName, 'video/mp4') + const preview540Url = await uploadFileToS3(previewPath, preview540FileName, 'video/mp4', undefined, options.protectedMaterialId) uploadedUrls.push(preview540Url) console.log(`[VideoProcessor] ${TRANSCODE_CONFIG.previewResolution}P preview uploaded:`, preview540Url) onProgress?.(60, 'clip') // 预览完成,开始片段 @@ -677,7 +679,7 @@ export async function processVideoTranscode( }, abortSignal) const clipFileName = `video-clip-${TRANSCODE_CONFIG.clipDuration}s-${materialId}-${outputIdentity}.mp4` onProgress?.(85, 'clip') // 上传开始 - const clipUrl = await uploadFileToS3(clipPath, clipFileName, 'video/mp4') + const clipUrl = await uploadFileToS3(clipPath, clipFileName, 'video/mp4', undefined, options.protectedMaterialId) uploadedUrls.push(clipUrl) console.log(`[VideoProcessor] ${TRANSCODE_CONFIG.clipDuration}s clip uploaded:`, clipUrl) onProgress?.(90, 'cover') // 片段完成,开始封面 @@ -689,7 +691,7 @@ export async function processVideoTranscode( await extractCoverImage(sourcePath, coverPath, abortSignal) const coverFileName = `video-cover-${materialId}-${outputIdentity}.jpg` onProgress?.(95, 'cover') // 上传开始 - coverUrl = await uploadFileToS3(coverPath, coverFileName, 'image/jpeg') + coverUrl = await uploadFileToS3(coverPath, coverFileName, 'image/jpeg', undefined, options.protectedMaterialId) uploadedUrls.push(coverUrl) console.log('[VideoProcessor] Cover image uploaded:', coverUrl) } else { diff --git a/lib/video-transcode-task.ts b/lib/video-transcode-task.ts index e092aaef..f703bfb6 100644 --- a/lib/video-transcode-task.ts +++ b/lib/video-transcode-task.ts @@ -1,5 +1,6 @@ // 视频转码任务封装,供上传接口和转码API复用 import { prisma } from '@/lib/prisma' +import { isRestrictedMaterial } from '@/lib/material-access-scope' import { transcodeQueue } from '@/lib/video-transcode-queue' import { processVideoTranscode, resolveLocalVideoPath } from '@/lib/video-processor' import { access } from 'fs/promises' @@ -321,6 +322,8 @@ export async function executeTranscodeTask( where: { id: materialId }, select: { videoSourceUrl: true, + accessScope: true, + taskDetailPrivate: true, videoCoverUrl: true, previewUrl: true, }, @@ -352,6 +355,7 @@ export async function executeTranscodeTask( } attemptResult = await processVideoTranscode({ + protectedMaterialId: latestMaterial && isRestrictedMaterial(latestMaterial) ? materialId : undefined, inputPath: videoSourceUrl, outputDir: './uploads/transcoded', materialId, diff --git a/lib/white-background-preview.ts b/lib/white-background-preview.ts index 182eb976..5bda5163 100644 --- a/lib/white-background-preview.ts +++ b/lib/white-background-preview.ts @@ -92,6 +92,11 @@ export function resolveWhiteBackgroundPreviewFileUrl(fileUrl?: string | null): s } const publicDisplayPath = buildWhiteBackgroundPublicDisplayPathFromAssetPath(normalizedFileUrl) + const materialId = publicDisplayPath?.split('/')[1] + const protectedPath = materialId && `uploads/materials/${materialId}/protected-display/${publicDisplayPath}` + if (protectedPath && existsSync(resolveAbsoluteLocalPath(protectedPath))) { + return `/api/${protectedPath.split('/').map(encodeURIComponent).join('/')}` + } const publicDisplayUrl = publicDisplayPath ? buildPublicDisplayUrl(publicDisplayPath) : null if (publicDisplayUrl) { return publicDisplayUrl diff --git a/prisma/migrations/20261106110000_material_access_scope/migration.sql b/prisma/migrations/20261106110000_material_access_scope/migration.sql new file mode 100644 index 00000000..b31f459b --- /dev/null +++ b/prisma/migrations/20261106110000_material_access_scope/migration.sql @@ -0,0 +1,12 @@ +ALTER TABLE "materials" + ADD COLUMN "access_scope" TEXT NOT NULL DEFAULT 'general'; + +ALTER TABLE "materials" + ADD CONSTRAINT "materials_access_scope_check" + CHECK ("access_scope" IN ('general', 'operations_g')); + +ALTER TABLE "materials" + ADD CONSTRAINT "materials_operations_g_shared_check" + CHECK ("access_scope" <> 'operations_g' OR "task_detail_private" = false); + +CREATE INDEX "materials_access_scope_idx" ON "materials" ("access_scope"); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 46b57aa8..b90fb801 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -355,6 +355,7 @@ model Material { taskDetailRequesterName String? @map("task_detail_requester_name") taskDetailDemandType String? @map("task_detail_demand_type") taskDetailPrivate Boolean @default(false) @map("task_detail_private") + accessScope String @default("general") @map("access_scope") /// 专用 init 建档时写 true,完成落库后写 false。列表/筛选只读这个标记, /// 不再每次去资产表现场判断是不是上传空壳。 isIncompleteShell Boolean @default(false) @map("is_incomplete_shell") @@ -373,6 +374,7 @@ model Material { @@index([userId]) @@index([custodyDepartmentId]) @@index([taskDetailRequesterUserId]) + @@index([accessScope]) @@index([createdAt]) @@index([categoryName]) @@index([sceneName]) diff --git a/scripts/safe-production-migrate.mjs b/scripts/safe-production-migrate.mjs index f7701235..5f5be79a 100644 --- a/scripts/safe-production-migrate.mjs +++ b/scripts/safe-production-migrate.mjs @@ -49,6 +49,7 @@ const TARGET_MIGRATIONS = Object.freeze([ '20261020120000_desktop_creation_tasks', '20261020150000_desktop_project_deletion', '20261023130000_personnel_salary_base', + '20261106110000_material_access_scope', ]) const VERIFIED_BACKUP_GENERATOR = 'scripts/create-verified-production-backup.mjs' const VERIFIED_BACKUP_MAINTENANCE_CONFIRMATION = 'NO_WRITES_DURING_SNAPSHOT' @@ -357,7 +358,7 @@ export async function queryEvidence(prisma, localMigrations) { `SELECT table_name, column_name, data_type, udt_name, is_nullable, column_default, numeric_precision, numeric_scale FROM information_schema.columns WHERE table_schema = current_schema() - AND ((table_name = 'materials' AND column_name IN ('uploadId', 'transcode_lease_token', 'transcode_lease_expires_at')) + AND ((table_name = 'materials' AND column_name IN ('uploadId', 'transcode_lease_token', 'transcode_lease_expires_at', 'access_scope')) OR (table_name = 'materials' AND column_name IN ('custody_department_id', 'custody_at', 'custody_reason', 'is_incomplete_shell', 'task_detail_demand_type', 'task_detail_private', 'report_kind', 'certificate_expires_on', 'certificate_tested_on', 'certificate_number', 'certificate_usage_instructions', 'report_usage_rules')) OR (table_name = 'product_package_upload_jobs' AND column_name IN ('worker_id', 'lease_token', 'lease_expires_at')) OR (table_name = 'material_permission_pack_items' AND column_name IN ('can_access_private')) @@ -408,6 +409,7 @@ export async function queryEvidence(prisma, localMigrations) { 'materials_transcode_lease_idx', 'materials_uploadId_key', 'materials_is_incomplete_shell_idx', + 'materials_access_scope_idx', 'brand_knowledge_product_category_name_idx', 'brand_knowledge_deleted_at_idx', 'brand_knowledge_likes_knowledge_id_user_id_key', @@ -478,6 +480,8 @@ export async function queryEvidence(prisma, localMigrations) { WHERE ns.nspname = current_schema() AND (con.conname IN ( 'materials_private_optimization_check', + 'materials_access_scope_check', + 'materials_operations_g_shared_check', 'brand_knowledge_likes_knowledge_id_fkey', 'brand_knowledge_likes_user_id_fkey', 'brand_knowledge_favorites_knowledge_id_fkey', @@ -896,6 +900,23 @@ export function assertTargetMigrationEvidence(localMigrations, evidence) { assertAiModelRegistryEvidence(evidence) assertMaterialPurgeEvidence(evidence) assertMaterialPurgeReferenceEvidence(evidence) + assertMaterialAccessScopeEvidence(evidence) +} + +export function assertMaterialAccessScopeEvidence(evidence) { + const column = evidence.columns.find(row => row.table_name === 'materials' && row.column_name === 'access_scope') + if (!column || column.data_type !== 'text' || column.is_nullable !== 'NO' || normalizeColumnDefault(column.column_default) !== 'general') { + fail('Material access scope column mismatch') + } + const index = evidence.indexes.find(row => row.indexname === 'materials_access_scope_idx') + if (!index?.indisvalid || !index.indisready) fail('Material access scope index is not ready') + assertExactBtreeIndex(index.indexdef, 'materials', ['access_scope']) + for (const [name, columns, expression] of [ + ['materials_access_scope_check', ['access_scope'], "access_scope = ANY (ARRAY['general', 'operations_g'])"], + ['materials_operations_g_shared_check', ['access_scope', 'task_detail_private'], "access_scope <> 'operations_g' OR task_detail_private = false"], + ]) { + assertExactCheckConstraint(evidence.constraints.find(row => row.constraint_name === name), 'materials', name, columns, expression) + } } export function materialPurgeReferenceExpectations() { diff --git a/scripts/safe-production-migrate.test.mjs b/scripts/safe-production-migrate.test.mjs index b9020345..08814124 100644 --- a/scripts/safe-production-migrate.test.mjs +++ b/scripts/safe-production-migrate.test.mjs @@ -19,6 +19,7 @@ import { assertOrganizationConfigurationEvidence, assertMaterialPurgeEvidence, assertMaterialPurgeReferenceEvidence, + assertMaterialAccessScopeEvidence, materialPurgeReferenceExpectations, databaseFingerprintHash, normalizeColumnDefault, @@ -392,6 +393,25 @@ test('SOP extracts the exact receipt basename and hash from a real helper result } }) +function materialScopeEvidence() { + return { + columns: [{ table_name: 'materials', column_name: 'access_scope', data_type: 'text', is_nullable: 'NO', column_default: "'general'::text" }], + indexes: [{ indexname: 'materials_access_scope_idx', indexdef: 'CREATE INDEX materials_access_scope_idx ON public.materials USING btree (access_scope)', indisvalid: true, indisready: true }], + constraints: [ + { tablename: 'materials', constraint_name: 'materials_access_scope_check', contype: 'c', convalidated: true, columns: ['access_scope'], expression: "access_scope = ANY (ARRAY['general'::text, 'operations_g'::text])" }, + { tablename: 'materials', constraint_name: 'materials_operations_g_shared_check', contype: 'c', convalidated: true, columns: ['access_scope', 'task_detail_private'], expression: "access_scope <> 'operations_g'::text OR task_detail_private = false" }, + ], + } +} + +test('material scope migration requires the default, ready index and both access constraints', () => { + const evidence = materialScopeEvidence() + assert.doesNotThrow(() => assertMaterialAccessScopeEvidence(evidence)) + assert.throws(() => assertMaterialAccessScopeEvidence({ ...evidence, columns: [{ ...evidence.columns[0], column_default: "'operations_g'::text" }] }), /column mismatch/) + assert.throws(() => assertMaterialAccessScopeEvidence({ ...evidence, indexes: [{ ...evidence.indexes[0], indisready: false }] }), /index is not ready/) + assert.throws(() => assertMaterialAccessScopeEvidence({ ...evidence, constraints: evidence.constraints.slice(0, 1) }), /constraint mismatch/) +}) + test('target evidence rejects nullable logo columns and structurally wrong indexes', () => { const migrations = new Map([ ['20260811_add_video_transcode_lease', { checksum: 'a' }], @@ -730,6 +750,12 @@ test('target evidence rejects nullable logo columns and structurally wrong index const organization = organizationEvidence() const purge = purgeEvidence() for (const key of ['columns', 'indexes', 'constraints']) evidence[key].push(...organization[key], ...purge[key]) + migrations.set('20261106110000_material_access_scope', { checksum: 'material-scope' }) + evidence.migrationRows.push({ migration_name: '20261106110000_material_access_scope', checksum: 'material-scope', finished_at: 'now', rolled_back_at: null }) + const scopeEvidence = materialScopeEvidence() + evidence.columns.push(...scopeEvidence.columns) + evidence.indexes.push(...scopeEvidence.indexes) + evidence.constraints.push(...scopeEvidence.constraints) assert.doesNotThrow(() => assertTargetMigrationEvidence(migrations, evidence)) const nullableLogo = { ...evidence, @@ -1091,12 +1117,12 @@ test('container supply chain and migrator image are immutable while SOP keeps co assert.match(sop, /-v "\$HOST_RESULT_DIR:\/audit"/) assert.match(sop, /test -f "\$PREFLIGHT_AUDIT_FILE" && test ! -L "\$PREFLIGHT_AUDIT_FILE"/) assert.doesNotMatch(sop, /-v \/root\/gongxiangp2-migration-audit:\/audit/) - assert.match(sop, /四十份目标 migration/) - assert.match(sop, /四十条目标 migration/) + assert.match(sop, /四十一份目标 migration/) + assert.match(sop, /四十一条目标 migration/) const targetBlock = migratorSource.match(/const TARGET_MIGRATIONS = Object\.freeze\(\[([\s\S]*?)\]\)/)?.[1] assert.ok(targetBlock, 'Migrator target list must be inspectable') const targets = [...targetBlock.matchAll(/'([^']+)'/g)].map(match => match[1]) - assert.equal(targets.length, 40) + assert.equal(targets.length, 41) for (const migration of targets) assert.ok(sop.includes(`\`${migration}\``), `SOP must name ${migration}`) const applyMigration = migratorSource.indexOf("['migrate', 'deploy'")