feat(materials): add shared operations G access scope

This commit is contained in:
WuYongJie 2026-11-06 16:00:50 +08:00
parent 72674fdc5b
commit 00ef6936cd
117 changed files with 1509 additions and 252 deletions

View File

@ -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' },

View File

@ -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,

View File

@ -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,

View File

@ -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 } = {}

View File

@ -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({

View File

@ -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' } })

View File

@ -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 预览生成失败')

View File

@ -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' },

View File

@ -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,
},

View File

@ -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),

View File

@ -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,
},

View File

@ -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;

View File

@ -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 } : {}),

View File

@ -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,

View File

@ -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: {

View File

@ -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({

View File

@ -64,7 +64,7 @@ export async function GET(request: NextRequest) {
assetType: 'sku-preview',
material: {
materialType: '任务-详情',
taskDetailPrivate: false,
taskDetailPrivate: false, accessScope: 'general',
deletedAt: null,
},
},

View File

@ -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,

View File

@ -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<ResolvedStandardModelTarget> {
const matches = await prisma.material.findMany({
where: {
where: { accessScope: 'general',
productModel: {
equals: input.spu,
mode: 'insensitive',

View File

@ -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,
},

View File

@ -239,7 +239,7 @@ async function findVideoMaterials(keyword: string): Promise<MaterialRow[]> {
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<MaterialRow[]> {
)
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<MaterialRow[]> {
// ── 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<MaterialRow[]> {
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<MaterialRow[]> {
// ── 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 },

View File

@ -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;
}

View File

@ -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),

View File

@ -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,
},
},

View File

@ -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<SkuRouteMaterial, 'userId'>,
material: Pick<SkuRouteMaterial, 'id' | 'userId'> & Partial<SkuRouteMaterial>,
): Promise<boolean> {
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<boolean> {
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',

View File

@ -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,

View File

@ -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<string, { data: any; expiresAt: number }>()
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<ReturnType<typeof createMaterialQueryContext>>): 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(

View File

@ -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({

View File

@ -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 字段)

View File

@ -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: '删除成功(可恢复),文件已保留' });
}

View File

@ -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,

View File

@ -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,

View File

@ -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(

View File

@ -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 唯一约束错误(任务号重复)

View File

@ -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 唯一约束错误(任务号重复)

View File

@ -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) => {

View File

@ -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 })
}

View File

@ -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' })

View File

@ -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(

View File

@ -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;

View File

@ -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 唯一约束错误(任务号重复)

View File

@ -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 已有赢家,就返回赢家且不清理任何候选文件。

View File

@ -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 唯一约束错误(任务号重复)

View File

@ -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 唯一约束错误(任务号重复)

View File

@ -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<string, { materialType: string }>()
const uploadMaterialInfoMap = new Map<string, { materialType: string; accessScope: string }>()
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'] },
},

View File

@ -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;

View File

@ -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,
},

View File

@ -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,
});

View File

@ -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;
}

View File

@ -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,

View File

