Merge remote-tracking branch 'origin/codex/xuxiake-mainline' into codex/xuxiake-supply-chain-archive-release-20260804
# Conflicts: # scripts/deploy-yydd-prod-from-git.ps1
This commit is contained in:
commit
2cb7a35c26
@ -5,7 +5,11 @@ import { jsonError, jsonSuccess } from '@/server/core/response'
|
||||
import { bomCostingWorkerService } from '@/server/services/bom-costing/bom-costing-worker.service'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const maxDuration = 780
|
||||
// A single worker turn may synthesize a large SKU catalog after the image
|
||||
// facts have been reused. Keep this bounded, but do not cut a healthy run off
|
||||
// at the old 30-minute HTTP client limit. This is still a finite safety cap;
|
||||
// stalled batches are split by the analyzer instead of retrying indefinitely.
|
||||
export const maxDuration = 2700
|
||||
|
||||
function hasValidWorkerSecret(request: NextRequest) {
|
||||
const expected = process.env.BOM_COSTING_WORKER_SECRET?.trim()
|
||||
|
||||
@ -151,7 +151,7 @@ export const competitorAnalysisResultV1Schema = z.object({
|
||||
}).optional(),
|
||||
),
|
||||
}),
|
||||
skus: z.array(competitorSkuSchema).min(1).max(200),
|
||||
skus: z.array(competitorSkuSchema).min(1).max(600),
|
||||
analyzedAt: z.iso.datetime(),
|
||||
})
|
||||
|
||||
|
||||
@ -219,8 +219,14 @@ function readSystemName(metadata: Prisma.JsonValue | null) {
|
||||
return typeof value === 'string' ? value.trim() : ''
|
||||
}
|
||||
|
||||
function buildSkuCreateData(skus: BomCostingPreparedSku[]) {
|
||||
const BOM_COSTING_PERSIST_BATCH_SIZE = 250
|
||||
|
||||
function buildSkuCreateData(
|
||||
caseId: string,
|
||||
skus: BomCostingPreparedSku[],
|
||||
): Prisma.BomCostingSkuCreateManyInput[] {
|
||||
return skus.map((sku) => ({
|
||||
caseId,
|
||||
externalSkuId: sku.externalSkuId,
|
||||
name: sku.name,
|
||||
structureGroupKey: sku.structureGroupKey,
|
||||
@ -237,52 +243,93 @@ function buildSkuCreateData(skus: BomCostingPreparedSku[]) {
|
||||
estimatedCost: sku.estimatedCost,
|
||||
costCalculatedAt: sku.costCalculatedAt,
|
||||
sortOrder: sku.sortOrder,
|
||||
bomLines: {
|
||||
create: sku.bomLines.map((line) => ({
|
||||
externalLineId: line.externalLineId,
|
||||
category: line.category,
|
||||
partName: line.partName,
|
||||
materialCode: line.materialCode,
|
||||
materialName: line.materialName,
|
||||
materialSpec: line.materialSpec,
|
||||
processName: line.processName,
|
||||
packagingKind: line.packagingKind,
|
||||
lengthMm: line.lengthMm,
|
||||
widthMm: line.widthMm,
|
||||
heightMm: line.heightMm,
|
||||
quantity: line.quantity,
|
||||
unit: line.unit,
|
||||
weightKg: line.weightKg,
|
||||
lossFactor: line.lossFactor,
|
||||
sourceConfidence: line.sourceConfidence,
|
||||
evidence: line.evidence,
|
||||
matchStatus: line.matchStatus,
|
||||
matchedLibraryType: line.matchedLibraryType,
|
||||
matchedLibraryRecordId: line.matchedLibraryRecordId,
|
||||
matchedLibraryName: line.matchedLibraryName,
|
||||
matchedLibrarySpec: line.matchedLibrarySpec,
|
||||
resolvedUnitPrice: line.resolvedUnitPrice,
|
||||
calculatedQuantity: line.calculatedQuantity,
|
||||
subtotal: line.subtotal,
|
||||
sortOrder: line.sortOrder,
|
||||
priceSnapshots: line.priceSnapshot
|
||||
? {
|
||||
create: {
|
||||
sourceType: line.priceSnapshot.sourceType,
|
||||
sourceRecordId: line.priceSnapshot.sourceRecordId,
|
||||
sourceName: line.priceSnapshot.sourceName,
|
||||
sourceSpec: line.priceSnapshot.sourceSpec,
|
||||
unitPrice: line.priceSnapshot.unitPrice,
|
||||
unit: line.priceSnapshot.unit,
|
||||
lossFactor: line.priceSnapshot.lossFactor,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
})),
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
function buildLineCreateData(
|
||||
skus: BomCostingPreparedSku[],
|
||||
skuIdByExternalId: Map<string, string>,
|
||||
): Prisma.BomCostingLineCreateManyInput[] {
|
||||
return skus.flatMap((sku) => {
|
||||
const skuId = skuIdByExternalId.get(sku.externalSkuId)
|
||||
if (!skuId) {
|
||||
throw new Error(`BOM 核算规格写入失败:未找到规格 ${sku.externalSkuId}`)
|
||||
}
|
||||
|
||||
return sku.bomLines.map((line) => ({
|
||||
skuId,
|
||||
externalLineId: line.externalLineId,
|
||||
category: line.category,
|
||||
partName: line.partName,
|
||||
materialCode: line.materialCode,
|
||||
materialName: line.materialName,
|
||||
materialSpec: line.materialSpec,
|
||||
processName: line.processName,
|
||||
packagingKind: line.packagingKind,
|
||||
lengthMm: line.lengthMm,
|
||||
widthMm: line.widthMm,
|
||||
heightMm: line.heightMm,
|
||||
quantity: line.quantity,
|
||||
unit: line.unit,
|
||||
weightKg: line.weightKg,
|
||||
lossFactor: line.lossFactor,
|
||||
sourceConfidence: line.sourceConfidence,
|
||||
evidence: line.evidence,
|
||||
matchStatus: line.matchStatus,
|
||||
matchedLibraryType: line.matchedLibraryType,
|
||||
matchedLibraryRecordId: line.matchedLibraryRecordId,
|
||||
matchedLibraryName: line.matchedLibraryName,
|
||||
matchedLibrarySpec: line.matchedLibrarySpec,
|
||||
resolvedUnitPrice: line.resolvedUnitPrice,
|
||||
calculatedQuantity: line.calculatedQuantity,
|
||||
subtotal: line.subtotal,
|
||||
sortOrder: line.sortOrder,
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
function buildPriceSnapshotCreateData(
|
||||
skus: BomCostingPreparedSku[],
|
||||
skuIdByExternalId: Map<string, string>,
|
||||
lineIdBySkuAndExternalLineId: Map<string, string>,
|
||||
): Prisma.BomCostingPriceSnapshotCreateManyInput[] {
|
||||
return skus.flatMap((sku) => {
|
||||
const skuId = skuIdByExternalId.get(sku.externalSkuId)
|
||||
if (!skuId) {
|
||||
throw new Error(`BOM 核算价格快照写入失败:未找到规格 ${sku.externalSkuId}`)
|
||||
}
|
||||
|
||||
return sku.bomLines.flatMap((line) => {
|
||||
if (!line.priceSnapshot) return []
|
||||
const lineId = lineIdBySkuAndExternalLineId.get(
|
||||
`${skuId}:${line.externalLineId}`,
|
||||
)
|
||||
if (!lineId) {
|
||||
throw new Error(`BOM 核算价格快照写入失败:未找到明细 ${line.externalLineId}`)
|
||||
}
|
||||
return [{
|
||||
lineId,
|
||||
sourceType: line.priceSnapshot.sourceType,
|
||||
sourceRecordId: line.priceSnapshot.sourceRecordId,
|
||||
sourceName: line.priceSnapshot.sourceName,
|
||||
sourceSpec: line.priceSnapshot.sourceSpec,
|
||||
unitPrice: line.priceSnapshot.unitPrice,
|
||||
unit: line.priceSnapshot.unit,
|
||||
lossFactor: line.priceSnapshot.lossFactor,
|
||||
}]
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function createManyInBatches<T>(
|
||||
values: T[],
|
||||
create: (batch: T[]) => Promise<unknown>,
|
||||
) {
|
||||
for (let index = 0; index < values.length; index += BOM_COSTING_PERSIST_BATCH_SIZE) {
|
||||
await create(values.slice(index, index + BOM_COSTING_PERSIST_BATCH_SIZE))
|
||||
}
|
||||
}
|
||||
|
||||
export class BomCostingRepository {
|
||||
async listCases(input: { createdById?: string; limit: number }) {
|
||||
return prisma.bomCostingCase.findMany({
|
||||
@ -808,6 +855,120 @@ export class BomCostingRepository {
|
||||
return recoveredCaseIds
|
||||
}
|
||||
|
||||
async requeueTransientMultimodalFailure(input: {
|
||||
caseId: string
|
||||
analysisRunId: string
|
||||
message: string
|
||||
maxAutoRecoveries?: number
|
||||
}) {
|
||||
const maxAutoRecoveries = Math.max(1, input.maxAutoRecoveries ?? 3)
|
||||
return prisma.$transaction(async (tx) => {
|
||||
const run = await tx.bomCostingAnalysisRun.findFirst({
|
||||
where: {
|
||||
id: input.analysisRunId,
|
||||
caseId: input.caseId,
|
||||
status: BomCostingAnalysisRunStatus.PROCESSING,
|
||||
case: {
|
||||
is: {
|
||||
status: BomCostingCaseStatus.ANALYZING,
|
||||
deletedAt: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
caseId: true,
|
||||
revision: true,
|
||||
mode: true,
|
||||
case: {
|
||||
select: {
|
||||
providerTaskId: true,
|
||||
progress: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!run) return false
|
||||
|
||||
// Only count recoveries after the most recent successful synthesis batch.
|
||||
// A successful batch proves the provider recovered, so older retries must
|
||||
// not consume the budget for a later, unrelated short-lived timeout.
|
||||
const latestSynthesisCompletion = await tx.bomCostingTaskEvent.findFirst({
|
||||
where: {
|
||||
caseId: input.caseId,
|
||||
eventType: 'MODEL_SYNTHESIS_BATCH_COMPLETED',
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
select: { createdAt: true },
|
||||
})
|
||||
|
||||
// Keep a finite limit for consecutive failures so a persistent provider
|
||||
// outage still cannot make an invisible endless loop.
|
||||
const recoveryCount = await tx.bomCostingTaskEvent.count({
|
||||
where: {
|
||||
caseId: input.caseId,
|
||||
eventType: 'TASK_RECOVERY_QUEUED',
|
||||
...(latestSynthesisCompletion
|
||||
? { createdAt: { gt: latestSynthesisCompletion.createdAt } }
|
||||
: {}),
|
||||
},
|
||||
})
|
||||
if (recoveryCount >= maxAutoRecoveries) return false
|
||||
|
||||
const queued = await tx.bomCostingCase.updateMany({
|
||||
where: {
|
||||
id: input.caseId,
|
||||
status: BomCostingCaseStatus.ANALYZING,
|
||||
deletedAt: null,
|
||||
},
|
||||
data: {
|
||||
status: BomCostingCaseStatus.QUEUED,
|
||||
statusMessage: '模型服务短暂波动,已保留完成进度并自动继续处理',
|
||||
processingStartedAt: null,
|
||||
processingFinishedAt: null,
|
||||
},
|
||||
})
|
||||
if (queued.count !== 1) return false
|
||||
|
||||
const requeuedRun = await tx.bomCostingAnalysisRun.updateMany({
|
||||
where: {
|
||||
id: run.id,
|
||||
status: BomCostingAnalysisRunStatus.PROCESSING,
|
||||
},
|
||||
data: {
|
||||
status: BomCostingAnalysisRunStatus.PENDING,
|
||||
errorMessage: '',
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
},
|
||||
})
|
||||
if (requeuedRun.count !== 1) {
|
||||
throw new Error('BOM 核算运行版本状态已变化')
|
||||
}
|
||||
|
||||
await tx.bomCostingTaskEvent.create({
|
||||
data: {
|
||||
caseId: run.caseId,
|
||||
eventType: 'TASK_RECOVERY_QUEUED',
|
||||
status: BomCostingCaseStatus.QUEUED,
|
||||
progress: run.case.progress,
|
||||
message: '模型服务短暂波动,已保留完成进度并自动继续处理',
|
||||
providerTaskId: run.case.providerTaskId,
|
||||
payload: {
|
||||
runId: run.id,
|
||||
revision: run.revision,
|
||||
mode: run.mode,
|
||||
recoveryReason: 'TRANSIENT_MULTIMODAL_FAILURE',
|
||||
failedMessage: input.message,
|
||||
autoRecoveryAttempt: recoveryCount + 1,
|
||||
maxAutoRecoveries,
|
||||
},
|
||||
},
|
||||
})
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
async recoverStaleSourceSnapshots(input: { staleBefore: Date }) {
|
||||
return prisma.bomCostingSourceSnapshot.updateMany({
|
||||
where: {
|
||||
@ -863,6 +1024,20 @@ export class BomCostingRepository {
|
||||
})
|
||||
}
|
||||
|
||||
async saveAnalysisRunSynthesisCheckpoint(input: {
|
||||
id: string
|
||||
checkpoint: Prisma.InputJsonValue
|
||||
}) {
|
||||
return prisma.bomCostingAnalysisRun.update({
|
||||
where: { id: input.id },
|
||||
data: {
|
||||
status: BomCostingAnalysisRunStatus.PROCESSING,
|
||||
resultSnapshot: input.checkpoint,
|
||||
errorMessage: '',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async createRecalculationRun(input: {
|
||||
caseId: string
|
||||
mode: Exclude<BomCostingAnalysisRunMode, 'INITIAL'>
|
||||
@ -1367,6 +1542,52 @@ export class BomCostingRepository {
|
||||
await tx.bomCostingSku.deleteMany({
|
||||
where: { caseId: input.caseId },
|
||||
})
|
||||
|
||||
const skuRows = buildSkuCreateData(input.caseId, input.skus)
|
||||
await createManyInBatches(skuRows, (data) =>
|
||||
tx.bomCostingSku.createMany({ data }),
|
||||
)
|
||||
const persistedSkus = await tx.bomCostingSku.findMany({
|
||||
where: { caseId: input.caseId },
|
||||
select: {
|
||||
id: true,
|
||||
externalSkuId: true,
|
||||
},
|
||||
})
|
||||
const skuIdByExternalId = new Map(
|
||||
persistedSkus.map((sku) => [sku.externalSkuId, sku.id]),
|
||||
)
|
||||
const lineRows = buildLineCreateData(input.skus, skuIdByExternalId)
|
||||
await createManyInBatches(lineRows, (data) =>
|
||||
tx.bomCostingLine.createMany({ data }),
|
||||
)
|
||||
const persistedLines = await tx.bomCostingLine.findMany({
|
||||
where: {
|
||||
skuId: {
|
||||
in: persistedSkus.map((sku) => sku.id),
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
skuId: true,
|
||||
externalLineId: true,
|
||||
},
|
||||
})
|
||||
const lineIdBySkuAndExternalLineId = new Map(
|
||||
persistedLines.map((line) => [
|
||||
`${line.skuId}:${line.externalLineId}`,
|
||||
line.id,
|
||||
]),
|
||||
)
|
||||
const priceSnapshotRows = buildPriceSnapshotCreateData(
|
||||
input.skus,
|
||||
skuIdByExternalId,
|
||||
lineIdBySkuAndExternalLineId,
|
||||
)
|
||||
await createManyInBatches(priceSnapshotRows, (data) =>
|
||||
tx.bomCostingPriceSnapshot.createMany({ data }),
|
||||
)
|
||||
|
||||
await tx.bomCostingAnalysisRun.update({
|
||||
where: { id: input.analysisRunId },
|
||||
data: {
|
||||
@ -1382,7 +1603,7 @@ export class BomCostingRepository {
|
||||
completedAt: new Date(),
|
||||
},
|
||||
})
|
||||
return tx.bomCostingCase.update({
|
||||
await tx.bomCostingCase.update({
|
||||
where: { id: input.caseId },
|
||||
data: {
|
||||
title: input.title,
|
||||
@ -1391,9 +1612,6 @@ export class BomCostingRepository {
|
||||
statusMessage: `核算完成,共 ${input.skus.length} 个 SKU`,
|
||||
rawAnalysisSnapshot: input.analysis,
|
||||
processingFinishedAt: new Date(),
|
||||
skus: {
|
||||
create: buildSkuCreateData(input.skus),
|
||||
},
|
||||
taskEvents: {
|
||||
create: {
|
||||
eventType: 'RESULT_SAVED',
|
||||
@ -1404,8 +1622,10 @@ export class BomCostingRepository {
|
||||
},
|
||||
},
|
||||
},
|
||||
include: caseDetailInclude,
|
||||
})
|
||||
}, {
|
||||
maxWait: 10_000,
|
||||
timeout: 120_000,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@ -327,12 +327,32 @@ export const aiPositiveNumberSchema = z.preprocess(
|
||||
)
|
||||
|
||||
export const aiOptionalPositiveNumberSchema = z.preprocess(
|
||||
(value) => parseAiFiniteNumber(aiNullToUndefined(value)),
|
||||
(value) => {
|
||||
const parsed = parseAiFiniteNumber(aiNullToUndefined(value))
|
||||
// Optional measurements are frequently returned as 0, null, or a
|
||||
// non-numeric placeholder such as “unknown”. Preserve the strict positive
|
||||
// rule for a real measurement, but treat all of those placeholders as
|
||||
// omitted instead of rejecting an otherwise usable BOM.
|
||||
return typeof parsed === 'number' && parsed > 0 ? parsed : undefined
|
||||
},
|
||||
z.number().finite().positive().optional(),
|
||||
)
|
||||
|
||||
const DEFAULT_AI_CONFIDENCE = 0.5
|
||||
|
||||
function parseAiConfidence(value: unknown) {
|
||||
// Confidence is advisory metadata. Some otherwise complete model responses
|
||||
// omit it, so retain the usable BOM with an explicitly conservative value
|
||||
// instead of discarding and re-running the entire batch.
|
||||
if (value === null || value === undefined) return DEFAULT_AI_CONFIDENCE
|
||||
if (typeof value === 'string' && !value.trim()) {
|
||||
return DEFAULT_AI_CONFIDENCE
|
||||
}
|
||||
return parseAiFiniteNumber(value)
|
||||
}
|
||||
|
||||
export const aiConfidenceSchema = z.preprocess(
|
||||
parseAiFiniteNumber,
|
||||
parseAiConfidence,
|
||||
z.number().finite().min(0).max(1),
|
||||
)
|
||||
|
||||
|
||||
@ -8,6 +8,8 @@ import {
|
||||
import {
|
||||
BomCostingMultimodalAnalyzer,
|
||||
buildBomCostingMultimodalImages,
|
||||
buildSynthesisFactInput,
|
||||
type BomCostingSynthesisCheckpoint,
|
||||
} from './bom-costing-multimodal-analyzer'
|
||||
import type { MarketDetailSnapshot } from './market-detail-client'
|
||||
|
||||
@ -203,21 +205,24 @@ function mockFactExtractionThenAnalysis(
|
||||
inputSnapshot: MarketDetailSnapshot,
|
||||
analysisPayload: unknown,
|
||||
) {
|
||||
const analysisContent = JSON.stringify(analysisPayload)
|
||||
return jest.spyOn(global, 'fetch')
|
||||
.mockResolvedValueOnce(
|
||||
createStreamingResponse(
|
||||
JSON.stringify(createFactBatchPayload(inputSnapshot)),
|
||||
),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
createStreamingResponse(JSON.stringify(analysisPayload)),
|
||||
)
|
||||
.mockImplementation(async () => createStreamingResponse(analysisContent))
|
||||
}
|
||||
|
||||
describe('BOM 多模态分析器', () => {
|
||||
const originalMaxImages = process.env.BOM_COSTING_AI_MAX_IMAGES
|
||||
const originalFactBatchSize = process.env.BOM_COSTING_AI_FACT_BATCH_SIZE
|
||||
const originalAnalysisTimeout = process.env.BOM_COSTING_AI_TIMEOUT_MS
|
||||
const originalSynthesisSkuBatchSize =
|
||||
process.env.BOM_COSTING_SYNTHESIS_SKU_BATCH_SIZE
|
||||
const originalSynthesisBatchConcurrency =
|
||||
process.env.BOM_COSTING_SYNTHESIS_BATCH_CONCURRENCY
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.BOM_COSTING_AI_FACT_BATCH_SIZE = '6'
|
||||
@ -245,6 +250,18 @@ describe('BOM 多模态分析器', () => {
|
||||
} else {
|
||||
process.env.BOM_COSTING_AI_TIMEOUT_MS = originalAnalysisTimeout
|
||||
}
|
||||
if (originalSynthesisSkuBatchSize === undefined) {
|
||||
delete process.env.BOM_COSTING_SYNTHESIS_SKU_BATCH_SIZE
|
||||
} else {
|
||||
process.env.BOM_COSTING_SYNTHESIS_SKU_BATCH_SIZE =
|
||||
originalSynthesisSkuBatchSize
|
||||
}
|
||||
if (originalSynthesisBatchConcurrency === undefined) {
|
||||
delete process.env.BOM_COSTING_SYNTHESIS_BATCH_CONCURRENCY
|
||||
} else {
|
||||
process.env.BOM_COSTING_SYNTHESIS_BATCH_CONCURRENCY =
|
||||
originalSynthesisBatchConcurrency
|
||||
}
|
||||
jest.restoreAllMocks()
|
||||
})
|
||||
|
||||
@ -430,6 +447,9 @@ describe('BOM 多模态分析器', () => {
|
||||
`${JSON.stringify(firstPayload)}\n${JSON.stringify(secondPayload)}`,
|
||||
),
|
||||
)
|
||||
.mockImplementation(async () => createStreamingResponse(
|
||||
`${JSON.stringify(firstPayload)}\n${JSON.stringify(secondPayload)}`,
|
||||
))
|
||||
|
||||
await expect(new BomCostingMultimodalAnalyzer().analyze({
|
||||
sourceUrl: snapshot.detailUrl,
|
||||
@ -502,7 +522,7 @@ describe('BOM 多模态分析器', () => {
|
||||
expect(result.skus.map((sku) => sku.dimensions)).toEqual([{}, {}])
|
||||
})
|
||||
|
||||
it('把模型对可选 BOM 字段返回的 null 规范为空值', async () => {
|
||||
it('把模型对可选 BOM 字段返回的占位内容规范为空值', async () => {
|
||||
const structureGroup = analyzedStructureGroup()
|
||||
const line = structureGroup.bomLines[0]
|
||||
mockFactExtractionThenAnalysis(snapshot, {
|
||||
@ -517,13 +537,15 @@ describe('BOM 多模态分析器', () => {
|
||||
index === 0
|
||||
? {
|
||||
...line,
|
||||
lengthMm: 0,
|
||||
widthMm: '0',
|
||||
materialCode: null,
|
||||
materialSpec: null,
|
||||
processName: null,
|
||||
packagingKind: null,
|
||||
heightMm: null,
|
||||
weightKg: null,
|
||||
suggestedLossFactor: null,
|
||||
weightKg: '未知',
|
||||
suggestedLossFactor: '待确认',
|
||||
evidence: [{
|
||||
sourceUrl: null,
|
||||
imageUrl: null,
|
||||
@ -539,7 +561,11 @@ describe('BOM 多模态分析器', () => {
|
||||
{
|
||||
...analyzedSku('sku-white'),
|
||||
attributes: null,
|
||||
dimensions: null,
|
||||
dimensions: {
|
||||
lengthMm: '未知',
|
||||
widthMm: '待确认',
|
||||
heightMm: 0,
|
||||
},
|
||||
weightKg: null,
|
||||
packaging: null,
|
||||
},
|
||||
@ -568,6 +594,8 @@ describe('BOM 多模态分析器', () => {
|
||||
materialSpec: undefined,
|
||||
processName: undefined,
|
||||
packagingKind: undefined,
|
||||
lengthMm: undefined,
|
||||
widthMm: undefined,
|
||||
heightMm: undefined,
|
||||
weightKg: undefined,
|
||||
estimatedUnitPrice: 21,
|
||||
@ -649,6 +677,34 @@ describe('BOM 多模态分析器', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('模型省略置信度时使用保守默认值,不重跑完整 BOM 批次', async () => {
|
||||
const structureGroup = analyzedStructureGroup()
|
||||
const modelLine = JSON.parse(
|
||||
JSON.stringify(structureGroup.bomLines[0]),
|
||||
) as Record<string, unknown>
|
||||
delete modelLine.confidence
|
||||
const modelEvidence = modelLine.evidence as Array<Record<string, unknown>>
|
||||
delete modelEvidence[0]?.confidence
|
||||
mockFactExtractionThenAnalysis(snapshot, {
|
||||
product: { category: '书桌' },
|
||||
structureGroups: [{
|
||||
...structureGroup,
|
||||
bomLines: [modelLine, ...structureGroup.bomLines.slice(1)],
|
||||
}],
|
||||
skus: [analyzedSku('sku-white'), analyzedSku('sku-black')],
|
||||
})
|
||||
|
||||
const result = await new BomCostingMultimodalAnalyzer().analyze({
|
||||
sourceUrl: snapshot.detailUrl,
|
||||
snapshot,
|
||||
})
|
||||
|
||||
expect(result.skus[0]?.bomLines[0]).toMatchObject({
|
||||
confidence: 0.5,
|
||||
evidence: [{ confidence: 0.5 }],
|
||||
})
|
||||
})
|
||||
|
||||
it('模型返回其他不完整 SKU 信息时不暴露内部校验细节', async () => {
|
||||
mockFactExtractionThenAnalysis(snapshot, {
|
||||
product: { category: '书桌' },
|
||||
@ -679,7 +735,140 @@ describe('BOM 多模态分析器', () => {
|
||||
sourceUrl: snapshot.detailUrl,
|
||||
snapshot,
|
||||
}),
|
||||
).rejects.toThrow('SKU 覆盖不一致,缺少 1 条,多出 0 条')
|
||||
).rejects.toThrow('SKU 覆盖不一致')
|
||||
})
|
||||
|
||||
it('单批结果首次漏掉 SKU 时只重试该批,并接受第二次完整结果', async () => {
|
||||
const existingFactSnapshot = createCompleteFactSnapshot(snapshot)
|
||||
const fetchSpy = jest.spyOn(global, 'fetch')
|
||||
.mockResolvedValueOnce(createStreamingResponse(JSON.stringify({
|
||||
product: { category: '书桌' },
|
||||
structureGroups: [analyzedStructureGroup()],
|
||||
skus: [analyzedSku('sku-white')],
|
||||
})))
|
||||
.mockResolvedValueOnce(createStreamingResponse(JSON.stringify({
|
||||
product: { category: '书桌' },
|
||||
structureGroups: [analyzedStructureGroup()],
|
||||
skus: [analyzedSku('sku-white'), analyzedSku('sku-black')],
|
||||
})))
|
||||
|
||||
const output = await new BomCostingMultimodalAnalyzer().analyzeWithTrace({
|
||||
sourceUrl: snapshot.detailUrl,
|
||||
snapshot,
|
||||
existingFactSnapshot,
|
||||
})
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(2)
|
||||
const retryRequestBody = JSON.parse(
|
||||
String((fetchSpy.mock.calls[1]?.[1] as RequestInit | undefined)?.body),
|
||||
) as { messages?: Array<{ content: string }> }
|
||||
const retryPrompt = JSON.parse(
|
||||
retryRequestBody.messages?.[1]?.content ?? '{}',
|
||||
) as { contractRetryRule?: string }
|
||||
expect(retryPrompt.contractRetryRule).toContain('全部 SKU')
|
||||
expect(output.result.skus.map((sku) => sku.externalSkuId)).toEqual([
|
||||
'sku-white',
|
||||
'sku-black',
|
||||
])
|
||||
})
|
||||
|
||||
it('从已保存的规格检查点继续时跳过已完成批次,不再调用模型', async () => {
|
||||
const structureGroup = analyzedStructureGroup()
|
||||
const checkpoint: BomCostingSynthesisCheckpoint = {
|
||||
kind: 'BOM_COSTING_SYNTHESIS_CHECKPOINT',
|
||||
version: 1,
|
||||
sourceSkuIds: snapshot.skus.map((sku) => sku.externalSkuId),
|
||||
batches: [{
|
||||
batchIndex: 0,
|
||||
skuIds: snapshot.skus.map((sku) => sku.externalSkuId),
|
||||
product: { category: '书桌' },
|
||||
skus: snapshot.skus.map((sku) => ({
|
||||
...analyzedSku(sku.externalSkuId),
|
||||
name: sku.externalSkuId,
|
||||
bomLines: structureGroup.bomLines,
|
||||
})),
|
||||
}],
|
||||
}
|
||||
const fetchSpy = jest.spyOn(global, 'fetch')
|
||||
|
||||
const output = await new BomCostingMultimodalAnalyzer().analyzeWithTrace({
|
||||
sourceUrl: snapshot.detailUrl,
|
||||
snapshot,
|
||||
existingFactSnapshot: createCompleteFactSnapshot(snapshot),
|
||||
synthesisCheckpoint: checkpoint,
|
||||
})
|
||||
|
||||
expect(fetchSpy).not.toHaveBeenCalled()
|
||||
expect(output.result.skus.map((sku) => sku.externalSkuId)).toEqual([
|
||||
'sku-white',
|
||||
'sku-black',
|
||||
])
|
||||
})
|
||||
|
||||
it('同一批首次超时时立即拆成更小批次,不丢失任何 SKU', async () => {
|
||||
const timeoutError = new Error('The operation was aborted due to timeout')
|
||||
timeoutError.name = 'TimeoutError'
|
||||
const fetchSpy = jest.spyOn(global, 'fetch')
|
||||
.mockRejectedValueOnce(timeoutError)
|
||||
.mockResolvedValueOnce(createStreamingResponse(JSON.stringify({
|
||||
product: { category: '书桌' },
|
||||
structureGroups: [analyzedStructureGroup()],
|
||||
skus: [analyzedSku('sku-white')],
|
||||
})))
|
||||
.mockResolvedValueOnce(createStreamingResponse(JSON.stringify({
|
||||
product: { category: '书桌' },
|
||||
structureGroups: [analyzedStructureGroup()],
|
||||
skus: [analyzedSku('sku-black')],
|
||||
})))
|
||||
|
||||
const output = await new BomCostingMultimodalAnalyzer().analyzeWithTrace({
|
||||
sourceUrl: snapshot.detailUrl,
|
||||
snapshot,
|
||||
existingFactSnapshot: createCompleteFactSnapshot(snapshot),
|
||||
})
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(3)
|
||||
expect(output.result.skus.map((sku) => sku.externalSkuId)).toEqual([
|
||||
'sku-white',
|
||||
'sku-black',
|
||||
])
|
||||
expect(new Set(output.result.skus.map((sku) => sku.structureGroupKey)).size)
|
||||
.toBe(2)
|
||||
expect(output.trace.synthesisCallIds).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('连接超时重试后改为拆分,而不是让整条任务失败', async () => {
|
||||
const transportError = new TypeError('socket timed out')
|
||||
Object.assign(transportError, {
|
||||
cause: Object.assign(new Error('connect timed out'), {
|
||||
code: 'ETIMEDOUT',
|
||||
}),
|
||||
})
|
||||
const fetchSpy = jest.spyOn(global, 'fetch')
|
||||
.mockRejectedValueOnce(transportError)
|
||||
.mockRejectedValueOnce(transportError)
|
||||
.mockResolvedValueOnce(createStreamingResponse(JSON.stringify({
|
||||
product: { category: '书桌' },
|
||||
structureGroups: [analyzedStructureGroup()],
|
||||
skus: [analyzedSku('sku-white')],
|
||||
})))
|
||||
.mockResolvedValueOnce(createStreamingResponse(JSON.stringify({
|
||||
product: { category: '书桌' },
|
||||
structureGroups: [analyzedStructureGroup()],
|
||||
skus: [analyzedSku('sku-black')],
|
||||
})))
|
||||
|
||||
const output = await new BomCostingMultimodalAnalyzer().analyzeWithTrace({
|
||||
sourceUrl: snapshot.detailUrl,
|
||||
snapshot,
|
||||
existingFactSnapshot: createCompleteFactSnapshot(snapshot),
|
||||
})
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(4)
|
||||
expect(output.result.skus.map((sku) => sku.externalSkuId)).toEqual([
|
||||
'sku-white',
|
||||
'sku-black',
|
||||
])
|
||||
})
|
||||
|
||||
it('已有完整逐图事实时只执行最终合成,不再次发送图片', async () => {
|
||||
@ -711,7 +900,7 @@ describe('BOM 多模态分析器', () => {
|
||||
),
|
||||
).toBe(false)
|
||||
expect(requestBody).toMatchObject({
|
||||
reasoning_effort: 'low',
|
||||
reasoning_effort: 'minimal',
|
||||
max_tokens: 12_000,
|
||||
})
|
||||
expect(output.trace).toMatchObject({
|
||||
@ -722,10 +911,81 @@ describe('BOM 多模态分析器', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('将高规格商品拆成多个汇总批次,并覆盖每一个平台 SKU', async () => {
|
||||
process.env.BOM_COSTING_SYNTHESIS_SKU_BATCH_SIZE = '8'
|
||||
process.env.BOM_COSTING_SYNTHESIS_BATCH_CONCURRENCY = '3'
|
||||
const highCardinalitySnapshot: MarketDetailSnapshot = {
|
||||
...snapshot,
|
||||
skuTotalRows: 552,
|
||||
skuReturnedRows: 552,
|
||||
skuTruncated: false,
|
||||
skus: Array.from({ length: 552 }, (_, index) => ({
|
||||
...snapshot.skus[0],
|
||||
externalSkuId: `sku-${index + 1}`,
|
||||
name: `规格 ${index + 1}`,
|
||||
})),
|
||||
}
|
||||
const batchSizes: number[] = []
|
||||
let activeRequestCount = 0
|
||||
let peakConcurrentRequestCount = 0
|
||||
const fetchSpy = jest.spyOn(global, 'fetch').mockImplementation(
|
||||
async (_input, init) => {
|
||||
activeRequestCount += 1
|
||||
peakConcurrentRequestCount = Math.max(
|
||||
peakConcurrentRequestCount,
|
||||
activeRequestCount,
|
||||
)
|
||||
const requestBody = JSON.parse(String((init as RequestInit).body)) as {
|
||||
messages?: Array<{ content: string }>
|
||||
}
|
||||
const prompt = JSON.parse(
|
||||
requestBody.messages?.[1]?.content ?? '{}',
|
||||
) as {
|
||||
skuTruth?: Array<{ externalSkuId: string }>
|
||||
}
|
||||
const skuTruth = prompt.skuTruth ?? []
|
||||
batchSizes.push(skuTruth.length)
|
||||
try {
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 5))
|
||||
return createStreamingResponse(JSON.stringify({
|
||||
product: { category: '书桌' },
|
||||
structureGroups: [analyzedStructureGroup()],
|
||||
skus: skuTruth.map((sku) => analyzedSku(sku.externalSkuId)),
|
||||
}))
|
||||
} finally {
|
||||
activeRequestCount -= 1
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
const output = await new BomCostingMultimodalAnalyzer().analyzeWithTrace({
|
||||
sourceUrl: highCardinalitySnapshot.detailUrl,
|
||||
snapshot: highCardinalitySnapshot,
|
||||
existingFactSnapshot: createCompleteFactSnapshot(highCardinalitySnapshot),
|
||||
})
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(69)
|
||||
expect(batchSizes).toEqual(Array.from({ length: 69 }, () => 8))
|
||||
expect(peakConcurrentRequestCount).toBe(3)
|
||||
expect(output.result.skus).toHaveLength(552)
|
||||
expect(new Set(output.result.skus.map((sku) => sku.externalSkuId)).size).toBe(552)
|
||||
expect(output.result.skus[0]?.structureGroupKey).toBe('batch-1-desk-120')
|
||||
expect(output.result.skus[8]?.structureGroupKey).toBe('batch-2-desk-120')
|
||||
expect(output.result.skus[551]?.structureGroupKey).toBe('batch-69-desk-120')
|
||||
expect(output.trace).toMatchObject({
|
||||
inputSkuCount: 552,
|
||||
synthesisBatchCount: 69,
|
||||
})
|
||||
})
|
||||
|
||||
it('最终汇总紧凑传递逐图事实,不丢失可核验的证据内容', async () => {
|
||||
const factSnapshot = createCompleteFactSnapshot(snapshot)
|
||||
const image = factSnapshot.imageFacts[0]!
|
||||
image.observedTexts = ['桌面标注:120 × 60 cm']
|
||||
image.observedTexts = [
|
||||
'桌面标注:120 × 60 cm',
|
||||
'重复 OCR 片段一',
|
||||
'重复 OCR 片段二',
|
||||
]
|
||||
image.facts = [{
|
||||
factId: 'storage-only-fact-id',
|
||||
kind: 'DIMENSION',
|
||||
@ -738,15 +998,22 @@ describe('BOM 多模态分析器', () => {
|
||||
note: '图片尺寸标注',
|
||||
confidence: 0.9,
|
||||
}]
|
||||
const factlessImage = factSnapshot.imageFacts[3]!
|
||||
factlessImage.observedTexts = ['未提取成事实的文字一', '文字二']
|
||||
const modelStructureGroup = analyzedStructureGroup()
|
||||
modelStructureGroup.bomLines[0]!.evidence = [{
|
||||
imageUrl: `bom-image:${image.imageId}`,
|
||||
confidence: 0.8,
|
||||
}]
|
||||
const fetchSpy = jest.spyOn(global, 'fetch').mockResolvedValue(
|
||||
createStreamingResponse(JSON.stringify({
|
||||
product: { category: '书桌' },
|
||||
structureGroups: [analyzedStructureGroup()],
|
||||
structureGroups: [modelStructureGroup],
|
||||
skus: [analyzedSku('sku-white'), analyzedSku('sku-black')],
|
||||
})),
|
||||
)
|
||||
|
||||
await new BomCostingMultimodalAnalyzer().analyzeWithTrace({
|
||||
const output = await new BomCostingMultimodalAnalyzer().analyzeWithTrace({
|
||||
sourceUrl: snapshot.detailUrl,
|
||||
snapshot,
|
||||
existingFactSnapshot: factSnapshot,
|
||||
@ -768,7 +1035,7 @@ describe('BOM 多模态分析器', () => {
|
||||
|
||||
expect(compactImage).toEqual(expect.objectContaining({
|
||||
id: image.imageId,
|
||||
url: image.sourceImageUrl,
|
||||
url: `bom-image:${image.imageId}`,
|
||||
kind: image.kind,
|
||||
skuCount: image.externalSkuIds.length,
|
||||
texts: ['桌面标注:120 × 60 cm'],
|
||||
@ -788,6 +1055,96 @@ describe('BOM 多模态分析器', () => {
|
||||
})
|
||||
expect(compactFact?.[0]).not.toHaveProperty('factId')
|
||||
expect(promptPayload.installationKnowledge).not.toHaveProperty('usagePolicy')
|
||||
const compactFactlessImage = promptPayload.extractedImageFacts?.images
|
||||
?.find((entry) => entry.id === factlessImage.imageId)
|
||||
expect(compactFactlessImage).toEqual(expect.objectContaining({
|
||||
texts: ['未提取成事实的文字一', '文字二'],
|
||||
}))
|
||||
expect(output.result.skus[0]?.bomLines[0]?.evidence[0]?.imageUrl).toBe(
|
||||
image.sourceImageUrl,
|
||||
)
|
||||
})
|
||||
|
||||
it('最终汇总只传当前批次关联的 SKU 图片,保留产品级事实', () => {
|
||||
const factSnapshot = createCompleteFactSnapshot(snapshot)
|
||||
factSnapshot.imageFacts.push({
|
||||
imageId: 'SKU_9999',
|
||||
sourceImageUrl: 'https://img.example.com/other.jpg',
|
||||
kind: 'SKU',
|
||||
label: '其他规格图',
|
||||
externalSkuIds: ['sku-other'],
|
||||
observedTexts: ['不属于当前批次的规格说明'],
|
||||
facts: [],
|
||||
})
|
||||
|
||||
const compactInput = buildSynthesisFactInput(
|
||||
factSnapshot,
|
||||
[snapshot.skus[0]!],
|
||||
)
|
||||
const images = compactInput.images as Array<{
|
||||
id: string
|
||||
skus?: string[]
|
||||
}>
|
||||
|
||||
const [mainImage, whiteSkuImage, , detailImage] = factSnapshot.imageFacts
|
||||
expect(images.map((image) => image.id)).toEqual([
|
||||
mainImage?.imageId,
|
||||
whiteSkuImage?.imageId,
|
||||
detailImage?.imageId,
|
||||
])
|
||||
expect(images.find((image) => image.id === whiteSkuImage?.imageId)?.skus).toEqual([
|
||||
'sku-white',
|
||||
])
|
||||
expect(JSON.stringify(compactInput)).not.toContain('sku-other')
|
||||
expect(JSON.stringify(compactInput)).not.toContain('不属于当前批次')
|
||||
})
|
||||
|
||||
it('高密度详情事实只保留最有成本价值的一组产品级证据', () => {
|
||||
const factSnapshot = createCompleteFactSnapshot(snapshot)
|
||||
const factKinds = [
|
||||
'DIMENSION',
|
||||
'MATERIAL',
|
||||
'STRUCTURE',
|
||||
'MECHANISM',
|
||||
'HARDWARE',
|
||||
'PART',
|
||||
'PROCESS',
|
||||
'PACKAGING',
|
||||
'WEIGHT',
|
||||
'SKU_DIFFERENCE',
|
||||
'TEXT',
|
||||
] as const
|
||||
factSnapshot.imageFacts.push(...Array.from({ length: 18 }, (_, index) => ({
|
||||
imageId: `DETAIL_DENSE_${index + 1}`,
|
||||
sourceImageUrl: `https://img.example.com/detail-dense-${index + 1}.jpg`,
|
||||
kind: 'DETAIL' as const,
|
||||
label: `高密度详情图 ${index + 1}`,
|
||||
externalSkuIds: [],
|
||||
observedTexts: [],
|
||||
facts: [{
|
||||
factId: `fact_dense_${index + 1}`,
|
||||
kind: factKinds[index % factKinds.length]!,
|
||||
subject: `部件 ${index + 1}`,
|
||||
value: `事实 ${index + 1}`,
|
||||
relatedSkuIds: [],
|
||||
basis: 'IMAGE' as const,
|
||||
confidence: 0.8,
|
||||
}],
|
||||
})))
|
||||
|
||||
const compactInput = buildSynthesisFactInput(
|
||||
factSnapshot,
|
||||
[snapshot.skus[0]!],
|
||||
)
|
||||
const detailImages = compactInput.images.filter(
|
||||
(image) => image.kind === 'DETAIL',
|
||||
)
|
||||
const retainedKinds = new Set(
|
||||
detailImages.flatMap((image) => image.facts.map((fact) => fact.k)),
|
||||
)
|
||||
|
||||
expect(detailImages).toHaveLength(14)
|
||||
expect([...factKinds].every((kind) => retainedKinds.has(kind))).toBe(true)
|
||||
})
|
||||
|
||||
it('复用图片事实时,GPT-5 最终汇总在网关截断前结束等待', async () => {
|
||||
@ -809,6 +1166,10 @@ describe('BOM 多模态分析器', () => {
|
||||
})
|
||||
|
||||
expect(timeoutSpy).toHaveBeenCalledWith(110_000)
|
||||
const requestBody = JSON.parse(
|
||||
String((global.fetch as jest.Mock).mock.calls[0]?.[1]?.body),
|
||||
) as { reasoning_effort?: string }
|
||||
expect(requestBody.reasoning_effort).toBe('minimal')
|
||||
})
|
||||
|
||||
it('最终汇总流在超时时保留可继续任务的提示', async () => {
|
||||
@ -829,7 +1190,7 @@ describe('BOM 多模态分析器', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('最终汇总遇到瞬时网络超时时自动重试一次', async () => {
|
||||
it('最终汇总遇到网络超时时立即拆分,不重试整批', async () => {
|
||||
const transportError = new TypeError('socket timed out')
|
||||
Object.assign(transportError, {
|
||||
cause: Object.assign(new Error('connect timed out'), {
|
||||
@ -842,7 +1203,14 @@ describe('BOM 多模态分析器', () => {
|
||||
createStreamingResponse(JSON.stringify({
|
||||
product: { category: '书桌' },
|
||||
structureGroups: [analyzedStructureGroup()],
|
||||
skus: [analyzedSku('sku-white'), analyzedSku('sku-black')],
|
||||
skus: [analyzedSku('sku-white')],
|
||||
})),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
createStreamingResponse(JSON.stringify({
|
||||
product: { category: '书桌' },
|
||||
structureGroups: [analyzedStructureGroup()],
|
||||
skus: [analyzedSku('sku-black')],
|
||||
})),
|
||||
)
|
||||
|
||||
@ -852,7 +1220,7 @@ describe('BOM 多模态分析器', () => {
|
||||
existingFactSnapshot: createCompleteFactSnapshot(snapshot),
|
||||
})
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(2)
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(3)
|
||||
expect(output.result.skus).toHaveLength(2)
|
||||
})
|
||||
|
||||
@ -872,10 +1240,10 @@ describe('BOM 多模态分析器', () => {
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('组合型 SKU 超过契约上限时说明选项结构并在付费模型前停止', async () => {
|
||||
it('组合型 SKU 超过 600 条上限时说明选项结构并在付费模型前停止', async () => {
|
||||
const fetchSpy = jest.spyOn(global, 'fetch')
|
||||
const styleCount = 24
|
||||
const sizeCount = 23
|
||||
const sizeCount = 26
|
||||
const highCardinalitySnapshot: MarketDetailSnapshot = {
|
||||
...snapshot,
|
||||
skuTotalRows: styleCount * sizeCount,
|
||||
@ -904,7 +1272,7 @@ describe('BOM 多模态分析器', () => {
|
||||
snapshot: highCardinalitySnapshot,
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
'该商品返回 552 个可购买组合(颜色分类 24 种 × 尺寸 23 种),不是 552 个独立款式。当前版本尚未支持这类组合型 SKU 的按需核算,系统未调用多模态模型',
|
||||
'该商品返回 624 个可购买组合(颜色分类 24 种 × 尺寸 26 种),不是 624 个独立款式。当前版本尚未支持这类组合型 SKU 的按需核算,系统未调用多模态模型',
|
||||
)
|
||||
expect(fetchSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,96 @@
|
||||
/** @jest-environment node */
|
||||
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import {
|
||||
callBomCostingMultimodalModel,
|
||||
isBomCostingMultimodalTransientError,
|
||||
} from './bom-costing-multimodal-gateway'
|
||||
|
||||
describe('BOM 多模态网关', () => {
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('流式响应空转超过时限时取消读取并返回可恢复的超时错误', async () => {
|
||||
let cancelReason: unknown
|
||||
const stalledStream = new ReadableStream({
|
||||
cancel(reason) {
|
||||
cancelReason = reason
|
||||
},
|
||||
})
|
||||
const fetchSpy = jest.spyOn(global, 'fetch').mockResolvedValue(
|
||||
new Response(stalledStream, {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'text/event-stream' },
|
||||
}),
|
||||
)
|
||||
|
||||
await expect(
|
||||
callBomCostingMultimodalModel({
|
||||
config: {
|
||||
baseUrl: 'https://ai.example.com/v1',
|
||||
apiKey: 'test-key',
|
||||
model: 'gpt-5.6-luna',
|
||||
},
|
||||
operation: 'SYNTHESIS',
|
||||
systemPrompt: 'test',
|
||||
userContent: 'test',
|
||||
maxTokens: 100,
|
||||
timeoutMs: 25,
|
||||
}),
|
||||
).rejects.toThrow('多模态 BOM 分析超时')
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
||||
expect((cancelReason as Error | undefined)?.name).toBe('TimeoutError')
|
||||
})
|
||||
|
||||
it('规格汇总遇到网络超时时立即交由上层拆分,不白白重试整批', async () => {
|
||||
const networkTimeout = Object.assign(
|
||||
new Error('socket timed out'),
|
||||
{ code: 'ETIMEDOUT' },
|
||||
)
|
||||
const fetchSpy = jest.spyOn(global, 'fetch').mockRejectedValue(
|
||||
networkTimeout,
|
||||
)
|
||||
|
||||
await expect(
|
||||
callBomCostingMultimodalModel({
|
||||
config: {
|
||||
baseUrl: 'https://ai.example.com/v1',
|
||||
apiKey: 'test-key',
|
||||
model: 'gpt-5.6-luna',
|
||||
},
|
||||
operation: 'SYNTHESIS',
|
||||
systemPrompt: 'test',
|
||||
userContent: 'test',
|
||||
maxTokens: 100,
|
||||
timeoutMs: 25,
|
||||
}),
|
||||
).rejects.toThrow('多模态 BOM 分析超时')
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('把短暂的模型连接故障标为可自动续跑,保留配置或结构错误的失败提示', () => {
|
||||
expect(isBomCostingMultimodalTransientError(new AppError(
|
||||
ErrorCode.BOM_COSTING_INVALID_PROVIDER,
|
||||
'多模态分析服务暂时无法连接',
|
||||
))).toBe(true)
|
||||
expect(isBomCostingMultimodalTransientError(new AppError(
|
||||
ErrorCode.BOM_COSTING_INVALID_PROVIDER,
|
||||
'多模态分析服务没有返回可读取的结果',
|
||||
))).toBe(true)
|
||||
expect(isBomCostingMultimodalTransientError(new AppError(
|
||||
ErrorCode.BOM_COSTING_INVALID_PROVIDER,
|
||||
'多模态分析服务返回 400',
|
||||
))).toBe(true)
|
||||
expect(isBomCostingMultimodalTransientError(new AppError(
|
||||
ErrorCode.BOM_COSTING_INVALID_PROVIDER,
|
||||
'多模态分析返回的 SKU 信息不完整,请重新处理',
|
||||
))).toBe(true)
|
||||
expect(isBomCostingMultimodalTransientError(new AppError(
|
||||
ErrorCode.BOM_COSTING_INVALID_PROVIDER,
|
||||
'多模态分析服务鉴权失败,请联系管理员检查模型配置',
|
||||
))).toBe(false)
|
||||
})
|
||||
})
|
||||
@ -68,7 +68,10 @@ function getAiServiceType() {
|
||||
return process.env.BOM_COSTING_AI_SERVICE_TYPE?.trim() || 'prompt-optimizer'
|
||||
}
|
||||
|
||||
function getBomCostingReasoningEffort(model: string) {
|
||||
function getBomCostingReasoningEffort(
|
||||
model: string,
|
||||
operation: BomCostingMultimodalOperation,
|
||||
) {
|
||||
const configured = process.env.BOM_COSTING_AI_REASONING_EFFORT
|
||||
?.trim()
|
||||
.toLowerCase()
|
||||
@ -76,10 +79,13 @@ function getBomCostingReasoningEffort(model: string) {
|
||||
return configured
|
||||
}
|
||||
|
||||
// The configured GPT-5-compatible gateway terminates long, non-streaming
|
||||
// reasoning around two minutes. BOM synthesis is structured extraction, not
|
||||
// an open-ended reasoning task, so keep the default response bounded.
|
||||
return /^gpt-5(?:[.-]|$)/i.test(model) ? 'low' : undefined
|
||||
if (!/^gpt-5(?:[.-]|$)/i.test(model)) return undefined
|
||||
|
||||
// Image facts need a modest amount of visual judgement. The final synthesis
|
||||
// is different: it turns facts already saved by the system into a strict JSON
|
||||
// table. Asking GPT-5 to reason at the same depth there can spend the entire
|
||||
// gateway window before it emits a single streaming token.
|
||||
return operation === 'SYNTHESIS' ? 'minimal' : 'low'
|
||||
}
|
||||
|
||||
export async function getBomCostingMultimodalProviderConfig():
|
||||
@ -204,7 +210,10 @@ function readUpstreamRequestId(headers: Headers): string | null {
|
||||
return null
|
||||
}
|
||||
|
||||
async function readStreamingChatCompletion(response: Response) {
|
||||
async function readStreamingChatCompletion(
|
||||
response: Response,
|
||||
options: { signal?: AbortSignal } = {},
|
||||
) {
|
||||
if (!response.body) {
|
||||
throw new AppError(
|
||||
ErrorCode.BOM_COSTING_INVALID_PROVIDER,
|
||||
@ -213,6 +222,22 @@ async function readStreamingChatCompletion(response: Response) {
|
||||
}
|
||||
|
||||
const reader = response.body.getReader()
|
||||
const { signal } = options
|
||||
const throwIfAborted = () => {
|
||||
if (!signal?.aborted) return
|
||||
throw signal.reason ?? new DOMException('The operation was aborted', 'AbortError')
|
||||
}
|
||||
const cancelReaderOnAbort = () => {
|
||||
// A fetch signal reliably limits the initial HTTP response, but some
|
||||
// upstreams can leave an already-open SSE stream idle forever. Cancel the
|
||||
// reader too so a pending reader.read() wakes up and the request reaches
|
||||
// the same timeout path instead of permanently occupying a worker slot.
|
||||
void reader.cancel(signal?.reason).catch(() => undefined)
|
||||
}
|
||||
|
||||
throwIfAborted()
|
||||
signal?.addEventListener('abort', cancelReaderOnAbort, { once: true })
|
||||
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ''
|
||||
let content = ''
|
||||
@ -268,6 +293,7 @@ async function readStreamingChatCompletion(response: Response) {
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
throwIfAborted()
|
||||
if (done) break
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const lines = buffer.split(/\r?\n/)
|
||||
@ -279,6 +305,7 @@ async function readStreamingChatCompletion(response: Response) {
|
||||
buffer.split(/\r?\n/).forEach(consumeLine)
|
||||
}
|
||||
} finally {
|
||||
signal?.removeEventListener('abort', cancelReaderOnAbort)
|
||||
reader.releaseLock()
|
||||
}
|
||||
|
||||
@ -295,25 +322,74 @@ async function readStreamingChatCompletion(response: Response) {
|
||||
function readTransportErrorCode(error: unknown): string | null {
|
||||
let current = error
|
||||
for (let depth = 0; depth < 4; depth += 1) {
|
||||
if (!(current instanceof Error)) return null
|
||||
const code = (current as Error & { code?: unknown }).code
|
||||
if (typeof current !== 'object' || current === null) return null
|
||||
const code = (current as { code?: unknown }).code
|
||||
if (typeof code === 'string' && code.trim()) return code.trim()
|
||||
current = (current as Error & { cause?: unknown }).cause
|
||||
current = (current as { cause?: unknown }).cause
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function readErrorName(error: unknown): string | null {
|
||||
if (typeof error !== 'object' || error === null) return null
|
||||
const name = (error as { name?: unknown }).name
|
||||
return typeof name === 'string' && name.trim() ? name.trim() : null
|
||||
}
|
||||
|
||||
function isDirectMultimodalTimeoutError(error: unknown) {
|
||||
return readErrorName(error) === 'TimeoutError'
|
||||
}
|
||||
|
||||
function isMultimodalTimeoutFailure(error: unknown) {
|
||||
const code = readTransportErrorCode(error)
|
||||
return (
|
||||
isDirectMultimodalTimeoutError(error) ||
|
||||
code === 'ETIMEDOUT' ||
|
||||
code === 'UND_ERR_CONNECT_TIMEOUT'
|
||||
)
|
||||
}
|
||||
|
||||
function describeMultimodalTransportFailure(error: unknown) {
|
||||
return error instanceof Error && error.name === 'TimeoutError'
|
||||
return isMultimodalTimeoutFailure(error)
|
||||
? '多模态 BOM 分析超时;已完成的图片事实不会重复分析,可稍后继续任务'
|
||||
: '多模态分析服务暂时无法连接'
|
||||
}
|
||||
|
||||
function isRetriableMultimodalTransportFailure(error: unknown) {
|
||||
const code = readTransportErrorCode(error)
|
||||
return (
|
||||
(error instanceof Error && error.name === 'TimeoutError') ||
|
||||
return isMultimodalTimeoutFailure(error) ||
|
||||
(code !== null && BOM_COSTING_RETRYABLE_TRANSPORT_CODES.has(code))
|
||||
}
|
||||
|
||||
export function isBomCostingMultimodalTimeoutError(error: unknown) {
|
||||
return (
|
||||
error instanceof AppError &&
|
||||
error.code === ErrorCode.BOM_COSTING_INVALID_PROVIDER &&
|
||||
(
|
||||
error.message.startsWith('多模态 BOM 分析超时') ||
|
||||
error.message.startsWith('多模态分析服务处理超时')
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
// A completed image-fact snapshot and synthesis checkpoint are both durable.
|
||||
// A short-lived gateway outage or an occasional malformed model answer should
|
||||
// therefore requeue the same run rather than showing the user a terminal
|
||||
// failure that they have to resume manually.
|
||||
export function isBomCostingMultimodalTransientError(error: unknown) {
|
||||
return (
|
||||
error instanceof AppError &&
|
||||
error.code === ErrorCode.BOM_COSTING_INVALID_PROVIDER &&
|
||||
(
|
||||
error.message.startsWith('多模态 BOM 分析超时') ||
|
||||
error.message.startsWith('多模态分析服务处理超时') ||
|
||||
error.message.startsWith('多模态分析服务暂时无法连接') ||
|
||||
error.message.startsWith('多模态分析服务没有返回可读取的结果') ||
|
||||
error.message.startsWith('多模态分析服务未返回可读取的结果流') ||
|
||||
error.message.startsWith('多模态分析服务返回 400') ||
|
||||
error.message.startsWith('多模态分析返回的 SKU 信息不完整') ||
|
||||
error.message.startsWith('多模态分析返回的产品结构信息不完整')
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@ -330,9 +406,13 @@ export async function callBomCostingMultimodalModel(input: {
|
||||
userContent: BomCostingMultimodalUserContent
|
||||
maxTokens: number
|
||||
timeoutMs: number
|
||||
retrySynthesisTimeout?: boolean
|
||||
}): Promise<BomCostingMultimodalCallResult> {
|
||||
const endpoint = `${input.config.baseUrl.replace(/\/+$/, '')}/chat/completions`
|
||||
const reasoningEffort = getBomCostingReasoningEffort(input.config.model)
|
||||
const reasoningEffort = getBomCostingReasoningEffort(
|
||||
input.config.model,
|
||||
input.operation,
|
||||
)
|
||||
const startedAt = Date.now()
|
||||
const maxAttempts =
|
||||
input.operation === 'SYNTHESIS'
|
||||
@ -341,6 +421,7 @@ export async function callBomCostingMultimodalModel(input: {
|
||||
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
||||
let response: Response
|
||||
const timeoutSignal = AbortSignal.timeout(input.timeoutMs)
|
||||
try {
|
||||
response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
@ -361,7 +442,7 @@ export async function callBomCostingMultimodalModel(input: {
|
||||
...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),
|
||||
}),
|
||||
cache: 'no-store',
|
||||
signal: AbortSignal.timeout(input.timeoutMs),
|
||||
signal: timeoutSignal,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('[BOM costing] multimodal request failed', {
|
||||
@ -369,12 +450,17 @@ export async function callBomCostingMultimodalModel(input: {
|
||||
model: input.config.model,
|
||||
attempt,
|
||||
durationMs: Date.now() - startedAt,
|
||||
errorName: error instanceof Error ? error.name : 'UnknownError',
|
||||
errorName: readErrorName(error) ?? 'UnknownError',
|
||||
errorCode: readTransportErrorCode(error),
|
||||
})
|
||||
if (
|
||||
attempt < maxAttempts &&
|
||||
isRetriableMultimodalTransportFailure(error)
|
||||
isRetriableMultimodalTransportFailure(error) &&
|
||||
!(
|
||||
input.operation === 'SYNTHESIS' &&
|
||||
!input.retrySynthesisTimeout &&
|
||||
isMultimodalTimeoutFailure(error)
|
||||
)
|
||||
) {
|
||||
console.warn('[BOM costing] retrying transient multimodal request', {
|
||||
operation: input.operation,
|
||||
@ -423,19 +509,26 @@ export async function callBomCostingMultimodalModel(input: {
|
||||
|
||||
let result: Awaited<ReturnType<typeof readStreamingChatCompletion>>
|
||||
try {
|
||||
result = await readStreamingChatCompletion(response)
|
||||
result = await readStreamingChatCompletion(response, {
|
||||
signal: timeoutSignal,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('[BOM costing] multimodal response stream failed', {
|
||||
operation: input.operation,
|
||||
model: input.config.model,
|
||||
attempt,
|
||||
durationMs: Date.now() - startedAt,
|
||||
errorName: error instanceof Error ? error.name : 'UnknownError',
|
||||
errorName: readErrorName(error) ?? 'UnknownError',
|
||||
errorCode: readTransportErrorCode(error),
|
||||
})
|
||||
if (
|
||||
attempt < maxAttempts &&
|
||||
isRetriableMultimodalTransportFailure(error)
|
||||
isRetriableMultimodalTransportFailure(error) &&
|
||||
!(
|
||||
input.operation === 'SYNTHESIS' &&
|
||||
!input.retrySynthesisTimeout &&
|
||||
isMultimodalTimeoutFailure(error)
|
||||
)
|
||||
) {
|
||||
console.warn('[BOM costing] retrying transient multimodal request', {
|
||||
operation: input.operation,
|
||||
|
||||
@ -8,6 +8,7 @@ import {
|
||||
BomCostingSourceAssetStatus,
|
||||
BomCostingSourceStatus,
|
||||
} from '@prisma/client'
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import {
|
||||
BOM_COSTING_FACT_ANALYSIS_STATUS,
|
||||
BOM_COSTING_FACT_SCHEMA_VERSION,
|
||||
@ -19,6 +20,8 @@ import { marketDetailClient, type MarketDetailSnapshot } from './market-detail-c
|
||||
const mockRunAnalysis = jest.fn()
|
||||
const mockBuildStoredSnapshot = jest.fn()
|
||||
const mockRefreshSourceMetadata = jest.fn()
|
||||
const mockArchive = jest.fn()
|
||||
const mockSourceImagesChangedError = class extends Error {}
|
||||
|
||||
jest.mock('@/lib/storage', () => ({
|
||||
readObjectStorageKeyFromUrl: (value: string) => {
|
||||
@ -57,9 +60,10 @@ jest.mock('./bom-costing-source-archive.service', () => ({
|
||||
buildMarketSnapshotFromStoredSource: (...args: unknown[]) =>
|
||||
mockBuildStoredSnapshot(...args),
|
||||
bomCostingSourceArchiveService: {
|
||||
archive: jest.fn(),
|
||||
archive: (...args: unknown[]) => mockArchive(...args),
|
||||
refreshMetadata: (...args: unknown[]) => mockRefreshSourceMetadata(...args),
|
||||
},
|
||||
BomCostingSourceImagesChangedError: mockSourceImagesChangedError,
|
||||
}))
|
||||
|
||||
const snapshot: MarketDetailSnapshot = {
|
||||
@ -297,6 +301,8 @@ function caseRecord() {
|
||||
describe('BomCostingProcessingService', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
mockArchive.mockReset()
|
||||
mockRefreshSourceMetadata.mockReset()
|
||||
jest.spyOn(bomCostingRepository, 'claimCaseForProcessing').mockResolvedValue(true)
|
||||
jest.spyOn(bomCostingRepository, 'findProcessingAnalysisRun')
|
||||
.mockResolvedValue({
|
||||
@ -318,6 +324,8 @@ describe('BomCostingProcessingService', () => {
|
||||
.mockResolvedValue(factAnalysisRecord() as never)
|
||||
jest.spyOn(bomCostingRepository, 'linkAnalysisRunFact')
|
||||
.mockResolvedValue({} as never)
|
||||
jest.spyOn(bomCostingRepository, 'saveAnalysisRunSynthesisCheckpoint')
|
||||
.mockResolvedValue({} as never)
|
||||
jest.spyOn(bomCostingRepository, 'claimSourceFactAnalysis')
|
||||
.mockResolvedValue(true)
|
||||
jest.spyOn(bomCostingRepository, 'saveSourceFactAnalysisBatch')
|
||||
@ -336,6 +344,8 @@ describe('BomCostingProcessingService', () => {
|
||||
})
|
||||
jest.spyOn(bomCostingRepository, 'completeCase').mockResolvedValue({} as never)
|
||||
jest.spyOn(bomCostingRepository, 'failCase').mockResolvedValue(undefined)
|
||||
jest.spyOn(bomCostingRepository, 'requeueTransientMultimodalFailure')
|
||||
.mockResolvedValue(false)
|
||||
jest.spyOn(bomCostingRepository, 'failSourceSnapshot').mockResolvedValue({} as never)
|
||||
mockBuildStoredSnapshot.mockResolvedValue(snapshot)
|
||||
})
|
||||
@ -351,6 +361,7 @@ describe('BomCostingProcessingService', () => {
|
||||
onFactBatchStarted?: (progress: unknown) => Promise<void>
|
||||
onFactBatchCompleted?: (progress: unknown) => Promise<void>
|
||||
onFactExtractionCompleted?: (result: unknown) => Promise<void>
|
||||
onSynthesisBatchCompleted?: (progress: unknown) => Promise<void>
|
||||
}
|
||||
const batchImages = [{
|
||||
imageId: 'IMG_0001',
|
||||
@ -401,6 +412,28 @@ describe('BomCostingProcessingService', () => {
|
||||
completionTokens: 80,
|
||||
},
|
||||
})
|
||||
await analysisInput.onSynthesisBatchCompleted?.({
|
||||
batchIndex: 1,
|
||||
totalBatches: 1,
|
||||
batchSkuCount: 1,
|
||||
completedSkuCount: 1,
|
||||
model: 'grok-4.5',
|
||||
callId: 'synthesis-call-1',
|
||||
durationMs: 22_000,
|
||||
promptTokens: 40,
|
||||
completionTokens: 120,
|
||||
synthesisCheckpoint: {
|
||||
kind: 'BOM_COSTING_SYNTHESIS_CHECKPOINT',
|
||||
version: 1,
|
||||
sourceSkuIds: ['sku-1'],
|
||||
batches: [{
|
||||
batchIndex: 0,
|
||||
skuIds: ['sku-1'],
|
||||
product: { category: '书桌' },
|
||||
skus: analysisResult.skus,
|
||||
}],
|
||||
},
|
||||
})
|
||||
return {
|
||||
result: analysisResult,
|
||||
trace: {
|
||||
@ -444,6 +477,17 @@ describe('BomCostingProcessingService', () => {
|
||||
totalImageCount: 2,
|
||||
}),
|
||||
)
|
||||
expect(
|
||||
bomCostingRepository.saveAnalysisRunSynthesisCheckpoint,
|
||||
).toHaveBeenCalledWith(expect.objectContaining({
|
||||
id: 'analysis-run-1',
|
||||
checkpoint: expect.objectContaining({
|
||||
kind: 'BOM_COSTING_SYNTHESIS_CHECKPOINT',
|
||||
batches: expect.arrayContaining([
|
||||
expect.objectContaining({ batchIndex: 0 }),
|
||||
]),
|
||||
}),
|
||||
}))
|
||||
expect(bomCostingRepository.completeSourceFactAnalysis).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: 'fact-analysis-1',
|
||||
@ -586,6 +630,76 @@ describe('BomCostingProcessingService', () => {
|
||||
expect(bomCostingRepository.failSourceSnapshot).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('旧版资料的图片已更新时自动重新归档,再继续核算', async () => {
|
||||
const legacySnapshot: MarketDetailSnapshot = {
|
||||
...snapshot,
|
||||
skus: Array.from({ length: 500 }, (_, index) => ({
|
||||
...snapshot.skus[0],
|
||||
externalSkuId: `legacy-sku-${index + 1}`,
|
||||
name: `旧规格 ${index + 1}`,
|
||||
})),
|
||||
requestId: 'legacy-request',
|
||||
}
|
||||
const refreshedSnapshot: MarketDetailSnapshot = {
|
||||
...snapshot,
|
||||
skuTotalRows: 1,
|
||||
skuReturnedRows: 1,
|
||||
skuTruncated: false,
|
||||
mainImages: ['https://storage.example.com/latest-main.jpg'],
|
||||
requestId: 'refreshed-request',
|
||||
}
|
||||
const rearchivedSource = {
|
||||
...sourceSnapshot,
|
||||
rawSnapshot: refreshedSnapshot,
|
||||
storedImageCount: 2,
|
||||
}
|
||||
jest.spyOn(bomCostingRepository, 'findCaseForProcessing').mockResolvedValue({
|
||||
...caseRecord(),
|
||||
sourceSnapshot: {
|
||||
...sourceSnapshot,
|
||||
skuCount: 500,
|
||||
rawSnapshot: legacySnapshot,
|
||||
},
|
||||
} as never)
|
||||
jest
|
||||
.spyOn(bomCostingRepository, 'claimSourceSnapshotMetadataRefresh')
|
||||
.mockResolvedValue(true)
|
||||
jest.spyOn(bomCostingRepository, 'updateCaseTitle').mockResolvedValue({} as never)
|
||||
jest
|
||||
.spyOn(marketDetailClient, 'readProduct')
|
||||
.mockResolvedValue(refreshedSnapshot)
|
||||
mockRefreshSourceMetadata.mockRejectedValue(
|
||||
new mockSourceImagesChangedError('竞品图片集合已经变化'),
|
||||
)
|
||||
mockArchive.mockResolvedValue(rearchivedSource)
|
||||
mockRunAnalysis.mockRejectedValue(new Error('停止在重新归档后的测试边界'))
|
||||
const { BomCostingProcessingService } = await import(
|
||||
'./bom-costing-processing.service'
|
||||
)
|
||||
|
||||
await new BomCostingProcessingService().processCase('case-1')
|
||||
|
||||
expect(mockArchive).toHaveBeenCalledWith(expect.objectContaining({
|
||||
sourceSnapshotId: 'source-1',
|
||||
snapshot: refreshedSnapshot,
|
||||
onProgress: expect.any(Function),
|
||||
}))
|
||||
expect(bomCostingRepository.updateCaseStage).toHaveBeenCalledWith(
|
||||
'case-1',
|
||||
expect.objectContaining({
|
||||
eventType: 'SOURCE_REARCHIVE_STARTED',
|
||||
message: '竞品图片已更新,正在重新归档最新资料',
|
||||
}),
|
||||
)
|
||||
expect(bomCostingRepository.updateCaseStage).toHaveBeenCalledWith(
|
||||
'case-1',
|
||||
expect.objectContaining({
|
||||
eventType: 'SOURCE_REARCHIVE_COMPLETED',
|
||||
}),
|
||||
)
|
||||
expect(bomCostingRepository.failSourceSnapshot).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('旧版元数据刷新失败时恢复归档为可复用状态', async () => {
|
||||
const legacySnapshot: MarketDetailSnapshot = {
|
||||
...snapshot,
|
||||
@ -654,6 +768,34 @@ describe('BomCostingProcessingService', () => {
|
||||
expect(mockRunAnalysis).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('已保存逐图事实后的临时模型网络故障会自动续跑,不要求用户手动继续', async () => {
|
||||
jest.spyOn(bomCostingRepository, 'prepareSourceFactAnalysis')
|
||||
.mockResolvedValue(factAnalysisRecord(
|
||||
BOM_COSTING_FACT_ANALYSIS_STATUS.READY,
|
||||
) as never)
|
||||
mockRunAnalysis.mockRejectedValue(new AppError(
|
||||
ErrorCode.BOM_COSTING_INVALID_PROVIDER,
|
||||
'多模态分析服务暂时无法连接',
|
||||
))
|
||||
const requeueSpy = jest
|
||||
.spyOn(bomCostingRepository, 'requeueTransientMultimodalFailure')
|
||||
.mockResolvedValue(true)
|
||||
const { BomCostingProcessingService } = await import(
|
||||
'./bom-costing-processing.service'
|
||||
)
|
||||
|
||||
await new BomCostingProcessingService().processCase('case-1')
|
||||
|
||||
expect(requeueSpy).toHaveBeenCalledWith({
|
||||
caseId: 'case-1',
|
||||
analysisRunId: 'analysis-run-1',
|
||||
message: '多模态分析服务暂时无法连接',
|
||||
})
|
||||
expect(bomCostingRepository.failCase).not.toHaveBeenCalled()
|
||||
expect(bomCostingRepository.failSourceSnapshot).not.toHaveBeenCalled()
|
||||
expect(bomCostingRepository.failSourceFactAnalysis).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('逐图事实保存完成后最终合成失败,不把事实缓存回退为失败', async () => {
|
||||
mockRunAnalysis.mockImplementation(async (input) => {
|
||||
const analysisInput = input as {
|
||||
|
||||
@ -24,9 +24,15 @@ import { bomCostingRepository } from '@/server/repositories/bom-costing.reposito
|
||||
import {
|
||||
buildMarketSnapshotFromStoredSource,
|
||||
bomCostingSourceArchiveService,
|
||||
BomCostingSourceImagesChangedError,
|
||||
type BomCostingArchiveProgress,
|
||||
} from './bom-costing-source-archive.service'
|
||||
import { prepareBomCostingAnalysis } from './bom-costing-result-preparer'
|
||||
import { getCompetitorAnalysisProvider } from './bom-costing-provider'
|
||||
import {
|
||||
readBomCostingSynthesisCheckpoint,
|
||||
} from './bom-costing-multimodal-analyzer'
|
||||
import { isBomCostingMultimodalTransientError } from './bom-costing-multimodal-gateway'
|
||||
import {
|
||||
isLegacyMarketSkuSnapshotPossiblyTruncated,
|
||||
marketDetailClient,
|
||||
@ -241,6 +247,42 @@ function buildAnalysisImagePlan(
|
||||
})
|
||||
}
|
||||
|
||||
async function persistArchiveProgress(
|
||||
caseId: string,
|
||||
progress: BomCostingArchiveProgress,
|
||||
) {
|
||||
const settled = progress.storedCount + progress.failedCount
|
||||
const caseProgress =
|
||||
20 +
|
||||
Math.round((settled / Math.max(progress.totalCount, 1)) * 24)
|
||||
await bomCostingRepository.updateCaseStage(caseId, {
|
||||
eventType:
|
||||
progress.phase === 'STARTED'
|
||||
? 'ASSET_ARCHIVE_ITEM_STARTED'
|
||||
: progress.status === BomCostingSourceAssetStatus.STORED
|
||||
? 'ASSET_STORED'
|
||||
: 'ASSET_ARCHIVE_FAILED',
|
||||
status: BomCostingCaseStatus.ANALYZING,
|
||||
progress: caseProgress,
|
||||
message:
|
||||
progress.phase === 'STARTED'
|
||||
? `正在归档第 ${progress.sortOrder + 1} 张图片`
|
||||
: `图片归档 ${settled}/${progress.totalCount}`,
|
||||
payload: {
|
||||
phase: progress.phase,
|
||||
assetId: progress.assetId,
|
||||
kind: progress.kind,
|
||||
assetStatus: progress.status,
|
||||
storedUrl: progress.storedUrl,
|
||||
sortOrder: progress.sortOrder,
|
||||
externalSkuIds: progress.externalSkuIds,
|
||||
storedCount: progress.storedCount,
|
||||
failedCount: progress.failedCount,
|
||||
totalCount: progress.totalCount,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export class BomCostingProcessingService {
|
||||
async processCase(caseId: string) {
|
||||
const claimed = await bomCostingRepository.claimCaseForProcessing(caseId)
|
||||
@ -301,25 +343,74 @@ export class BomCostingProcessingService {
|
||||
},
|
||||
})
|
||||
const fetched = await marketDetailClient.readProduct(record.sourceUrl)
|
||||
source = await bomCostingSourceArchiveService.refreshMetadata({
|
||||
source,
|
||||
snapshot: fetched,
|
||||
})
|
||||
sourceMetadataRefreshOwnedByTask = false
|
||||
await bomCostingRepository.updateCaseTitle(caseId, fetched.title)
|
||||
await bomCostingRepository.updateCaseStage(caseId, {
|
||||
eventType: 'SOURCE_METADATA_REFRESH_COMPLETED',
|
||||
status: BomCostingCaseStatus.ANALYZING,
|
||||
progress: 18,
|
||||
message: `已补全 ${fetched.skuReturnedRows ?? fetched.skus.length}/${fetched.skuTotalRows ?? fetched.skus.length} 条平台规格元数据,沿用 ${source.storedImageCount} 张归档图片`,
|
||||
payload: {
|
||||
try {
|
||||
source = await bomCostingSourceArchiveService.refreshMetadata({
|
||||
source,
|
||||
snapshot: fetched,
|
||||
})
|
||||
sourceMetadataRefreshOwnedByTask = false
|
||||
await bomCostingRepository.updateCaseTitle(caseId, fetched.title)
|
||||
await bomCostingRepository.updateCaseStage(caseId, {
|
||||
eventType: 'SOURCE_METADATA_REFRESH_COMPLETED',
|
||||
status: BomCostingCaseStatus.ANALYZING,
|
||||
progress: 18,
|
||||
message: `已补全 ${fetched.skuReturnedRows ?? fetched.skus.length}/${fetched.skuTotalRows ?? fetched.skus.length} 条平台规格元数据,沿用 ${source.storedImageCount} 张归档图片`,
|
||||
payload: {
|
||||
sourceSnapshotId: source.id,
|
||||
skuTotalRows: fetched.skuTotalRows ?? fetched.skus.length,
|
||||
skuReturnedRows:
|
||||
fetched.skuReturnedRows ?? fetched.skus.length,
|
||||
archivedImageCount: source.storedImageCount,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
if (!(error instanceof BomCostingSourceImagesChangedError)) {
|
||||
throw error
|
||||
}
|
||||
|
||||
sourceMetadataRefreshOwnedByTask = false
|
||||
sourceOwnedByTask = true
|
||||
await bomCostingRepository.updateCaseTitle(caseId, fetched.title)
|
||||
await bomCostingRepository.updateCaseStage(caseId, {
|
||||
eventType: 'SOURCE_REARCHIVE_STARTED',
|
||||
status: BomCostingCaseStatus.ANALYZING,
|
||||
progress: 18,
|
||||
message: '竞品图片已更新,正在重新归档最新资料',
|
||||
payload: {
|
||||
sourceSnapshotId: source.id,
|
||||
previousImageCount: source.storedImageCount,
|
||||
latestImageCount:
|
||||
fetched.mainImages.length +
|
||||
fetched.skuImages.length +
|
||||
fetched.detailImages.length,
|
||||
},
|
||||
})
|
||||
await bomCostingRepository.updateCaseStage(caseId, {
|
||||
eventType: 'ASSET_ARCHIVE_STARTED',
|
||||
status: BomCostingCaseStatus.ANALYZING,
|
||||
progress: 20,
|
||||
message: '正在将最新竞品图片归档到对象存储',
|
||||
})
|
||||
source = await bomCostingSourceArchiveService.archive({
|
||||
sourceSnapshotId: source.id,
|
||||
skuTotalRows: fetched.skuTotalRows ?? fetched.skus.length,
|
||||
skuReturnedRows:
|
||||
fetched.skuReturnedRows ?? fetched.skus.length,
|
||||
archivedImageCount: source.storedImageCount,
|
||||
},
|
||||
})
|
||||
snapshot: fetched,
|
||||
onProgress: (progress) =>
|
||||
persistArchiveProgress(caseId, progress),
|
||||
})
|
||||
sourceOwnedByTask = false
|
||||
await bomCostingRepository.updateCaseStage(caseId, {
|
||||
eventType: 'SOURCE_REARCHIVE_COMPLETED',
|
||||
status: BomCostingCaseStatus.ANALYZING,
|
||||
progress: 46,
|
||||
message: `已更新并归档 ${source.storedImageCount} 张最新竞品图片`,
|
||||
payload: {
|
||||
sourceSnapshotId: source.id,
|
||||
storedImageCount: source.storedImageCount,
|
||||
failedImageCount: source.failedImageCount,
|
||||
skuCount: source.skuCount,
|
||||
},
|
||||
})
|
||||
}
|
||||
} else {
|
||||
await bomCostingRepository.updateCaseStage(caseId, {
|
||||
eventType: 'SOURCE_METADATA_REFRESH_WAITING',
|
||||
@ -385,40 +476,8 @@ export class BomCostingProcessingService {
|
||||
source = await bomCostingSourceArchiveService.archive({
|
||||
sourceSnapshotId: source.id,
|
||||
snapshot: fetched,
|
||||
onProgress: async (progress) => {
|
||||
const settled = progress.storedCount + progress.failedCount
|
||||
const caseProgress =
|
||||
20 +
|
||||
Math.round(
|
||||
(settled / Math.max(progress.totalCount, 1)) * 24,
|
||||
)
|
||||
await bomCostingRepository.updateCaseStage(caseId, {
|
||||
eventType:
|
||||
progress.phase === 'STARTED'
|
||||
? 'ASSET_ARCHIVE_ITEM_STARTED'
|
||||
: progress.status === BomCostingSourceAssetStatus.STORED
|
||||
? 'ASSET_STORED'
|
||||
: 'ASSET_ARCHIVE_FAILED',
|
||||
status: BomCostingCaseStatus.ANALYZING,
|
||||
progress: caseProgress,
|
||||
message:
|
||||
progress.phase === 'STARTED'
|
||||
? `正在归档第 ${progress.sortOrder + 1} 张图片`
|
||||
: `图片归档 ${settled}/${progress.totalCount}`,
|
||||
payload: {
|
||||
phase: progress.phase,
|
||||
assetId: progress.assetId,
|
||||
kind: progress.kind,
|
||||
assetStatus: progress.status,
|
||||
storedUrl: progress.storedUrl,
|
||||
sortOrder: progress.sortOrder,
|
||||
externalSkuIds: progress.externalSkuIds,
|
||||
storedCount: progress.storedCount,
|
||||
failedCount: progress.failedCount,
|
||||
totalCount: progress.totalCount,
|
||||
},
|
||||
})
|
||||
},
|
||||
onProgress: (progress) =>
|
||||
persistArchiveProgress(caseId, progress),
|
||||
})
|
||||
sourceOwnedByTask = false
|
||||
await bomCostingRepository.updateCaseStage(caseId, {
|
||||
@ -690,6 +749,9 @@ export class BomCostingProcessingService {
|
||||
sourceUrl: record.sourceUrl,
|
||||
snapshot: marketSnapshot,
|
||||
existingFactSnapshot,
|
||||
synthesisCheckpoint: readBomCostingSynthesisCheckpoint(
|
||||
analysisRun.resultSnapshot,
|
||||
),
|
||||
analysisInstruction: analysisRun.instruction,
|
||||
onFactBatchStarted:
|
||||
factAnalysisOwnedByTask && factAnalysisId
|
||||
@ -823,6 +885,63 @@ export class BomCostingProcessingService {
|
||||
message: '正在合并逐图事实并生成各 SKU 的结构化 BOM',
|
||||
})
|
||||
},
|
||||
onSynthesisBatchStarted: async (progress) => {
|
||||
const caseProgress =
|
||||
78 +
|
||||
Math.floor(
|
||||
(progress.completedSkuCount /
|
||||
Math.max(analysisInputStats.inputSkuCount, 1)) *
|
||||
7,
|
||||
)
|
||||
await bomCostingRepository.updateCaseStage(caseId, {
|
||||
eventType: 'MODEL_SYNTHESIS_BATCH_STARTED',
|
||||
status: BomCostingCaseStatus.ANALYZING,
|
||||
progress: caseProgress,
|
||||
message:
|
||||
`正在并行汇总第 ${progress.batchIndex}/${progress.totalBatches} 批规格结构` +
|
||||
`(${progress.batchSkuCount} 个 SKU)`,
|
||||
payload: {
|
||||
batchIndex: progress.batchIndex,
|
||||
totalBatches: progress.totalBatches,
|
||||
batchSkuCount: progress.batchSkuCount,
|
||||
completedSkuCount: progress.completedSkuCount,
|
||||
},
|
||||
})
|
||||
},
|
||||
onSynthesisBatchCompleted: async (progress) => {
|
||||
if (progress.synthesisCheckpoint) {
|
||||
await bomCostingRepository.saveAnalysisRunSynthesisCheckpoint({
|
||||
id: analysisRunId,
|
||||
checkpoint:
|
||||
progress.synthesisCheckpoint as unknown as Prisma.InputJsonValue,
|
||||
})
|
||||
}
|
||||
const caseProgress =
|
||||
78 +
|
||||
Math.round(
|
||||
(progress.completedSkuCount /
|
||||
Math.max(analysisInputStats.inputSkuCount, 1)) *
|
||||
7,
|
||||
)
|
||||
await bomCostingRepository.updateCaseStage(caseId, {
|
||||
eventType: 'MODEL_SYNTHESIS_BATCH_COMPLETED',
|
||||
status: BomCostingCaseStatus.ANALYZING,
|
||||
progress: caseProgress,
|
||||
message:
|
||||
`已完成 ${progress.completedSkuCount}/${analysisInputStats.inputSkuCount} 个 SKU 的结构汇总`,
|
||||
payload: {
|
||||
batchIndex: progress.batchIndex,
|
||||
totalBatches: progress.totalBatches,
|
||||
batchSkuCount: progress.batchSkuCount,
|
||||
completedSkuCount: progress.completedSkuCount,
|
||||
model: progress.model,
|
||||
callId: progress.callId,
|
||||
durationMs: progress.durationMs,
|
||||
promptTokens: progress.promptTokens,
|
||||
completionTokens: progress.completionTokens,
|
||||
},
|
||||
})
|
||||
},
|
||||
})
|
||||
const persistedResult = archivedSource
|
||||
? replaceAnalysisImageUrlsWithStableArchive(output.result, archivedSource)
|
||||
@ -830,7 +949,7 @@ export class BomCostingProcessingService {
|
||||
await bomCostingRepository.updateCaseStage(caseId, {
|
||||
eventType: 'MODEL_ANALYSIS_COMPLETED',
|
||||
status: BomCostingCaseStatus.ANALYZING,
|
||||
progress: 80,
|
||||
progress: 86,
|
||||
message: `结构分析完成,识别到 ${persistedResult.skus.length} 个 SKU`,
|
||||
payload: {
|
||||
...output.trace,
|
||||
@ -879,6 +998,30 @@ export class BomCostingProcessingService {
|
||||
})
|
||||
} catch (error) {
|
||||
const message = readErrorMessage(error)
|
||||
const canAutoRecoverTransientMultimodalFailure =
|
||||
!sourceOwnedByTask &&
|
||||
!sourceMetadataRefreshOwnedByTask &&
|
||||
!factAnalysisOwnedByTask &&
|
||||
isBomCostingMultimodalTransientError(error)
|
||||
if (canAutoRecoverTransientMultimodalFailure) {
|
||||
const requeued = await bomCostingRepository
|
||||
.requeueTransientMultimodalFailure({
|
||||
caseId,
|
||||
analysisRunId,
|
||||
message,
|
||||
})
|
||||
.catch((persistError) => {
|
||||
console.error('[BOM costing] failed to requeue transient model failure', {
|
||||
caseId,
|
||||
error:
|
||||
persistError instanceof Error
|
||||
? persistError.message
|
||||
: String(persistError),
|
||||
})
|
||||
return false
|
||||
})
|
||||
if (requeued) return
|
||||
}
|
||||
if (factAnalysisOwnedByTask && factAnalysisId) {
|
||||
await bomCostingRepository
|
||||
.failSourceFactAnalysis(factAnalysisId, message)
|
||||
|
||||
@ -17,6 +17,8 @@ import {
|
||||
isBomCostingMultimodalConfigured,
|
||||
type BomCostingMultimodalInputStats,
|
||||
type BomCostingMultimodalOutput,
|
||||
type BomCostingSynthesisCheckpoint,
|
||||
type BomCostingSynthesisBatchProgress,
|
||||
} from './bom-costing-multimodal-analyzer'
|
||||
import type {
|
||||
BomCostingFactBatchProgress,
|
||||
@ -35,6 +37,7 @@ export interface CompetitorAnalysisProvider {
|
||||
sourceUrl: string
|
||||
snapshot: MarketDetailSnapshot | null
|
||||
existingFactSnapshot?: BomCostingSourceFactSnapshot | null
|
||||
synthesisCheckpoint?: BomCostingSynthesisCheckpoint | null
|
||||
analysisInstruction?: string
|
||||
onFactBatchStarted?: (
|
||||
progress: Omit<BomCostingFactBatchProgress, 'snapshot' | 'call'>,
|
||||
@ -46,6 +49,15 @@ export interface CompetitorAnalysisProvider {
|
||||
snapshot: BomCostingSourceFactSnapshot
|
||||
trace: BomCostingFactExtractionTrace
|
||||
}) => Promise<void>
|
||||
onSynthesisBatchStarted?: (
|
||||
progress: Pick<
|
||||
BomCostingSynthesisBatchProgress,
|
||||
'batchIndex' | 'totalBatches' | 'batchSkuCount' | 'completedSkuCount'
|
||||
>,
|
||||
) => Promise<void>
|
||||
onSynthesisBatchCompleted?: (
|
||||
progress: BomCostingSynthesisBatchProgress,
|
||||
) => Promise<void>
|
||||
}): Promise<BomCostingMultimodalOutput>
|
||||
}
|
||||
|
||||
@ -278,6 +290,8 @@ class FixtureCompetitorAnalysisProvider implements CompetitorAnalysisProvider {
|
||||
imageCount: 0,
|
||||
inputSkuCount: result.skus.length,
|
||||
factBatchCount: 0,
|
||||
synthesisBatchCount: 0,
|
||||
synthesisCallIds: [],
|
||||
reusedImageCount: 0,
|
||||
analyzedImageCount: 0,
|
||||
durationMs: 0,
|
||||
@ -313,6 +327,7 @@ class MarketDetailMultimodalProvider implements CompetitorAnalysisProvider {
|
||||
sourceUrl: string
|
||||
snapshot: MarketDetailSnapshot | null
|
||||
existingFactSnapshot?: BomCostingSourceFactSnapshot | null
|
||||
synthesisCheckpoint?: BomCostingSynthesisCheckpoint | null
|
||||
analysisInstruction?: string
|
||||
onFactBatchStarted?: (
|
||||
progress: Omit<BomCostingFactBatchProgress, 'snapshot' | 'call'>,
|
||||
@ -324,6 +339,15 @@ class MarketDetailMultimodalProvider implements CompetitorAnalysisProvider {
|
||||
snapshot: BomCostingSourceFactSnapshot
|
||||
trace: BomCostingFactExtractionTrace
|
||||
}) => Promise<void>
|
||||
onSynthesisBatchStarted?: (
|
||||
progress: Pick<
|
||||
BomCostingSynthesisBatchProgress,
|
||||
'batchIndex' | 'totalBatches' | 'batchSkuCount' | 'completedSkuCount'
|
||||
>,
|
||||
) => Promise<void>
|
||||
onSynthesisBatchCompleted?: (
|
||||
progress: BomCostingSynthesisBatchProgress,
|
||||
) => Promise<void>
|
||||
}) {
|
||||
if (!input.snapshot) {
|
||||
throw new Error('竞品资料快照不存在,不能开始多模态分析')
|
||||
|
||||
@ -182,4 +182,43 @@ describe('BOM 核算结果准备', () => {
|
||||
subtotal: 80,
|
||||
})
|
||||
})
|
||||
|
||||
it('单件桌面板缺少自身长宽时,使用已识别的 SKU 桌面尺寸按面积核算', () => {
|
||||
const missingBoardDimensions: CompetitorAnalysisResultV1 = {
|
||||
...analysis,
|
||||
skus: analysis.skus.map((sku) => ({
|
||||
...sku,
|
||||
dimensions: {
|
||||
lengthMm: 1200,
|
||||
widthMm: 600,
|
||||
heightMm: 750,
|
||||
},
|
||||
bomLines: sku.bomLines.map((line) =>
|
||||
line.category === 'BOARD'
|
||||
? {
|
||||
...line,
|
||||
lengthMm: undefined,
|
||||
widthMm: undefined,
|
||||
unit: '平方米',
|
||||
}
|
||||
: line,
|
||||
),
|
||||
})),
|
||||
}
|
||||
|
||||
const [sku] = prepareBomCostingAnalysis(
|
||||
missingBoardDimensions,
|
||||
emptyCandidates(),
|
||||
)
|
||||
const board = sku?.bomLines.find((line) => line.category === 'BOARD')
|
||||
|
||||
expect(sku?.estimatedCost).toBeGreaterThan(0)
|
||||
expect(board).toMatchObject({
|
||||
matchedLibraryType: 'EXTERNAL_ANALYSIS_ESTIMATE',
|
||||
lengthMm: 1200,
|
||||
widthMm: 600,
|
||||
calculatedQuantity: 0.72,
|
||||
subtotal: 57.6,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@ -6,6 +6,7 @@ import {
|
||||
import type {
|
||||
CompetitorAnalysisResultV1,
|
||||
CompetitorBomLineV1,
|
||||
CompetitorSkuV1,
|
||||
} from '@/lib/bom-costing/contracts'
|
||||
import {
|
||||
calculateBomCostingLine,
|
||||
@ -83,13 +84,45 @@ function createExternalEstimateCandidate(
|
||||
}
|
||||
}
|
||||
|
||||
function isSquareMeterUnit(unit: string) {
|
||||
return ['㎡', 'm²', 'm2', '平方米'].includes(unit.trim().toLowerCase())
|
||||
}
|
||||
|
||||
function resolvePricingDimensions(
|
||||
line: CompetitorBomLineV1,
|
||||
skuDimensions: CompetitorSkuV1['dimensions'],
|
||||
) {
|
||||
const canUseSkuSurfaceDimensions =
|
||||
line.category === 'BOARD' &&
|
||||
line.quantity === 1 &&
|
||||
isSquareMeterUnit(line.unit) &&
|
||||
Boolean(skuDimensions.lengthMm) &&
|
||||
Boolean(skuDimensions.widthMm)
|
||||
|
||||
if (!canUseSkuSurfaceDimensions) {
|
||||
return {
|
||||
lengthMm: line.lengthMm,
|
||||
widthMm: line.widthMm,
|
||||
heightMm: line.heightMm,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
lengthMm: line.lengthMm ?? skuDimensions.lengthMm,
|
||||
widthMm: line.widthMm ?? skuDimensions.widthMm,
|
||||
heightMm: line.heightMm,
|
||||
}
|
||||
}
|
||||
|
||||
function prepareLine(
|
||||
line: CompetitorBomLineV1,
|
||||
candidates: Record<BomCostingLineCategory, BomCostingLibraryCandidate[]>,
|
||||
sortOrder: number,
|
||||
skuDimensions: CompetitorSkuV1['dimensions'],
|
||||
): BomCostingPreparedLine {
|
||||
const category = line.category as BomCostingLineCategory
|
||||
const lossFactor = line.suggestedLossFactor ?? 1
|
||||
const pricingDimensions = resolvePricingDimensions(line, skuDimensions)
|
||||
const externalEstimate = createExternalEstimateCandidate(line)
|
||||
const libraryEstimate = resolveBomCostingLibraryEstimate(candidates[category], {
|
||||
code: line.materialCode,
|
||||
@ -107,9 +140,9 @@ function prepareLine(
|
||||
category: line.category,
|
||||
packagingKind: normalizePackagingKind(line.packagingKind),
|
||||
pricingMode: candidate?.pricingMode,
|
||||
lengthMm: line.lengthMm,
|
||||
widthMm: line.widthMm,
|
||||
heightMm: line.heightMm,
|
||||
lengthMm: pricingDimensions.lengthMm,
|
||||
widthMm: pricingDimensions.widthMm,
|
||||
heightMm: pricingDimensions.heightMm,
|
||||
quantity: line.quantity,
|
||||
unitPrice: candidate?.unitPrice,
|
||||
lossFactor,
|
||||
@ -139,9 +172,9 @@ function prepareLine(
|
||||
materialSpec: line.materialSpec ?? '',
|
||||
processName: line.processName ?? '',
|
||||
packagingKind: normalizePackagingKind(line.packagingKind),
|
||||
lengthMm: line.lengthMm ?? null,
|
||||
widthMm: line.widthMm ?? null,
|
||||
heightMm: line.heightMm ?? null,
|
||||
lengthMm: pricingDimensions.lengthMm ?? null,
|
||||
widthMm: pricingDimensions.widthMm ?? null,
|
||||
heightMm: pricingDimensions.heightMm ?? null,
|
||||
quantity: line.quantity,
|
||||
unit: line.unit,
|
||||
weightKg: line.weightKg ?? null,
|
||||
@ -177,7 +210,7 @@ export function prepareBomCostingAnalysis(
|
||||
) {
|
||||
return analysis.skus.map<BomCostingPreparedSku>((sku, skuIndex) => {
|
||||
const bomLines = sku.bomLines.map((line, lineIndex) =>
|
||||
prepareLine(line, candidates, lineIndex),
|
||||
prepareLine(line, candidates, lineIndex, sku.dimensions),
|
||||
)
|
||||
const summary = summarizeBomCosting(
|
||||
bomLines.map((line) => ({
|
||||
|
||||
@ -24,6 +24,13 @@ type SourceWithAssets = BomCostingSourceSnapshot & {
|
||||
assets: BomCostingSourceAsset[]
|
||||
}
|
||||
|
||||
export class BomCostingSourceImagesChangedError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message)
|
||||
this.name = 'BomCostingSourceImagesChangedError'
|
||||
}
|
||||
}
|
||||
|
||||
export interface BomCostingArchiveProgress {
|
||||
phase: 'STARTED' | 'SETTLED'
|
||||
assetId: string
|
||||
@ -254,7 +261,7 @@ export class BomCostingSourceArchiveService {
|
||||
seeds.length !== input.source.assets.length ||
|
||||
seeds.some((seed) => !existingByOriginalUrl.has(seed.originalUrl))
|
||||
) {
|
||||
throw new Error(
|
||||
throw new BomCostingSourceImagesChangedError(
|
||||
'竞品图片集合已经变化,不能只刷新 SKU 元数据;请重新归档竞品资料',
|
||||
)
|
||||
}
|
||||
@ -266,7 +273,7 @@ export class BomCostingSourceArchiveService {
|
||||
existing.status !== BomCostingSourceAssetStatus.STORED ||
|
||||
!existing.storageKey
|
||||
) {
|
||||
throw new Error(
|
||||
throw new BomCostingSourceImagesChangedError(
|
||||
'旧竞品图片没有完整归档,不能只刷新 SKU 元数据;请重新归档竞品资料',
|
||||
)
|
||||
}
|
||||
|
||||
@ -208,9 +208,20 @@ start_pm2_release() {
|
||||
local app_root="$release_root/__PROJECT_SUBDIR__"
|
||||
local start_command
|
||||
local worker_command
|
||||
local worker_timeout
|
||||
prepare_standalone_runtime "$app_root"
|
||||
# Read the shared environment before resolving the curl limit. The worker
|
||||
# command itself sources this file later, but doing it only there leaves the
|
||||
# already-interpolated --max-time stuck at the 45-minute default.
|
||||
set -a
|
||||
source "$SHARED/.env"
|
||||
set +a
|
||||
worker_timeout="${BOM_COSTING_WORKER_REQUEST_TIMEOUT_SECONDS:-2700}"
|
||||
if ! [[ "$worker_timeout" =~ ^[1-9][0-9]*$ ]]; then
|
||||
worker_timeout=2700
|
||||
fi
|
||||
start_command="cd '$app_root' && set -a && source '$SHARED/.env' && set +a && exec env PORT=$APP_PORT HOSTNAME=0.0.0.0 node .next/standalone/server.js"
|
||||
worker_command="cd '$app_root' && set -a && source '$SHARED/.env' && set +a && : \"\${BOM_COSTING_WORKER_SECRET:?BOM_COSTING_WORKER_SECRET is required}\"; while true; do curl --fail --silent --show-error --max-time 780 --request POST 'http://127.0.0.1:$APP_PORT/api/internal/bom-costing/worker/run' --header \"x-bom-costing-worker-secret: \$BOM_COSTING_WORKER_SECRET\" >/dev/null || echo '[BOM costing worker] loop request failed' >&2; sleep 10; done"
|
||||
worker_command="cd '$app_root' && set -a && source '$SHARED/.env' && set +a && : \"\${BOM_COSTING_WORKER_SECRET:?BOM_COSTING_WORKER_SECRET is required}\"; while true; do curl --fail --silent --show-error --max-time $worker_timeout --request POST 'http://127.0.0.1:$APP_PORT/api/internal/bom-costing/worker/run' --header \"x-bom-costing-worker-secret: \$BOM_COSTING_WORKER_SECRET\" >/dev/null || echo '[BOM costing worker] loop request failed' >&2; sleep 10; done"
|
||||
pm2 delete "$PM2_NAME" >/dev/null 2>&1 || true
|
||||
pm2 delete "$BOM_WORKER_NAME" >/dev/null 2>&1 || true
|
||||
pm2 start /bin/bash --name "$PM2_NAME" -- -lc "$start_command"
|
||||
|
||||
@ -285,13 +285,21 @@ start_pm2_release() {
|
||||
local app_root="$release_root/$PROJECT_SUBDIR"
|
||||
local start_command
|
||||
local worker_command
|
||||
local worker_timeout
|
||||
prepare_standalone_runtime "$app_root"
|
||||
# Read the shared environment before resolving the curl limit. The worker
|
||||
# command itself sources this file later, but doing it only there leaves the
|
||||
# already-interpolated --max-time stuck at the 45-minute default.
|
||||
set -a
|
||||
source "$SHARED/.env"
|
||||
set +a
|
||||
ensure_image_search_model
|
||||
worker_timeout="${BOM_COSTING_WORKER_REQUEST_TIMEOUT_SECONDS:-2700}"
|
||||
if ! [[ "$worker_timeout" =~ ^[1-9][0-9]*$ ]]; then
|
||||
worker_timeout=2700
|
||||
fi
|
||||
start_command="cd '$app_root' && set -a && source '$SHARED/.env' && set +a && exec env IMAGE_SEARCH_MODEL_PATH='$SHARED/models/dinov2-small' PORT=$APP_PORT HOSTNAME=0.0.0.0 node .next/standalone/server.js"
|
||||
worker_command="cd '$app_root' && set -a && source '$SHARED/.env' && set +a && : \"\${BOM_COSTING_WORKER_SECRET:?BOM_COSTING_WORKER_SECRET is required}\"; while true; do curl --fail --silent --show-error --max-time 780 --request POST 'http://127.0.0.1:$APP_PORT/api/internal/bom-costing/worker/run' --header \"x-bom-costing-worker-secret: \$BOM_COSTING_WORKER_SECRET\" >/dev/null || echo '[BOM costing worker] loop request failed' >&2; sleep 10; done"
|
||||
worker_command="cd '$app_root' && set -a && source '$SHARED/.env' && set +a && : \"\${BOM_COSTING_WORKER_SECRET:?BOM_COSTING_WORKER_SECRET is required}\"; while true; do curl --fail --silent --show-error --max-time $worker_timeout --request POST 'http://127.0.0.1:$APP_PORT/api/internal/bom-costing/worker/run' --header \"x-bom-costing-worker-secret: \$BOM_COSTING_WORKER_SECRET\" >/dev/null || echo '[BOM costing worker] loop request failed' >&2; sleep 10; done"
|
||||
pm2 delete "$PM2_NAME" >/dev/null 2>&1 || true
|
||||
pm2 delete "$BOM_WORKER_NAME" >/dev/null 2>&1 || true
|
||||
pm2 start /bin/bash --name "$PM2_NAME" -- -lc "$start_command"
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user