198 lines
6.8 KiB
TypeScript
198 lines
6.8 KiB
TypeScript
import { createHash } from 'node:crypto'
|
||
import { loadEnvConfig } from '@next/env'
|
||
import { BomCostingReferenceSyncStatus, Prisma } from '@prisma/client'
|
||
import {
|
||
BOM_COST_BACKTEST_MAX_SAMPLE_SIZE,
|
||
BOM_COST_BACKTEST_MIN_SAMPLE_SIZE,
|
||
buildBomCostBacktestReport,
|
||
evaluateBomCostBacktestCase,
|
||
selectBomCostBacktestCandidates,
|
||
type BomCostBacktestMirrorRow,
|
||
} from '../src/lib/bom-costing/dynamic-bom-cost-backtest'
|
||
|
||
loadEnvConfig(process.cwd())
|
||
|
||
type CliOptions = {
|
||
sampleSize: number
|
||
help: boolean
|
||
}
|
||
|
||
const mirrorRowSelect = Prisma.validator<Prisma.BomCostingReferenceRowSelect>()({
|
||
sourceRowId: true,
|
||
sourceSku: true,
|
||
bomVersionKey: true,
|
||
category: true,
|
||
categoryCode: true,
|
||
partNumber: true,
|
||
partName: true,
|
||
materialName: true,
|
||
materialCode: true,
|
||
materialSpec: true,
|
||
processName: true,
|
||
unit: true,
|
||
rawNote: true,
|
||
lengthMm: true,
|
||
widthMm: true,
|
||
quantity: true,
|
||
coefficient: true,
|
||
areaSqm: true,
|
||
edgeLengthM: true,
|
||
unitPrice: true,
|
||
amount: true,
|
||
sourceCreatedAt: true,
|
||
syncedAt: true,
|
||
isSummaryRow: true,
|
||
})
|
||
|
||
function parseArgs(argv: string[]): CliOptions {
|
||
const options: CliOptions = { sampleSize: 30, help: false }
|
||
for (const argument of argv) {
|
||
if (argument === '--help' || argument === '-h') options.help = true
|
||
else if (argument.startsWith('--sample-size=')) {
|
||
const sampleSize = Number(argument.slice('--sample-size='.length))
|
||
if (!Number.isSafeInteger(sampleSize) ||
|
||
sampleSize < BOM_COST_BACKTEST_MIN_SAMPLE_SIZE ||
|
||
sampleSize > BOM_COST_BACKTEST_MAX_SAMPLE_SIZE) {
|
||
throw new Error(
|
||
`--sample-size must be an integer between ${BOM_COST_BACKTEST_MIN_SAMPLE_SIZE} and ${BOM_COST_BACKTEST_MAX_SAMPLE_SIZE}`,
|
||
)
|
||
}
|
||
options.sampleSize = sampleSize
|
||
} else {
|
||
throw new Error(`Unknown argument: ${argument}`)
|
||
}
|
||
}
|
||
return options
|
||
}
|
||
|
||
function printHelp() {
|
||
console.log(`
|
||
Usage:
|
||
npm run backtest:bom-cost-reference
|
||
npm run backtest:bom-cost-reference -- --sample-size=50
|
||
|
||
只读取本地最新成功 BOM 镜像,不访问上游,也不写数据库。默认稳定抽取 30 个公司 SKU,
|
||
比较历史“总成本”与当前规则逐行重算结果。样本只能设为 20 至 50;任何可比较 SKU
|
||
误差超过固定 10% 门槛,或可比较样本不足,命令都会以非 0 状态退出。
|
||
`.trim())
|
||
}
|
||
|
||
function stableCandidateKey(sourceSku: string, bomVersionKey: string) {
|
||
return createHash('sha256').update(`${sourceSku}\u0000${bomVersionKey}`).digest('hex')
|
||
}
|
||
|
||
function pairKey(sourceSku: string, bomVersionKey: string) {
|
||
return `${sourceSku}\u0000${bomVersionKey}`
|
||
}
|
||
|
||
async function main() {
|
||
const options = parseArgs(process.argv.slice(2))
|
||
if (options.help) {
|
||
printHelp()
|
||
return
|
||
}
|
||
const { prisma } = await import('../src/lib/prisma')
|
||
try {
|
||
const latestSuccessful = await prisma.bomCostingReferenceSyncRun.findFirst({
|
||
where: { status: BomCostingReferenceSyncStatus.SUCCEEDED },
|
||
orderBy: [{ completedAt: 'desc' }, { createdAt: 'desc' }],
|
||
select: {
|
||
id: true,
|
||
batchKey: true,
|
||
completedAt: true,
|
||
sourceAsOf: true,
|
||
rowsRead: true,
|
||
},
|
||
})
|
||
if (!latestSuccessful) throw new Error('本地没有成功的 BOM 镜像批次,无法回测')
|
||
|
||
const [summaryRows, residualRow] = await Promise.all([
|
||
prisma.bomCostingReferenceRow.findMany({
|
||
where: {
|
||
syncRunId: latestSuccessful.id,
|
||
isSummaryRow: true,
|
||
amount: { gt: 0 },
|
||
sourceSku: { not: '' },
|
||
},
|
||
select: mirrorRowSelect,
|
||
orderBy: [{ sourceSku: 'asc' }, { sourceCreatedAt: 'desc' }],
|
||
}),
|
||
prisma.bomCostingReferenceRow.findFirst({
|
||
where: { syncRunId: { not: latestSuccessful.id } },
|
||
select: { syncRunId: true },
|
||
}),
|
||
])
|
||
const typedSummaries = summaryRows as BomCostBacktestMirrorRow[]
|
||
const summaryById = new Map(typedSummaries.map((row) => [row.sourceRowId, row]))
|
||
const candidates = selectBomCostBacktestCandidates(typedSummaries)
|
||
.sort((left, right) => stableCandidateKey(left.sourceSku, left.bomVersionKey)
|
||
.localeCompare(stableCandidateKey(right.sourceSku, right.bomVersionKey)))
|
||
const evaluations = []
|
||
let evaluatedCandidateCount = 0
|
||
const chunkSize = Math.max(50, options.sampleSize * 2)
|
||
for (let offset = 0; offset < candidates.length &&
|
||
evaluations.filter((evaluation) => evaluation.status === 'COMPARABLE').length < options.sampleSize;
|
||
offset += chunkSize) {
|
||
const chunk = candidates.slice(offset, offset + chunkSize)
|
||
const sourceSkus = Array.from(new Set(chunk.map((candidate) => candidate.sourceSku)))
|
||
const detailRows = await prisma.bomCostingReferenceRow.findMany({
|
||
where: {
|
||
syncRunId: latestSuccessful.id,
|
||
isSummaryRow: false,
|
||
sourceSku: { in: sourceSkus },
|
||
},
|
||
select: mirrorRowSelect,
|
||
orderBy: [{ sourceSku: 'asc' }, { sourceRowId: 'asc' }],
|
||
}) as BomCostBacktestMirrorRow[]
|
||
const detailsByPair = new Map<string, BomCostBacktestMirrorRow[]>()
|
||
for (const row of detailRows) {
|
||
const key = pairKey(row.sourceSku, row.bomVersionKey)
|
||
const values = detailsByPair.get(key) ?? []
|
||
values.push(row)
|
||
detailsByPair.set(key, values)
|
||
}
|
||
for (const candidate of chunk) {
|
||
evaluatedCandidateCount += 1
|
||
const summary = summaryById.get(candidate.historicalTotalSourceRowId)
|
||
if (!summary) continue
|
||
const evaluation = evaluateBomCostBacktestCase([
|
||
...(detailsByPair.get(pairKey(candidate.sourceSku, candidate.bomVersionKey)) ?? []),
|
||
summary,
|
||
])
|
||
if (evaluation) evaluations.push(evaluation)
|
||
if (evaluations.filter((item) => item.status === 'COMPARABLE').length >= options.sampleSize) break
|
||
}
|
||
}
|
||
|
||
const report = buildBomCostBacktestReport({
|
||
evaluations,
|
||
requestedSampleSize: options.sampleSize,
|
||
})
|
||
console.log(JSON.stringify({
|
||
generatedAt: new Date().toISOString(),
|
||
dataSource: 'LOCAL_BOM_REFERENCE_MIRROR',
|
||
upstreamAccessed: false,
|
||
sync: {
|
||
runId: latestSuccessful.id,
|
||
batchKey: latestSuccessful.batchKey,
|
||
completedAt: latestSuccessful.completedAt?.toISOString() ?? null,
|
||
sourceAsOf: latestSuccessful.sourceAsOf?.toISOString() ?? null,
|
||
rowsRead: latestSuccessful.rowsRead,
|
||
mirrorState: residualRow ? 'MIXED' : 'SINGLE_SUCCESSFUL_SNAPSHOT',
|
||
residualRunId: residualRow?.syncRunId ?? null,
|
||
},
|
||
availableCandidateCount: candidates.length,
|
||
evaluatedCandidateCount,
|
||
...report,
|
||
}, null, 2))
|
||
if (!report.passed) process.exitCode = 1
|
||
} finally {
|
||
await prisma.$disconnect()
|
||
}
|
||
}
|
||
|
||
void main().catch((error) => {
|
||
console.error(`BOM cost backtest failed: ${error instanceof Error ? error.message : String(error)}`)
|
||
process.exitCode = 1
|
||
})
|