@ -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, {

View File

@ -57,6 +57,7 @@ export async function GET(request: NextRequest) {
previewUrl: true,
displayImages: true,
materialType: true,
accessScope: true,
categoryName: true,
sceneName: true,
platformName: true,

View File

@ -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,

View File

@ -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<MaterialAccessScope>('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 } })
</Select>
</div>
<MaterialAccessScopeField
id={`edit-material-${params.id}-scope`}
value={accessScope}
onChange={setAccessScope}
disabled={submitting}
/>
{showCategoryScene && (
<>
<div>

View File

@ -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() {
<MaterialDetailHeader
title={materialDisplayTitle || material.productModel || material.materialType}
materialType={mappedMaterialType}
accessScope={material.accessScope}
materialId={material.id}
isFavorited={Boolean(material.isFavorited)}
capabilities={material.capabilities || {

View File

@ -1,5 +1,8 @@
'use client'
import MaterialAccessScopeField from '@/components/upload/MaterialAccessScopeField'
import type { MaterialAccessScope } from '@/lib/material-access-scope'
import { useState, useRef, useEffect, useCallback } from 'react'
import { useGSAP } from '@gsap/react'
import gsap from 'gsap'
@ -176,6 +179,8 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = {
const [productCategoryName, setProductCategoryName] = useState('')
// 素材类型
const [materialType, setMaterialType] = useState('3D场景')
const [accessScope, setAccessScope] = useState<MaterialAccessScope>('general')
const [dedicatedUploading, setDedicatedUploading] = useState(false)
// 可见的素材类型列表(从API动态加载)
const [availableMaterialTypes, setAvailableMaterialTypes] = useState<string[]>([])
@ -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<HTMLInputElement>(null)
const zipInputRef = useRef<HTMLInputElement>(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}
/>
</div>
<MaterialAccessScopeField
id="upload-access-scope"
value={accessScope}
onChange={setAccessScope}
disabled={interactionLocked}
/>
{!usesDedicatedUploader && (
<TaskReferenceFields
idPrefix="generic-task-upload"
@ -2071,6 +2086,8 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = {
{materialType === '任务-详情' && (
<div>
<ProductPackageUploader
accessScope={accessScope}
onBusyChange={setDedicatedUploading}
onSuccess={() => {
onSuccess();
onClose();
@ -2090,6 +2107,8 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = {
{materialType === '任务-视频截图' && (
<div>
<VideoScreenshotUploader
accessScope={accessScope}
onBusyChange={setDedicatedUploading}
onSuccess={() => {
onSuccess();
onClose();
@ -2109,6 +2128,8 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = {
{materialType === '任务-页面' && (
<div>
<TaskPageUploader
accessScope={accessScope}
onBusyChange={setDedicatedUploading}
onSuccess={() => {
onSuccess();
onClose();
@ -2128,6 +2149,8 @@ export default function UploadModal({ onClose, onSuccess, materialTypeCounts = {
{materialType === '证书-检测报告' && (
<div>
<CertificateReportUploader
accessScope={accessScope}
onBusyChange={setDedicatedUploading}
onSuccess={() => {
onSuccess();
onClose();

View File

@ -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())

View File

@ -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({
<h1 className="truncate text-[20px] font-semibold tracking-[-0.03em] text-[#1a1c1d] sm:text-[22px]" title={title}>
{title}
</h1>
<p className="mt-1 flex min-w-0 items-center gap-2 text-[12px] text-[#86898e]">
<span className="flex-none">{materialType}</span>
<p className="mt-1 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-[12px] text-[#86898e]">
<span className="flex-none">{accessScope === 'operations_g' ? `${materialType} · 运营中心 G 专属` : materialType}</span>
<span aria-hidden="true">·</span>
<span className="truncate font-en tabular-nums tracking-[0.04em]" title={materialId}>ID {materialId}</span>
</p>

View File

@ -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 && (
<div>
<p className={detailMetaLabelClass}>需求类型 / 可见范围</p>
<p className={detailMetaValueClass}>{material.taskDetailDemandType} · {material.taskDetailPrivate ? '私密' : '公开'}</p>
<p className={detailMetaValueClass}>{material.taskDetailDemandType} · {material.accessScope === 'operations_g' ? '中心内共享' : material.taskDetailPrivate ? '私密' : '公开'}</p>
</div>
)}
<div>

View File

@ -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({
</div>
<div className="pt-4">
{material.accessScope === 'operations_g' && (
<p className="mb-1 text-xs font-medium text-[#52565b]">运营中心 G 专属</p>
)}
<h3 className="truncate font-display text-[16px] font-semibold tracking-[-0.03em] text-[#1a1c1d]">
{materialDisplayTitle}
</h3>

View File

@ -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<ReportFileItem[]>([])
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,

View File

@ -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<MaterialAccessScope>('general')
return <MaterialAccessScopeField id="scope" value={value} onChange={(next) => { changed(next); setValue(next) }} />
}
const user = userEvent.setup()
render(<Form />)
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(<MaterialAccessScopeField id="scope" value="operations_g" onChange={changed} disabled />)
const field = screen.getByRole('combobox', { name: '使用范围 *' })
expect(field).toBeDisabled()
await userEvent.click(field)
expect(screen.queryByRole('listbox')).not.toBeInTheDocument()
expect(changed).not.toHaveBeenCalled()
})

View File

@ -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 (
<div className="min-w-0 space-y-1">
<label htmlFor={id} className={fieldLabelClass}>使用范围 *</label>
<Select
id={id}
value={value}
onChange={(event) => onChange(event.target.value as MaterialAccessScope)}
disabled={disabled}
required
aria-describedby={`${id}-hint`}
className={`${fieldControlClass} min-h-11`}
>
{MATERIAL_ACCESS_SCOPES.map((scope) => (
<option key={scope} value={scope}>{MATERIAL_ACCESS_SCOPE_LABELS[scope]}</option>
))}
</Select>
<p id={`${id}-hint`} className={fieldHintClass}>
{value === 'operations_g'
? '仅运营中心 G 及其下属部门成员可见,中心内共享。'
: '按现有素材权限使用。'}
</p>
</div>
)
}

View File

@ -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<TaskDetailSourceType | ''>('');
const [taskDetailDemandType, setTaskDetailDemandType] = useState<TaskDetailDemandType>('新品');
const [taskDetailPrivate, setTaskDetailPrivate] = useState(false);
useEffect(() => {
if (accessScope === 'operations_g') setTaskDetailPrivate(false)
}, [accessScope]);
const [taskDetailRequesterUserId, setTaskDetailRequesterUserId] = useState('');
const [users, setUsers] = useState<Array<{ id: string; username: string; displayName: string }>>([]);
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<typeof normalizeTaskDetailPrivacyFields>;
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({
</label>
<Select
id="task-detail-visibility"
disabled={accessScope === 'operations_g' || uploading}
value={taskDetailVisibilityValue}
onChange={(e) => handleTaskDetailVisibilityChange(e.target.value as 'public' | 'private')}
disabled={uploading}
aria-describedby="task-detail-visibility-hint"
className={TASK_DETAIL_METADATA_FIELD_CLASS_NAME}
>
<option value="public">公开</option>
<option value="public">{accessScope === 'operations_g' ? '中心内共享' : '公开'}</option>
<option value="private" disabled={!isOptimizationDemand}>私密</option>
</Select>
</div>

View File

@ -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,

View File

@ -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,

View File

@ -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) {

View File

@ -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<str
if (metadata.livePlatform) formData.append('livePlatform', String(metadata.livePlatform))
const materialType = metadata.materialType || '3D场景'
formData.append('materialType', materialType)
formData.append('accessScope', metadata.accessScope || 'general')
// 统一处理renderer字段:根据素材类型判断是否需要传递
const rendererInfo = shouldPassRenderer(materialType, metadata.renderer)
@ -382,9 +384,11 @@ export async function uploadBatchMusic(
files: Array<{ file: File; productModel: string }>,
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: '通用',

View File

@ -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`:备份与隔离恢复验证通过后执行,审计同时核对字段默认值、索引、范围枚举约束及中心内共享约束。

View File

@ -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 成功后立即固定审计文件本身;后续“迁移批次部署”读取这一个文件,不能手工重写:

View File

@ -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([])
})

View File

@ -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' })
})

View File

@ -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,

View File

@ -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(

View File

@ -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)
})
})

View File

@ -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' },
] }] }),
}))
})

View File

@ -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({

View File

@ -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()

View File

@ -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)

View File

@ -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)
})

View File

@ -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',

View File

@ -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' },
}))
})
})

View File

@ -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(

View File

@ -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: {

View File

@ -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),

View File

@ -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
}

View File

@ -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

View File

@ -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: {

View File

@ -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<string, any>,
assets: Array<{ id: string; fileUrl: string }>,
skus: Array<{ id: string; filePath: string; previewUrl: string | null }> = [],
) {
const replacements = new Map<string, string>()
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<string, string | string[]> = {}
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()) }
}

View File

@ -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<MaterialAccessScope, string> = {
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
}

View File

@ -62,7 +62,7 @@ export async function canManageMaterial(
material: MaterialAuthorizationTarget,
): Promise<boolean> {
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,

View File

@ -0,0 +1,26 @@
type CacheEntry = { data: any; expiresAt: number }
const shared = globalThis as typeof globalThis & { __materialFacetsCache?: Map<string, CacheEntry> }
const cache = shared.__materialFacetsCache ||= new Map<string, CacheEntry>()
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()
}

View File

@ -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<boolean> {
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<MaterialAccessScope> {
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<string[]> {
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)]))
}

View File

@ -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<string> {
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<string> {
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
}

View File

@ -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<boolean> {
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(),

View File

@ -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 }
}

View File

@ -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<string, any> = {
...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 已完整记下了

View File

@ -37,7 +37,8 @@ export interface PdfUploadResult {
*/
export async function processPdfUpload(
pdfFilePath: string,
existingPreviewUrl?: string
existingPreviewUrl?: string,
protectedMaterialId?: string,
): Promise<PdfUploadResult> {
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)

View File

@ -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,

View File

@ -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})`,
);
}
}

Some files were not shown because too many files have changed in this diff Show More