import path from 'path' import { promises as fs } from 'fs' import { buildHistoryImportRecordsFromSkuCsv } from '@/lib/history-sku-csv-import' import { prisma } from '@/lib/prisma' function parseArgs() { const args = process.argv.slice(2) const getArg = (name: string) => { const match = args.find((arg) => arg.startsWith(`--${name}=`)) return match ? match.slice(name.length + 3) : '' } const input = getArg('input') const output = getArg('output') || path.join(process.cwd(), 'output', `history-sku-import-scan-${Date.now()}.json`) const limitRaw = getArg('limit') const sourceRootsRaw = getArg('source-roots') if (!input) { throw new Error('缺少 --input=SKU清单CSV路径') } return { input, output, limit: limitRaw ? Number(limitRaw) : undefined, sourceRoots: sourceRootsRaw ? sourceRootsRaw.split(',').map((item) => item.trim()).filter(Boolean) : undefined, } } async function main() { const options = parseArgs() const visualCenterAuthorRows = await prisma.user.findMany({ where: { archivedAt: null, department: '视觉中心', }, select: { username: true, realName: true, }, orderBy: [{ realName: 'asc' }, { username: 'asc' }], }) const visualCenterAuthors = Array.from( new Set( visualCenterAuthorRows .flatMap((item) => [item.realName || '', item.username || '']) .map((item) => item.trim()) .filter(Boolean), ), ) console.log('按SKU清单生成历史导入记录开始') console.log(`- 输入CSV: ${options.input}`) console.log(`- 视觉中心作者别名数(去重后): ${visualCenterAuthors.length}`) console.log(`- 视觉中心用户数: ${visualCenterAuthorRows.length}`) if (options.sourceRoots?.length) { console.log(`- 限定来源: ${options.sourceRoots.join(', ')}`) } const records = await buildHistoryImportRecordsFromSkuCsv({ csvPath: options.input, limit: options.limit, sourceRoots: options.sourceRoots, visualCenterAuthors, }) await fs.mkdir(path.dirname(options.output), { recursive: true }) await fs.writeFile(options.output, JSON.stringify(records, null, 2), 'utf8') const summary = records.reduce( (acc, record) => { acc.total += 1 acc[record.status] += 1 return acc }, { total: 0, ready: 0, needs_review: 0, skipped: 0 } as Record, ) console.log('\n生成完成') console.log(`- 总记录数: ${summary.total}`) console.log(`- 可直接导入: ${summary.ready}`) console.log(`- 需要人工确认: ${summary.needs_review}`) console.log(`- 已跳过: ${summary.skipped}`) console.log(`- 输出文件: ${options.output}`) const preview = records.slice(0, 12).map((record) => ({ status: record.status, spu: record.spu, store: record.guessedStore, main: record.mainCount, sku: record.skuCount, detail: record.detailCount, path: record.relativeSourcePath, reason: record.skipReason, })) console.table(preview) } main() .catch((error) => { console.error('按SKU清单生成历史导入记录失败:', error) process.exitCode = 1 }) .finally(async () => { await prisma.$disconnect() process.exit(process.exitCode ?? 0) })