furniture-3d-system-Wu/furniture-3d-system/scripts/import-sample-progress-xlsx.ts

134 lines
6.0 KiB
TypeScript

import type { Prisma } from '@prisma/client'
import * as XLSX from 'xlsx'
import { prisma } from '@/lib/prisma'
type SourceRow = Record<string, unknown>
type ImportRow = {
openingCode: string
orderDate: Date
productSize: string
color: string
material: string
sampleQuantity: number
sampleDueDate: Date
supplier: string
finalSampleFactory: string | null
status: string | null
progressDescription: string | null
requestedCost: number | null
actualCost: number | null
}
const statusByLabel: Record<string, string> = {
'白茬': 'BARE_WOOD',
'白茬审样': 'BARE_WOOD_REVIEW',
'油漆': 'PAINT',
'视频审核成品': 'VIDEO_REVIEW',
'寄样': 'SAMPLE_SHIPPING',
'实物审样': 'PHYSICAL_REVIEW',
'已完结': 'COMPLETED',
}
function text(value: unknown) {
return String(value ?? '').trim()
}
function uniqueLines(values: string[]) {
return Array.from(new Set(values.flatMap((value) => value.split(/\r?\n/)).map((value) => value.trim()).filter(Boolean))).join('\n')
}
function excelDate(value: unknown, fieldName: string) {
if (typeof value === 'number') {
const parsed = XLSX.SSF.parse_date_code(value)
if (parsed) return new Date(Date.UTC(parsed.y, parsed.m - 1, parsed.d))
}
const compactDate = text(value).match(/^(\d{4})\/(\d{1,2})(\d{2})$/)
const normalized = compactDate
? `${compactDate[1]}-${compactDate[2].padStart(2, '0')}-${compactDate[3]}`
: text(value).replaceAll('/', '-')
const parsed = new Date(`${normalized}T00:00:00Z`)
if (!Number.isNaN(parsed.getTime())) return parsed
throw new Error(`${fieldName}无法识别: ${text(value)}`)
}
function numberOrNull(value: unknown) {
if (value === null || value === undefined || text(value) === '') return null
if (typeof value === 'number' && Number.isFinite(value)) return value
const normalized = text(value)
return /^\d+(?:\.\d+)?$/.test(normalized) ? Number(normalized) : null
}
function mapRows(rows: SourceRow[]): ImportRow[] {
const grouped = new Map<string, SourceRow[]>()
for (const row of rows) {
const openingCode = text(row['开款编号']).toUpperCase()
if (!openingCode) continue
grouped.set(openingCode, [...(grouped.get(openingCode) ?? []), row])
}
return Array.from(grouped, ([openingCode, sourceRows]) => {
const first = sourceRows[0]
const descriptions = sourceRows.map((row) => text(row['进度说明'])).filter(Boolean)
const ambiguousCosts = sourceRows.map((row) => text(row['实际成本'])).filter((value) => value && numberOrNull(value) === null)
if (ambiguousCosts.length) descriptions.push(`多报价:${uniqueLines(ambiguousCosts)}`)
const statuses = sourceRows.map((row) => statusByLabel[text(row['打样状态'])]).filter(Boolean)
const requestedCosts = sourceRows.map((row) => numberOrNull(row['需求成本'])).filter((value): value is number => value !== null)
const actualCosts = sourceRows.map((row) => numberOrNull(row['实际成本'])).filter((value): value is number => value !== null)
return {
openingCode,
orderDate: excelDate(first['下单时间'], `${openingCode} 下单时间`),
productSize: uniqueLines(sourceRows.map((row) => text(row['产品尺寸']))),
color: uniqueLines(sourceRows.map((row) => text(row['颜色/材质']))) || '待确认',
material: uniqueLines(sourceRows.map((row) => text(row['颜色/材质']))) || '待确认',
sampleQuantity: sourceRows.reduce((sum, row) => sum + (numberOrNull(row['数量']) ?? 0), 0) || 1,
sampleDueDate: new Date(Math.max(...sourceRows.map((row) => excelDate(row['打样交期'], `${openingCode} 打样交期`).getTime()))),
supplier: uniqueLines(sourceRows.map((row) => text(row['供应商']))) || '待确认',
finalSampleFactory: uniqueLines(sourceRows.map((row) => text(row['最终出样厂家']))) || null,
status: statuses.at(-1) ?? null,
progressDescription: uniqueLines(descriptions) || null,
requestedCost: requestedCosts.length === 1 ? requestedCosts[0] : null,
actualCost: actualCosts.length === 1 ? actualCosts[0] : null,
}
})
}
async function main() {
const filePath = process.argv.find((value) => value.endsWith('.xlsx'))
const apply = process.argv.includes('--apply')
if (!filePath) throw new Error('用法: tsx scripts/import-sample-progress-xlsx.ts <file.xlsx> [--apply]')
const workbook = XLSX.readFile(filePath, { cellDates: false })
const sheet = workbook.Sheets[workbook.SheetNames[0]]
const rows = mapRows(XLSX.utils.sheet_to_json<SourceRow>(sheet, { defval: null }))
const existing = await prisma.sampleProgressItem.findMany({ where: { openingCode: { in: rows.map((row) => row.openingCode) } }, select: { openingCode: true } })
const existingCodes = new Set(existing.map((row) => row.openingCode))
const summary = { sourceRows: XLSX.utils.sheet_to_json(sheet).length, uniqueOpeningCodes: rows.length, matched: existing.length, toCreate: rows.filter((row) => !existingCodes.has(row.openingCode)).length, apply }
console.log(JSON.stringify(summary, null, 2))
if (!apply) return
await prisma.$transaction(rows.map((row) => {
const update: Prisma.SampleProgressItemUpdateInput = {
orderDate: row.orderDate,
productSize: row.productSize,
color: row.color,
material: row.material,
sampleQuantity: row.sampleQuantity,
sampleDueDate: row.sampleDueDate,
supplier: row.supplier,
finalSampleFactory: row.finalSampleFactory,
...(row.status ? { status: row.status } : {}),
...(row.progressDescription ? { progressDescription: row.progressDescription } : {}),
...(row.requestedCost !== null ? { requestedCost: row.requestedCost } : {}),
...(row.actualCost !== null ? { actualCost: row.actualCost } : {}),
autoGenerated: false,
}
return prisma.sampleProgressItem.upsert({
where: { openingCode: row.openingCode },
update,
create: { ...row, status: row.status ?? 'BARE_WOOD', brand: '', designer: '', autoGenerated: false },
})
}))
console.log(`已导入 ${rows.length} 条打样记录`)
}
main().finally(() => prisma.$disconnect())