diff --git a/furniture-3d-system/docs/workflow/生产部署入口说明.md b/furniture-3d-system/docs/workflow/生产部署入口说明.md index fac4c1d5..7b908f17 100644 --- a/furniture-3d-system/docs/workflow/生产部署入口说明.md +++ b/furniture-3d-system/docs/workflow/生产部署入口说明.md @@ -35,6 +35,21 @@ - 源库连接信息只允许放在生产本地 `/opt/furniture-3d-system-prod/shared/employee-directory-sync.env`,不能写入 Git 或共享文档。 - 生产应用内部接口密钥继续从 `/opt/furniture-3d-system-prod/shared/.env` 的 `HR_SYNC_SECRET` 读取。 +## BOM 成本参考镜像 + +- 用户核算请求只读取本地 PostgreSQL 镜像,不在请求中连接上游 `rpt.pm_bomBaseInfo`。 +- 低压只读预检:`npm run sync:bom-cost-reference -- --dry-run --max-pages=2`;默认单连接、每页 100 行、完整页之间等待 250ms。 +- 真实同步必须显式传 `--apply`、固定确认词、目标 PostgreSQL 身份和来源 SQL Server 身份;上游登录必须是 `report_reader`,`app_writer` 会被程序拒绝。 +- 生产定时器安装脚本:`furniture-3d-system/scripts/install-bom-cost-reference-sync-timer.sh`。 +- 生产 systemd 名称:`furniture-bom-cost-reference-sync.service` / `furniture-bom-cost-reference-sync.timer`。 +- 默认调度:每天中国标准时间 `02:00`,附带最多 10 分钟随机延迟;安装时可通过非敏感环境变量调整。 +- 上游连接继续只使用生产共享 `.env` 中现有的 `JST_PLANNING_SQLSERVER_* / report_reader`;不在第二个文件中重复保存密码。 +- 首次运行安装脚本只会创建权限为 `600` 的 `/opt/furniture-3d-system-prod/shared/bom-cost-reference-sync.env` 门禁与限速模板;目标/来源身份未填齐或现有只读配置不完整时拒绝安装定时器。 +- 本地参考行只保留最新成功批次,避免每日约 76 万行无限增长;历史场景在自己的明细快照中保留来源行、指纹、单价、规则和原始计算依据,不依赖旧镜像行回查。 +- 镜像新鲜度按最新成功批次的完成时间判断。上游当前可见的创建时间只作审计展示,不能用来判断当天同步是否过期。 +- 准确度回测:`npm run backtest:bom-cost-reference -- --sample-size=30`,只读最新成功镜像,不访问上游;样本限制 20 至 50 个,任一可比较 SKU 超过固定 10% 误差门槛即失败。 +- 迁移、真实同步、安装/启用定时器和生产回测都必须另行获得生产操作授权;部署代码本身不代表这些动作已经执行。 + ## 明确排除 - `192.168.58.20` 不是当前 `furniture-3d-system` 的生产部署目标。 diff --git a/furniture-3d-system/package.json b/furniture-3d-system/package.json index b2821fbb..7c178471 100644 --- a/furniture-3d-system/package.json +++ b/furniture-3d-system/package.json @@ -18,6 +18,8 @@ "prisma:studio": "prisma studio", "sync:supply-chain-product-archive": "tsx scripts/sync-supply-chain-product-archive.ts", "sync:jst-sku-product-archive": "tsx scripts/sync-jst-sku-product-archive.ts", + "sync:bom-cost-reference": "tsx scripts/sync-bom-cost-reference.ts", + "backtest:bom-cost-reference": "tsx scripts/backtest-bom-cost-reference.ts", "import:yunshan-created-at": "tsx scripts/import-yunshan-product-created-at.ts", "db:verify-master-data": "node scripts/verify-master-data-foundation.js", "db:verify-master-data:audit": "node scripts/verify-master-data-foundation.js --output .master-data-audits/foundation-hard-ready-gate-current.json --summary-output .master-data-audits/foundation-hard-ready-gate-current.summary.json --summary-stdout", diff --git a/furniture-3d-system/prisma/migrations/20260807143000_add_bom_cost_reference_and_scenarios/migration.sql b/furniture-3d-system/prisma/migrations/20260807143000_add_bom_cost_reference_and_scenarios/migration.sql new file mode 100644 index 00000000..72b14a94 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20260807143000_add_bom_cost_reference_and_scenarios/migration.sql @@ -0,0 +1,239 @@ +DO $$ BEGIN + CREATE TYPE "BomCostingReferenceSyncStatus" AS ENUM ('RUNNING', 'SUCCEEDED', 'FAILED'); +EXCEPTION + WHEN duplicate_object THEN NULL; +END $$; + +DO $$ BEGIN + CREATE TYPE "BomCostingScenarioKind" AS ENUM ('SAME_MATERIAL', 'MATERIAL_SUBSTITUTION'); +EXCEPTION + WHEN duplicate_object THEN NULL; +END $$; + +DO $$ BEGIN + CREATE TYPE "BomCostingScenarioStatus" AS ENUM ('FINAL', 'PROVISIONAL', 'INSUFFICIENT_DATA', 'STALE'); +EXCEPTION + WHEN duplicate_object THEN NULL; +END $$; + +CREATE TABLE "BomCostingReferenceSyncRun" ( + "id" TEXT NOT NULL, + "sourceSystem" TEXT NOT NULL DEFAULT 'JSReportReplica', + "sourceDatabase" TEXT NOT NULL DEFAULT '', + "sourceSchema" TEXT NOT NULL DEFAULT 'rpt', + "sourceObject" TEXT NOT NULL DEFAULT 'pm_bomBaseInfo', + "status" "BomCostingReferenceSyncStatus" NOT NULL DEFAULT 'RUNNING', + "batchKey" TEXT NOT NULL DEFAULT '', + "configFingerprint" VARCHAR(64) NOT NULL DEFAULT '', + "cursorStart" TEXT NOT NULL DEFAULT '', + "cursorEnd" TEXT NOT NULL DEFAULT '', + "rowsRead" INTEGER NOT NULL DEFAULT 0, + "rowsWritten" INTEGER NOT NULL DEFAULT 0, + "rowsCreated" INTEGER NOT NULL DEFAULT 0, + "rowsUpdated" INTEGER NOT NULL DEFAULT 0, + "rowsUnchanged" INTEGER NOT NULL DEFAULT 0, + "rowsSkipped" INTEGER NOT NULL DEFAULT 0, + "errorCount" INTEGER NOT NULL DEFAULT 0, + "errorMessage" TEXT NOT NULL DEFAULT '', + "durationMs" INTEGER NOT NULL DEFAULT 0, + "startedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "completedAt" TIMESTAMP(3), + "sourceAsOf" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + CONSTRAINT "BomCostingReferenceSyncRun_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE "BomCostingReferenceRow" ( + "id" TEXT NOT NULL, + "sourceRowId" TEXT NOT NULL, + "sourceSku" TEXT NOT NULL DEFAULT '', + "bomVersionKey" TEXT NOT NULL DEFAULT '', + "category" TEXT NOT NULL DEFAULT '', + "categoryCode" TEXT NOT NULL DEFAULT '', + "partNumber" TEXT NOT NULL DEFAULT '', + "partName" TEXT NOT NULL DEFAULT '', + "side" TEXT NOT NULL DEFAULT '', + "materialName" TEXT NOT NULL DEFAULT '', + "materialCode" TEXT NOT NULL DEFAULT '', + "materialSpec" TEXT NOT NULL DEFAULT '', + "processName" TEXT NOT NULL DEFAULT '', + "unit" TEXT NOT NULL DEFAULT '', + "rawLength" TEXT NOT NULL DEFAULT '', + "rawWidth" TEXT NOT NULL DEFAULT '', + "rawLongEdge" TEXT NOT NULL DEFAULT '', + "rawShortEdge" TEXT NOT NULL DEFAULT '', + "rawQuantity" TEXT NOT NULL DEFAULT '', + "rawCoefficient" TEXT NOT NULL DEFAULT '', + "rawArea" TEXT NOT NULL DEFAULT '', + "rawEdgeLength" TEXT NOT NULL DEFAULT '', + "rawUnitPrice" TEXT NOT NULL DEFAULT '', + "rawAmount" TEXT NOT NULL DEFAULT '', + "rawNote" TEXT NOT NULL DEFAULT '', + "rawCreatedAt" TEXT NOT NULL DEFAULT '', + "lengthMm" DECIMAL(18, 6), + "widthMm" DECIMAL(18, 6), + "longEdgeMm" DECIMAL(18, 6), + "shortEdgeMm" DECIMAL(18, 6), + "quantity" DECIMAL(18, 6), + "coefficient" DECIMAL(18, 6), + "areaSqm" DECIMAL(18, 6), + "edgeLengthM" DECIMAL(18, 6), + "unitPrice" DECIMAL(18, 6), + "amount" DECIMAL(18, 6), + "sourceCreatedAt" TIMESTAMP(3), + "sourceFingerprint" VARCHAR(64) NOT NULL, + "isSummaryRow" BOOLEAN NOT NULL DEFAULT false, + "syncRunId" TEXT NOT NULL, + "syncedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "BomCostingReferenceRow_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE "BomCostingMaterialOption" ( + "id" TEXT NOT NULL, + "code" TEXT NOT NULL, + "name" TEXT NOT NULL, + "normalizedName" TEXT NOT NULL, + "category" TEXT NOT NULL DEFAULT 'BOARD', + "aliases" JSONB NOT NULL DEFAULT '[]', + "enabled" BOOLEAN NOT NULL DEFAULT true, + "sortOrder" INTEGER NOT NULL DEFAULT 0, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + CONSTRAINT "BomCostingMaterialOption_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE "BomCostingScenario" ( + "id" TEXT NOT NULL, + "caseId" TEXT NOT NULL, + "skuId" TEXT NOT NULL, + "kind" "BomCostingScenarioKind" NOT NULL, + "scenarioKey" TEXT NOT NULL DEFAULT '', + "revision" INTEGER NOT NULL DEFAULT 1, + "isCurrent" BOOLEAN NOT NULL DEFAULT true, + "targetMaterialId" TEXT, + "targetMaterialName" TEXT NOT NULL DEFAULT '', + "status" "BomCostingScenarioStatus" NOT NULL DEFAULT 'PROVISIONAL', + "totalCost" DECIMAL(18, 2), + "knownCost" DECIMAL(18, 2), + "materialCost" DECIMAL(18, 2), + "processingCost" DECIMAL(18, 2), + "laborCost" DECIMAL(18, 2), + "packagingCost" DECIMAL(18, 2), + "lossCost" DECIMAL(18, 2), + "competitorPrice" DECIMAL(18, 2), + "priceDelta" DECIMAL(18, 2), + "confidence" DECIMAL(5, 4), + "warning" TEXT NOT NULL DEFAULT '', + "unresolvedCount" INTEGER NOT NULL DEFAULT 0, + "dataAsOf" TIMESTAMP(3), + "syncRunId" TEXT, + "rulesetVersion" TEXT NOT NULL DEFAULT 'dynamic-bom-cost/v2', + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + CONSTRAINT "BomCostingScenario_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE "BomCostingScenarioLine" ( + "id" TEXT NOT NULL, + "scenarioId" TEXT NOT NULL, + "sourceLineId" TEXT, + "sourceRowId" TEXT NOT NULL DEFAULT '', + "category" TEXT NOT NULL DEFAULT '', + "partName" TEXT NOT NULL DEFAULT '', + "originalMaterial" TEXT NOT NULL DEFAULT '', + "appliedMaterial" TEXT NOT NULL DEFAULT '', + "materialSpec" TEXT NOT NULL DEFAULT '', + "unit" TEXT NOT NULL DEFAULT '', + "quantity" DECIMAL(18, 6), + "coefficient" DECIMAL(18, 6), + "pricingQuantity" DECIMAL(18, 6), + "unitPrice" DECIMAL(18, 6), + "subtotal" DECIMAL(18, 2), + "priceSource" TEXT NOT NULL DEFAULT '', + "sourceSku" TEXT NOT NULL DEFAULT '', + "referenceSkus" JSONB NOT NULL DEFAULT '[]', + "referenceRowIds" JSONB NOT NULL DEFAULT '[]', + "sourceFingerprint" VARCHAR(64) NOT NULL DEFAULT '', + "sourceCreatedAt" TIMESTAMP(3), + "sourceSyncedAt" TIMESTAMP(3), + "calculationRule" TEXT NOT NULL DEFAULT '', + "confidence" DECIMAL(5, 4), + "status" "BomCostingScenarioStatus" NOT NULL DEFAULT 'PROVISIONAL', + "warning" TEXT NOT NULL DEFAULT '', + "rawSnapshot" JSONB, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "BomCostingScenarioLine_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "BomCostingReferenceRow_source_key" ON "BomCostingReferenceRow"("syncRunId", "sourceRowId", "sourceSku", "bomVersionKey"); +CREATE INDEX "BomCostingReferenceSyncRun_status_startedAt_idx" ON "BomCostingReferenceSyncRun"("status", "startedAt"); +CREATE INDEX "BomCostingReferenceSyncRun_status_completedAt_idx" ON "BomCostingReferenceSyncRun"("status", "completedAt"); +CREATE INDEX "BomCostingReferenceSyncRun_completedAt_idx" ON "BomCostingReferenceSyncRun"("completedAt"); +CREATE INDEX "BomCostingReferenceSyncRun_batchKey_idx" ON "BomCostingReferenceSyncRun"("batchKey"); +CREATE INDEX "BomCostingReferenceRow_sku_category_material_idx" ON "BomCostingReferenceRow"("sourceSku", "categoryCode", "materialName"); +CREATE INDEX "BomCostingReferenceRow_material_spec_unit_idx" ON "BomCostingReferenceRow"("materialName", "materialSpec", "unit"); +CREATE INDEX "BomCostingReferenceRow_syncRunId_sku_category_material_idx" ON "BomCostingReferenceRow"("syncRunId", "sourceSku", "categoryCode", "materialName"); +CREATE INDEX "BomCostingReferenceRow_syncRunId_material_spec_unit_idx" ON "BomCostingReferenceRow"("syncRunId", "materialName", "materialSpec", "unit"); +CREATE INDEX "BomCostingReferenceRow_syncRunId_category_part_number_idx" ON "BomCostingReferenceRow"("syncRunId", "categoryCode", "partNumber"); +CREATE INDEX "BomCostingReferenceRow_syncRunId_category_dimensions_idx" ON "BomCostingReferenceRow"("syncRunId", "categoryCode", "lengthMm", "widthMm"); +CREATE INDEX "BomCostingReferenceRow_syncRunId_idx" ON "BomCostingReferenceRow"("syncRunId"); +CREATE INDEX "BomCostingReferenceRow_syncRunId_summary_category_idx" ON "BomCostingReferenceRow"("syncRunId", "isSummaryRow", "categoryCode"); +CREATE INDEX "BomCostingReferenceRow_sourceCreatedAt_idx" ON "BomCostingReferenceRow"("sourceCreatedAt"); +CREATE UNIQUE INDEX "BomCostingMaterialOption_code_key" ON "BomCostingMaterialOption"("code"); +CREATE INDEX "BomCostingMaterialOption_enabled_sortOrder_idx" ON "BomCostingMaterialOption"("enabled", "sortOrder"); +CREATE INDEX "BomCostingMaterialOption_normalizedName_idx" ON "BomCostingMaterialOption"("normalizedName"); +CREATE UNIQUE INDEX "BomCostingScenario_sku_kind_scenarioKey_revision_key" ON "BomCostingScenario"("skuId", "kind", "scenarioKey", "revision"); +CREATE INDEX "BomCostingScenario_caseId_kind_idx" ON "BomCostingScenario"("caseId", "kind"); +CREATE INDEX "BomCostingScenario_skuId_isCurrent_updatedAt_idx" ON "BomCostingScenario"("skuId", "isCurrent", "updatedAt"); +CREATE INDEX "BomCostingScenario_status_dataAsOf_idx" ON "BomCostingScenario"("status", "dataAsOf"); +CREATE INDEX "BomCostingScenario_syncRunId_idx" ON "BomCostingScenario"("syncRunId"); +CREATE INDEX "BomCostingScenarioLine_scenarioId_category_idx" ON "BomCostingScenarioLine"("scenarioId", "category"); +CREATE INDEX "BomCostingScenarioLine_sourceRowId_idx" ON "BomCostingScenarioLine"("sourceRowId"); +CREATE INDEX "BomCostingScenarioLine_status_idx" ON "BomCostingScenarioLine"("status"); + +-- Material choices are a read-only projection of the company's enabled +-- substrate dictionary. The scheduled mirror refresh keeps this projection +-- current; this initial insert prevents a newly migrated environment from +-- exposing an empty selector when the master data already exists. +INSERT INTO "BomCostingMaterialOption" ( + "id", "code", "name", "normalizedName", "category", "aliases", "enabled", "sortOrder", "updatedAt" +) +SELECT + 'bom-material-' || "id", + 'SUBSTRATE_SYSTEM_NAME:' || "id", + "name", + lower(regexp_replace("name", '\s+', '', 'g')), + 'BOARD', + jsonb_build_array("name"), + "isActive", + "sortOrder", + CURRENT_TIMESTAMP +FROM "SubstrateSystemNameOption" +ON CONFLICT ("code") DO UPDATE SET + "name" = EXCLUDED."name", + "normalizedName" = EXCLUDED."normalizedName", + "aliases" = EXCLUDED."aliases", + "enabled" = EXCLUDED."enabled", + "sortOrder" = EXCLUDED."sortOrder", + "updatedAt" = CURRENT_TIMESTAMP; + +ALTER TABLE "BomCostingReferenceRow" + ADD CONSTRAINT "BomCostingReferenceRow_syncRunId_fkey" + FOREIGN KEY ("syncRunId") REFERENCES "BomCostingReferenceSyncRun"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "BomCostingScenario" + ADD CONSTRAINT "BomCostingScenario_caseId_fkey" + FOREIGN KEY ("caseId") REFERENCES "BomCostingCase"("id") ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT "BomCostingScenario_skuId_fkey" + FOREIGN KEY ("skuId") REFERENCES "BomCostingSku"("id") ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT "BomCostingScenario_targetMaterialId_fkey" + FOREIGN KEY ("targetMaterialId") REFERENCES "BomCostingMaterialOption"("id") ON DELETE SET NULL ON UPDATE CASCADE, + ADD CONSTRAINT "BomCostingScenario_syncRunId_fkey" + FOREIGN KEY ("syncRunId") REFERENCES "BomCostingReferenceSyncRun"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +ALTER TABLE "BomCostingScenarioLine" + ADD CONSTRAINT "BomCostingScenarioLine_scenarioId_fkey" + FOREIGN KEY ("scenarioId") REFERENCES "BomCostingScenario"("id") ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT "BomCostingScenarioLine_sourceLineId_fkey" + FOREIGN KEY ("sourceLineId") REFERENCES "BomCostingLine"("id") ON DELETE SET NULL ON UPDATE CASCADE; diff --git a/furniture-3d-system/prisma/migrations/20260809160000_update_bom_cost_ruleset_default/migration.sql b/furniture-3d-system/prisma/migrations/20260809160000_update_bom_cost_ruleset_default/migration.sql new file mode 100644 index 00000000..1a4e5671 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20260809160000_update_bom_cost_ruleset_default/migration.sql @@ -0,0 +1,2 @@ +ALTER TABLE "BomCostingScenario" + ALTER COLUMN "rulesetVersion" SET DEFAULT 'dynamic-bom-cost/v3'; diff --git a/furniture-3d-system/prisma/schema.prisma b/furniture-3d-system/prisma/schema.prisma index a8273de5..fdb96629 100644 --- a/furniture-3d-system/prisma/schema.prisma +++ b/furniture-3d-system/prisma/schema.prisma @@ -269,24 +269,24 @@ model IntakeNonIntegratedProduct { } model BarcodePrintImportRecord { - id String @id @default(cuid()) - kind String + id String @id @default(cuid()) + kind String // System-created barcode rows point to their pricing-row source. Imported // rows keep this null, so identical Excel rows remain independently valid. - sourcePricingRowId String? @unique - skuCode String - normalizedSku String - supplierCode String @default("") - supplierName String @default("") - normalizedSupplierName String @default("") - sourceFileName String @default("") - rowNumber Int @default(0) - importedAt DateTime @default(now()) - updates Json - createdBy String - creator User @relation("BarcodePrintImportRecordCreator", fields: [createdBy], references: [id], onDelete: Cascade) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + sourcePricingRowId String? @unique + skuCode String + normalizedSku String + supplierCode String @default("") + supplierName String @default("") + normalizedSupplierName String @default("") + sourceFileName String @default("") + rowNumber Int @default(0) + importedAt DateTime @default(now()) + updates Json + createdBy String + creator User @relation("BarcodePrintImportRecordCreator", fields: [createdBy], references: [id], onDelete: Cascade) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt @@index([kind]) @@index([normalizedSku]) @@ -792,6 +792,7 @@ model BomCostingCase { taskEvents BomCostingTaskEvent[] analysisRuns BomCostingAnalysisRun[] reviewInputs BomCostingReviewInput[] + scenarios BomCostingScenario[] @@index([createdById, deletedAt, createdAt]) @@index([status, deletedAt]) @@ -943,6 +944,7 @@ model BomCostingSku { bomLines BomCostingLine[] reviewInputs BomCostingReviewInput[] + scenarios BomCostingScenario[] @@unique([caseId, externalSkuId]) @@index([caseId, sortOrder]) @@ -984,6 +986,7 @@ model BomCostingLine { priceSnapshots BomCostingPriceSnapshot[] reviewInputs BomCostingReviewInput[] + scenarioLines BomCostingScenarioLine[] @@unique([skuId, externalLineId]) @@index([skuId, sortOrder]) @@ -1062,6 +1065,200 @@ model BomCostingTaskEvent { @@index([providerTaskId]) } +// Local, auditable mirror of the upstream rpt.pm_bomBaseInfo view. The +// costing request path only reads these rows; the SQL Server source is used by +// the scheduled sync job and never by a user request. +model BomCostingReferenceSyncRun { + id String @id @default(cuid()) + sourceSystem String @default("JSReportReplica") + sourceDatabase String @default("") + sourceSchema String @default("rpt") + sourceObject String @default("pm_bomBaseInfo") + status BomCostingReferenceSyncStatus @default(RUNNING) + batchKey String @default("") + configFingerprint String @default("") @db.VarChar(64) + cursorStart String @default("") + cursorEnd String @default("") + rowsRead Int @default(0) + rowsWritten Int @default(0) + rowsCreated Int @default(0) + rowsUpdated Int @default(0) + rowsUnchanged Int @default(0) + rowsSkipped Int @default(0) + errorCount Int @default(0) + errorMessage String @default("") @db.Text + durationMs Int @default(0) + startedAt DateTime @default(now()) + completedAt DateTime? + sourceAsOf DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + referenceRows BomCostingReferenceRow[] + scenarios BomCostingScenario[] + + @@index([status, startedAt]) + @@index([status, completedAt]) + @@index([completedAt]) + @@index([batchKey]) +} + +model BomCostingReferenceRow { + id String @id @default(cuid()) + sourceRowId String + sourceSku String @default("") + bomVersionKey String @default("") + category String @default("") + categoryCode String @default("") + partNumber String @default("") + partName String @default("") + side String @default("") + materialName String @default("") + materialCode String @default("") + materialSpec String @default("") + processName String @default("") + unit String @default("") + rawLength String @default("") + rawWidth String @default("") + rawLongEdge String @default("") + rawShortEdge String @default("") + rawQuantity String @default("") + rawCoefficient String @default("") + rawArea String @default("") + rawEdgeLength String @default("") + rawUnitPrice String @default("") + rawAmount String @default("") + rawNote String @default("") @db.Text + rawCreatedAt String @default("") + lengthMm Decimal? @db.Decimal(18, 6) + widthMm Decimal? @db.Decimal(18, 6) + longEdgeMm Decimal? @db.Decimal(18, 6) + shortEdgeMm Decimal? @db.Decimal(18, 6) + quantity Decimal? @db.Decimal(18, 6) + coefficient Decimal? @db.Decimal(18, 6) + areaSqm Decimal? @db.Decimal(18, 6) + edgeLengthM Decimal? @db.Decimal(18, 6) + unitPrice Decimal? @db.Decimal(18, 6) + amount Decimal? @db.Decimal(18, 6) + sourceCreatedAt DateTime? + sourceFingerprint String @db.VarChar(64) + isSummaryRow Boolean @default(false) + syncRunId String + syncRun BomCostingReferenceSyncRun @relation(fields: [syncRunId], references: [id], onDelete: Cascade) + syncedAt DateTime @default(now()) + + // A run is written as an isolated snapshot so failed/new runs cannot mutate + // the visible batch. After activation, only the newest operational mirror is + // retained; scenario lines keep immutable historical calculation snapshots. + @@unique([syncRunId, sourceRowId, sourceSku, bomVersionKey], map: "BomCostingReferenceRow_source_key") + @@index([syncRunId, sourceSku, categoryCode, materialName], map: "BomCostingReferenceRow_syncRunId_sku_category_material_idx") + @@index([syncRunId, materialName, materialSpec, unit], map: "BomCostingReferenceRow_syncRunId_material_spec_unit_idx") + @@index([syncRunId, categoryCode, partNumber], map: "BomCostingReferenceRow_syncRunId_category_part_number_idx") + @@index([syncRunId, categoryCode, lengthMm, widthMm], map: "BomCostingReferenceRow_syncRunId_category_dimensions_idx") + @@index([sourceSku, categoryCode, materialName], map: "BomCostingReferenceRow_sku_category_material_idx") + @@index([materialName, materialSpec, unit], map: "BomCostingReferenceRow_material_spec_unit_idx") + @@index([syncRunId]) + @@index([syncRunId, isSummaryRow, categoryCode], map: "BomCostingReferenceRow_syncRunId_summary_category_idx") + @@index([sourceCreatedAt]) +} + +model BomCostingMaterialOption { + id String @id @default(cuid()) + code String @unique + name String + normalizedName String + category String @default("BOARD") + aliases Json @default("[]") + enabled Boolean @default(true) + sortOrder Int @default(0) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + substitutionScenarios BomCostingScenario[] + + @@index([enabled, sortOrder]) + @@index([normalizedName]) +} + +model BomCostingScenario { + id String @id @default(cuid()) + caseId String + case BomCostingCase @relation(fields: [caseId], references: [id], onDelete: Cascade) + skuId String + sku BomCostingSku @relation(fields: [skuId], references: [id], onDelete: Cascade) + kind BomCostingScenarioKind + scenarioKey String @default("") + revision Int @default(1) + isCurrent Boolean @default(true) + targetMaterialId String? + targetMaterial BomCostingMaterialOption? @relation(fields: [targetMaterialId], references: [id], onDelete: SetNull) + targetMaterialName String @default("") + status BomCostingScenarioStatus @default(PROVISIONAL) + totalCost Decimal? @db.Decimal(18, 2) + knownCost Decimal? @db.Decimal(18, 2) + materialCost Decimal? @db.Decimal(18, 2) + processingCost Decimal? @db.Decimal(18, 2) + laborCost Decimal? @db.Decimal(18, 2) + packagingCost Decimal? @db.Decimal(18, 2) + lossCost Decimal? @db.Decimal(18, 2) + competitorPrice Decimal? @db.Decimal(18, 2) + priceDelta Decimal? @db.Decimal(18, 2) + confidence Decimal? @db.Decimal(5, 4) + warning String @default("") @db.Text + unresolvedCount Int @default(0) + dataAsOf DateTime? + syncRunId String? + syncRun BomCostingReferenceSyncRun? @relation(fields: [syncRunId], references: [id], onDelete: SetNull) + rulesetVersion String @default("dynamic-bom-cost/v3") + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + lines BomCostingScenarioLine[] + + @@unique([skuId, kind, scenarioKey, revision], map: "BomCostingScenario_sku_kind_scenarioKey_revision_key") + @@index([caseId, kind]) + @@index([skuId, isCurrent, updatedAt]) + @@index([status, dataAsOf]) + @@index([syncRunId]) +} + +model BomCostingScenarioLine { + id String @id @default(cuid()) + scenarioId String + scenario BomCostingScenario @relation(fields: [scenarioId], references: [id], onDelete: Cascade) + sourceLineId String? + sourceLine BomCostingLine? @relation(fields: [sourceLineId], references: [id], onDelete: SetNull) + sourceRowId String @default("") + category String @default("") + partName String @default("") + originalMaterial String @default("") + appliedMaterial String @default("") + materialSpec String @default("") + unit String @default("") + quantity Decimal? @db.Decimal(18, 6) + coefficient Decimal? @db.Decimal(18, 6) + pricingQuantity Decimal? @db.Decimal(18, 6) + unitPrice Decimal? @db.Decimal(18, 6) + subtotal Decimal? @db.Decimal(18, 2) + priceSource String @default("") + sourceSku String @default("") + referenceSkus Json @default("[]") + referenceRowIds Json @default("[]") + sourceFingerprint String @default("") @db.VarChar(64) + sourceCreatedAt DateTime? + sourceSyncedAt DateTime? + calculationRule String @default("") + confidence Decimal? @db.Decimal(5, 4) + status BomCostingScenarioStatus @default(PROVISIONAL) + warning String @default("") @db.Text + rawSnapshot Json? + createdAt DateTime @default(now()) + + @@index([scenarioId, category]) + @@index([sourceRowId]) + @@index([status]) +} + // ============================================ // 装配相关 // ============================================ @@ -2106,6 +2303,24 @@ enum BomCostingReviewInputSource { LIBRARY_MATCH } +enum BomCostingReferenceSyncStatus { + RUNNING + SUCCEEDED + FAILED +} + +enum BomCostingScenarioKind { + SAME_MATERIAL + MATERIAL_SUBSTITUTION +} + +enum BomCostingScenarioStatus { + FINAL + PROVISIONAL + INSUFFICIENT_DATA + STALE +} + enum ApprovalWorkflowStatus { DRAFT PENDING diff --git a/furniture-3d-system/scripts/backtest-bom-cost-reference.ts b/furniture-3d-system/scripts/backtest-bom-cost-reference.ts new file mode 100644 index 00000000..067ddf49 --- /dev/null +++ b/furniture-3d-system/scripts/backtest-bom-cost-reference.ts @@ -0,0 +1,197 @@ +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()({ + 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() + 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 +}) diff --git a/furniture-3d-system/scripts/install-bom-cost-reference-sync-timer.sh b/furniture-3d-system/scripts/install-bom-cost-reference-sync-timer.sh new file mode 100644 index 00000000..afc0de36 --- /dev/null +++ b/furniture-3d-system/scripts/install-bom-cost-reference-sync-timer.sh @@ -0,0 +1,116 @@ +#!/usr/bin/env bash +set -euo pipefail + +BASE="${FURNITURE_PROD_BASE:-/opt/furniture-3d-system-prod}" +SERVICE_NAME="${BOM_COST_REFERENCE_SYNC_SERVICE_NAME:-furniture-bom-cost-reference-sync}" +APP_ROOT="$BASE/current/furniture-3d-system" +SHARED="$BASE/shared" +APP_ENV="$SHARED/.env" +SYNC_ENV="$SHARED/bom-cost-reference-sync.env" +SERVICE_FILE="/etc/systemd/system/$SERVICE_NAME.service" +TIMER_FILE="/etc/systemd/system/$SERVICE_NAME.timer" +SYNC_CALENDAR="${BOM_COST_REFERENCE_SYNC_CALENDAR:-*-*-* 02:00:00 Asia/Shanghai}" +RANDOMIZED_DELAY_SEC="${BOM_COST_REFERENCE_SYNC_RANDOMIZED_DELAY_SEC:-10min}" + +if [ "$(id -u)" -ne 0 ]; then + echo "This installer must run as root." >&2 + exit 1 +fi + +if [ ! -d "$APP_ROOT" ]; then + echo "Missing app root: $APP_ROOT" >&2 + exit 1 +fi + +if [ ! -f "$APP_ENV" ]; then + echo "Missing app env: $APP_ENV" >&2 + exit 1 +fi + +mkdir -p "$SHARED" +if [ ! -f "$SYNC_ENV" ]; then + umask 077 + cat >"$SYNC_ENV" <<'EOF' +# Company BOM cost reference mirror controls. The SQL Server report_reader +# connection stays in shared/.env under JST_PLANNING_SQLSERVER_*. +BOM_COSTING_EXPECTED_DATABASE_IDENTITY= +BOM_COSTING_EXPECTED_SOURCE_DATABASE_IDENTITY= +BOM_COSTING_REFERENCE_PAGE_SIZE=100 +BOM_COSTING_REFERENCE_PAGE_DELAY_MS=250 +BOM_COSTING_REFERENCE_MAX_AGE_DAYS=2 +EOF + echo "Created env template: $SYNC_ENV" +fi + +chmod 600 "$SYNC_ENV" + +required_values=( + BOM_COSTING_EXPECTED_DATABASE_IDENTITY + BOM_COSTING_EXPECTED_SOURCE_DATABASE_IDENTITY +) +for name in "${required_values[@]}"; do + if ! grep -Eq "^${name}=.+$" "$SYNC_ENV"; then + echo "Missing $name in $SYNC_ENV; timer was not installed." >&2 + exit 2 + fi +done + +required_app_values=( + DATABASE_URL + JST_PLANNING_SQLSERVER_HOST + JST_PLANNING_SQLSERVER_DATABASE + JST_PLANNING_SQLSERVER_USERNAME + JST_PLANNING_SQLSERVER_PASSWORD +) +for name in "${required_app_values[@]}"; do + if ! grep -Eq "^${name}=.+$" "$APP_ENV"; then + echo "Missing $name in $APP_ENV; timer was not installed." >&2 + exit 2 + fi +done +if ! grep -Eq "^JST_PLANNING_SQLSERVER_USERNAME=(report_reader|\"report_reader\"|'report_reader')$" "$APP_ENV"; then + echo "JST_PLANNING_SQLSERVER_USERNAME must be report_reader; timer was not installed." >&2 + exit 2 +fi + +if command -v systemd-analyze >/dev/null 2>&1; then + systemd-analyze calendar "$SYNC_CALENDAR" >/dev/null +fi + +cat >"$SERVICE_FILE" <"$TIMER_FILE" < bounds.max) { + throw new Error(`${prefix.slice(0, -1)} must be an integer between ${bounds.min} and ${bounds.max}`) + } + return value +} + +function parseArgs(argv: string[]): CliOptions { + const options: CliOptions = { + apply: false, + allowLargeRemoval: false, + confirm: '', + expectedDatabaseIdentity: '', + expectedSourceDatabaseIdentity: '', + maxPages: undefined, + maxRetries: undefined, + startAfterId: '0', + resumeBatchId: '', + help: false, + } + for (const arg of argv) { + if (arg === '--apply') options.apply = true + else if (arg === '--dry-run') options.apply = false + else if (arg === '--allow-large-removal') options.allowLargeRemoval = true + else if (arg === '--help' || arg === '-h') options.help = true + else if (arg.startsWith('--confirm=')) options.confirm = arg.slice('--confirm='.length) + else if (arg.startsWith('--expected-database-identity=')) { + options.expectedDatabaseIdentity = arg.slice('--expected-database-identity='.length) + } else if (arg.startsWith('--expected-source-database-identity=')) { + options.expectedSourceDatabaseIdentity = arg.slice('--expected-source-database-identity='.length) + } else if (arg.startsWith('--max-pages=')) { + options.maxPages = parseIntegerOption(arg, '--max-pages=', { min: 1, max: 10_000 }) + } else if (arg.startsWith('--max-retries=')) { + options.maxRetries = parseIntegerOption(arg, '--max-retries=', { min: 0, max: 10 }) + } else if (arg.startsWith('--start-after-id=')) { + const value = arg.slice('--start-after-id='.length).trim() + if (!/^\d+$/.test(value)) throw new Error('--start-after-id must be a non-negative integer') + options.startAfterId = BigInt(value).toString() + } else if (arg.startsWith('--resume-batch-id=')) { + const value = arg.slice('--resume-batch-id='.length).trim() + if (!value || value.length > 200 || !/^[A-Za-z0-9_-]+$/.test(value)) { + throw new Error('--resume-batch-id is invalid') + } + options.resumeBatchId = value + } else { + throw new Error(`Unknown argument: ${arg}`) + } + } + if (argv.includes('--apply') && argv.includes('--dry-run')) { + throw new Error('Cannot pass --apply and --dry-run together') + } + if (!options.apply && options.allowLargeRemoval) { + throw new Error('--allow-large-removal requires --apply') + } + if (options.apply && options.maxPages !== undefined) { + throw new Error('--max-pages is dry-run only; apply must scan the complete source') + } + if (options.apply && options.startAfterId !== '0') { + throw new Error('--start-after-id is dry-run only; apply must start at zero') + } + if (!options.apply && options.resumeBatchId) { + throw new Error('--resume-batch-id requires --apply') + } + return options +} + +function databaseIdentityFromUrl(databaseUrl: string) { + const parsed = new URL(databaseUrl) + return [ + parsed.protocol.replace(/:$/, ''), + decodeURIComponent(parsed.username || ''), + parsed.hostname, + parsed.port || '', + parsed.pathname.replace(/^\//, ''), + parsed.searchParams.get('schema') ?? '', + ].join('|') +} + +export function sourceDatabaseIdentity(env: NodeJS.ProcessEnv = process.env) { + const host = ( + env.BOM_COSTING_UPSTREAM_HOST || + env.JST_PLANNING_SQLSERVER_HOST || + env.JST_REPORT_DB_HOST || + '' + ).trim() + const database = ( + env.BOM_COSTING_UPSTREAM_DATABASE || + env.JST_PLANNING_SQLSERVER_DATABASE || + env.JST_REPORT_DB_NAME || + '' + ).trim() + const user = ( + env.BOM_COSTING_UPSTREAM_USER || + env.JST_PLANNING_SQLSERVER_USERNAME || + env.JST_REPORT_DB_USER || + '' + ).trim() + if (!host || !database || !user) return '' + return [ + 'sqlserver', + user, + host, + ( + env.BOM_COSTING_UPSTREAM_PORT || + env.JST_PLANNING_SQLSERVER_PORT || + env.JST_REPORT_DB_PORT || + '1433' + ).trim(), + database, + ( + env.BOM_COSTING_UPSTREAM_SCHEMA || + env.JST_PLANNING_SQLSERVER_SCHEMA || + env.JST_REPORT_DB_SCHEMA || + 'rpt' + ).trim(), + (env.BOM_COSTING_UPSTREAM_OBJECT || 'pm_bomBaseInfo').trim(), + ].join('|') +} + +export function assertApplyGuards( + options: CliOptions, + env: NodeJS.ProcessEnv = process.env, +) { + if (!options.apply) return + if (options.confirm !== BOM_REFERENCE_SYNC_CONFIRM) { + throw new Error( + `真实写库必须显式传入 --confirm=${BOM_REFERENCE_SYNC_CONFIRM}。`, + ) + } + + const databaseUrl = env.DATABASE_URL?.trim() ?? '' + if (!databaseUrl) throw new Error('真实写库必须先配置 DATABASE_URL。') + const actualDatabaseIdentity = databaseIdentityFromUrl(databaseUrl) + if (!options.expectedDatabaseIdentity) { + throw new Error( + `真实写库必须显式传入 --expected-database-identity=${actualDatabaseIdentity}。`, + ) + } + if (options.expectedDatabaseIdentity !== actualDatabaseIdentity) { + throw new Error('目标 PostgreSQL 身份与 DATABASE_URL 不一致,禁止写库。') + } + + const actualSourceIdentity = sourceDatabaseIdentity(env) + if (!actualSourceIdentity) { + throw new Error( + '真实写库必须先配置 BOM_COSTING_UPSTREAM_*、' + + 'JST_PLANNING_SQLSERVER_* 或 JST_REPORT_DB_*。', + ) + } + if (!options.expectedSourceDatabaseIdentity) { + throw new Error( + `真实写库必须显式传入 --expected-source-database-identity=${actualSourceIdentity}。`, + ) + } + if (options.expectedSourceDatabaseIdentity !== actualSourceIdentity) { + throw new Error('来源 SQL Server 身份与当前上游配置不一致,禁止写库。') + } +} + +function printHelp() { + console.log(` +Usage: + npm run sync:bom-cost-reference -- --dry-run + npm run sync:bom-cost-reference -- --dry-run --max-pages=2 --start-after-id=0 + npm run sync:bom-cost-reference -- --apply --confirm=${BOM_REFERENCE_SYNC_CONFIRM} --expected-database-identity=... --expected-source-database-identity=... + npm run sync:bom-cost-reference -- --apply --resume-batch-id= --confirm=${BOM_REFERENCE_SYNC_CONFIRM} --expected-database-identity=... --expected-source-database-identity=... + +默认只做低压只读预览。默认每页 100 行,并在完整页之间等待 250ms;可用 BOM_COSTING_REFERENCE_PAGE_SIZE / BOM_COSTING_REFERENCE_PAGE_DELAY_MS 做受限调整,不提供并发。 +只读预览可用 --max-pages 限定页数、用 --start-after-id 从已记录游标续查;完整页触顶时结果会标记 complete=false。 +分页读取默认自动重试 2 次,可用 --max-retries=0..10 调整。apply 按页写入不可见新快照,全部成功后切换;失败批次可用 --resume-batch-id 从持久化游标继续,旧成功快照始终可读。 +真实写库还会校验 SQL Server 登录是否没有 INSERT/UPDATE/DELETE/EXECUTE/DDL 权限。 +来源配置优先使用 BOM_COSTING_UPSTREAM_*;未设置时优先复用现有 +JST_PLANNING_SQLSERVER_* 的 report_reader,最后才兼容 JST_REPORT_DB_*: + BOM_COSTING_UPSTREAM_HOST / DATABASE / USER / PASSWORD + BOM_COSTING_UPSTREAM_SCHEMA=rpt + BOM_COSTING_UPSTREAM_OBJECT=pm_bomBaseInfo + BOM_COSTING_UPSTREAM_ID_COLUMN=Id +`.trim()) +} + +async function main() { + const options = parseArgs(process.argv.slice(2)) + if (options.help) { + printHelp() + return + } + assertApplyGuards(options) + + const [ + { readUpstreamBomReferenceConfig, MssqlUpstreamBomReferenceSource }, + { PrismaBomReferenceMirrorStore, PostgresBomReferenceSyncLock }, + { UpstreamBomReferenceSyncService }, + { prisma }, + ] = await Promise.all([ + import('../src/server/services/bom-costing/upstream-bom-reference-source'), + import('../src/server/services/bom-costing/upstream-bom-reference-store'), + import('../src/server/services/bom-costing/upstream-bom-reference-sync.service'), + import('../src/lib/prisma'), + ]) + + const source = new MssqlUpstreamBomReferenceSource(readUpstreamBomReferenceConfig()) + const service = new UpstreamBomReferenceSyncService( + source, + new PrismaBomReferenceMirrorStore(prisma), + new PostgresBomReferenceSyncLock(), + ) + try { + const result = await service.sync({ + apply: options.apply, + allowLargeRemoval: options.allowLargeRemoval, + maxPages: options.maxPages, + maxRetries: options.maxRetries, + startAfterId: options.startAfterId, + resumeBatchId: options.resumeBatchId, + onPage: (progress) => console.log(JSON.stringify({ progress })), + }) + console.log(JSON.stringify(result, null, 2)) + } finally { + await prisma.$disconnect() + } +} + +void main().catch((error) => { + console.error(`BOM reference sync failed: ${error instanceof Error ? error.message : String(error)}`) + process.exitCode = 1 +}) diff --git a/furniture-3d-system/src/app/api/bom-costing/cases/[id]/route.ts b/furniture-3d-system/src/app/api/bom-costing/cases/[id]/route.ts index dbd1b4c2..f30bd9a1 100644 --- a/furniture-3d-system/src/app/api/bom-costing/cases/[id]/route.ts +++ b/furniture-3d-system/src/app/api/bom-costing/cases/[id]/route.ts @@ -2,6 +2,7 @@ import { NextRequest } from 'next/server' import { AppError } from '@/server/core/errors' import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' import { bomCostingService } from '@/server/services/bom-costing/bom-costing.service' +import { bomCostingScenarioService } from '@/server/services/bom-costing/bom-costing-scenario.service' type RouteContext = { params: Promise<{ id: string }> @@ -13,8 +14,14 @@ export async function GET(request: NextRequest, context: RouteContext) { async (ctx) => { const { id } = await context.params try { + const caseDetail = await bomCostingService.getCase(decodeURIComponent(id), ctx.user) return jsonSuccess( - { case: await bomCostingService.getCase(decodeURIComponent(id), ctx.user) }, + { + case: { + ...caseDetail, + dynamicCosting: await bomCostingScenarioService.getCaseDynamicCosting(caseDetail.id), + }, + }, 200, ctx.requestId, ) diff --git a/furniture-3d-system/src/app/api/bom-costing/cases/[id]/scenarios/route.ts b/furniture-3d-system/src/app/api/bom-costing/cases/[id]/scenarios/route.ts new file mode 100644 index 00000000..ad299951 --- /dev/null +++ b/furniture-3d-system/src/app/api/bom-costing/cases/[id]/scenarios/route.ts @@ -0,0 +1,59 @@ +import { NextRequest } from 'next/server' +import { bomCostingScenarioCalculationSchema } from '@/lib/bom-costing/contracts' +import { AppError, ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { bomCostingService } from '@/server/services/bom-costing/bom-costing.service' +import { bomCostingScenarioService } from '@/server/services/bom-costing/bom-costing-scenario.service' + +type RouteContext = { params: Promise<{ id: string }> } + +export async function GET(request: NextRequest, context: RouteContext) { + return handleRequest( + request, + async (ctx) => { + const { id } = await context.params + const caseId = decodeURIComponent(id) + const skuId = request.nextUrl.searchParams.get('skuId')?.trim() || undefined + try { + await bomCostingService.getCase(caseId, ctx.user) + return jsonSuccess( + { scenarios: await bomCostingScenarioService.listScenarios({ caseId, skuId }) }, + 200, + ctx.requestId, + ) + } catch (error) { + if (error instanceof AppError) { + return jsonError(error.code, error.message, error.statusCode, ctx.requestId) + } + throw error + } + }, + { requireAuth: true }, + ) +} + +export async function POST(request: NextRequest, context: RouteContext) { + return handleRequest( + request, + async (ctx) => { + const { id } = await context.params + const caseId = decodeURIComponent(id) + const body = await request.json().catch(() => null) + const parsed = bomCostingScenarioCalculationSchema.safeParse(body) + if (!parsed.success) { + return jsonError(ErrorCode.VALIDATION_FAILED, '目标材质参数不正确', 400, ctx.requestId) + } + try { + await bomCostingService.getCase(caseId, ctx.user) + const result = await bomCostingScenarioService.calculate({ caseId, ...parsed.data }) + return jsonSuccess(result, 200, ctx.requestId) + } catch (error) { + if (error instanceof AppError) { + return jsonError(error.code, error.message, error.statusCode, ctx.requestId) + } + throw error + } + }, + { requireAuth: true }, + ) +} diff --git a/furniture-3d-system/src/app/api/bom-costing/materials/route.ts b/furniture-3d-system/src/app/api/bom-costing/materials/route.ts new file mode 100644 index 00000000..63b24860 --- /dev/null +++ b/furniture-3d-system/src/app/api/bom-costing/materials/route.ts @@ -0,0 +1,40 @@ +import { NextRequest } from 'next/server' +import { AppError } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { bomCostingAccessService } from '@/server/services/bom-costing/bom-costing-access.service' +import { bomCostingScenarioService } from '@/server/services/bom-costing/bom-costing-scenario.service' + +export async function GET(request: NextRequest) { + return handleRequest( + request, + async (ctx) => { + try { + bomCostingAccessService.assertCanView(ctx.user) + const [materials, sync] = await Promise.all([ + bomCostingScenarioService.listMaterials(), + bomCostingScenarioService.getSyncFreshness(), + ]) + return jsonSuccess( + { + materials: materials.map((material) => ({ + id: material.id, + code: material.code, + name: material.name, + category: material.category, + enabled: material.enabled, + })), + sync, + }, + 200, + ctx.requestId, + ) + } catch (error) { + if (error instanceof AppError) { + return jsonError(error.code, error.message, error.statusCode, ctx.requestId) + } + throw error + } + }, + { requireAuth: true }, + ) +} diff --git a/furniture-3d-system/src/app/bom-costing/BomCostingWorkbenchClient.test.tsx b/furniture-3d-system/src/app/bom-costing/BomCostingWorkbenchClient.test.tsx index 9262ba3b..2839f9f2 100644 --- a/furniture-3d-system/src/app/bom-costing/BomCostingWorkbenchClient.test.tsx +++ b/furniture-3d-system/src/app/bom-costing/BomCostingWorkbenchClient.test.tsx @@ -1,4 +1,4 @@ -import { fireEvent, render, screen, waitFor, within } from '@testing-library/react' +import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react' import BomCostingWorkbenchClient from './BomCostingWorkbenchClient' jest.mock('@/components/platform/AssetWorkbenchEmptyBackdrop', () => ({ @@ -6,6 +6,68 @@ jest.mock('@/components/platform/AssetWorkbenchEmptyBackdrop', () => ({ })) describe('BomCostingWorkbenchClient', () => { + it('详情读取超时后结束加载并提供重试入口', async () => { + const originalFetch = global.fetch + jest.useFakeTimers() + global.fetch = jest.fn((_input: RequestInfo | URL, init?: RequestInit) => ( + new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => { + const error = new Error('aborted') + error.name = 'AbortError' + reject(error) + }) + }) + )) as jest.Mock + + try { + render( + , + ) + + expect(screen.getByRole('status')).toHaveTextContent('正在读取核算记录') + await act(async () => { + jest.advanceTimersByTime(15_000) + await Promise.resolve() + await Promise.resolve() + }) + + const loadError = screen.getByRole('alert') + expect(loadError).toHaveTextContent('核算记录暂未读到') + expect( + within(loadError).getByText('核算记录读取超时,请重试;后台任务不会受影响'), + ).toBeInTheDocument() + expect(screen.getByRole('button', { name: '重新读取' })).toBeEnabled() + } finally { + jest.useRealTimers() + global.fetch = originalFetch + } + }) + it('生产服务未接入且没有案例时只展示紧凑入口', () => { render( { ) expect(screen.getByText('历史记录')).toBeInTheDocument() - expect(screen.getByLabelText('搜索历史记录')).toBeInTheDocument() - expect(screen.getByLabelText('筛选历史状态')).toBeInTheDocument() + const historySearch = screen.getByLabelText('搜索历史记录') + const historyFilter = screen.getByLabelText('筛选历史状态') + expect(historySearch).toBeInTheDocument() + expect(historyFilter).toBeInTheDocument() + expect(historySearch.closest('.mb-2')).not.toHaveClass('hidden') expect( await screen.findByText('多模态分析服务暂时不可用'), ).toBeInTheDocument() @@ -999,6 +1064,9 @@ describe('BomCostingWorkbenchClient', () => { ) expect(await screen.findByText('桌面板')).toBeInTheDocument() + const bomDetailTable = screen.getByRole('table', { name: 'BOM 核算明细' }) + expect(bomDetailTable).toHaveClass('block', 'md:table') + expect(screen.getByText('桌面板').closest('tr')).toHaveClass('grid', 'md:table-row') expect(screen.getByText('主图可见桌面板尺寸与材质')).toBeInTheDocument() expect(screen.getByText('预计出厂成本')).toBeInTheDocument() expect(screen.getByText('选择 SKU')).toBeInTheDocument() @@ -1283,13 +1351,22 @@ describe('BomCostingWorkbenchClient', () => { '只重新汇总结构、BOM 与资料库价格,复用已保存的逐图结果。', ) expect(reuseFactsExplanation.closest('[role="tooltip"]')).toHaveClass('sr-only') + fireEvent.click(screen.getByRole('button', { name: '查看按现有事实重算说明' })) + expect(reuseFactsExplanation.closest('[role="tooltip"]')).not.toHaveClass('sr-only') expect( - screen.getByText('不读取竞品资料 · 不调用图片模型 · 仅汇总实际 SKU'), + screen.getByText('重看 1 张图片'), ).toBeInTheDocument() fireEvent.click( - screen.getByRole('button', { name: '查看按现有事实重算说明' }), + screen.getByRole('button', { name: '全部重新分析 重新读取 · 2 张图片' }), ) - expect(reuseFactsExplanation.closest('[role="tooltip"]')).not.toHaveClass('sr-only') + expect( + screen.getByText('重新读取 · 2 张图片'), + ).toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: '开始重新核算' })) + expect(screen.getByText('确认全部重新分析')).toBeInTheDocument() + expect(screen.getByRole('button', { name: '确认并开始' })).toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: '返回检查' })) + fireEvent.click(screen.getByRole('button', { name: '仅重试失败图片' })) expect(screen.getByText('已选 1 张')).toBeInTheDocument() fireEvent.change(screen.getByPlaceholderText(/重点核对折叠机构/), { target: { value: '重点核对折叠机构和导轨' }, @@ -1511,6 +1588,9 @@ describe('BomCostingWorkbenchClient', () => { fireEvent.click( screen.getByRole('button', { name: '记录橡胶木桌面板人工复核值' }), ) + expect(screen.getByText('材质与规格')).toBeInTheDocument() + expect(screen.getByText('部件尺寸')).toBeInTheDocument() + expect(screen.getByText('计价参数')).toBeInTheDocument() fireEvent.change(screen.getByLabelText('材质名称'), { target: { value: '橡胶木实木板' }, }) @@ -1575,4 +1655,383 @@ describe('BomCostingWorkbenchClient', () => { global.fetch = originalFetch } }) + + it('动态成本优先展示,并提交目标材质生成双场景且保留超售价金额', async () => { + const originalFetch = global.fetch + const now = new Date().toISOString() + const scenario = (input: { + id: string + kind: 'SAME_MATERIAL' | 'MATERIAL_SUBSTITUTION' + targetMaterialId: string | null + targetMaterialName: string + status: 'FINAL' | 'PROVISIONAL' | 'INSUFFICIENT_DATA' | 'STALE' + totalCost: number | null + knownCost: number + unresolvedCount: number + competitorPrice: number + priceDelta: number | null + unitPrice: number | null + subtotal: number | null + secondarySubtotal?: number + }) => ({ + id: input.id, + skuId: 'sku-dynamic', + kind: input.kind, + targetMaterialId: input.targetMaterialId, + targetMaterialName: input.targetMaterialName, + revision: 1, + isCurrent: true, + status: input.status, + totalCost: input.totalCost, + knownCost: input.knownCost, + materialCost: input.totalCost === null ? null : input.totalCost - 30, + processingCost: 10, + laborCost: 8, + packagingCost: 7, + lossCost: 5, + competitorPrice: input.competitorPrice, + priceDelta: input.priceDelta, + confidence: input.status === 'INSUFFICIENT_DATA' ? 0.62 : 0.82, + warning: input.priceDelta !== null && input.priceDelta > 0 + ? '成本高于竞品售价,需复核主要驱动项' + : '', + unresolvedCount: input.unresolvedCount, + dataAsOf: now, + syncRunId: 'run-success', + syncStatus: 'SUCCEEDED', + syncCompletedAt: now, + rulesetVersion: 'dynamic-bom-cost/v1', + createdAt: now, + lines: [{ + id: `${input.id}-line`, + sourceLineId: 'line-board', + sourceRowId: 'reference-board', + category: 'BOARD', + partName: '桌面板', + originalMaterial: '黑胡桃木', + appliedMaterial: input.kind === 'MATERIAL_SUBSTITUTION' ? '橡胶木' : '黑胡桃木', + materialSpec: '20 mm', + unit: 'm2', + quantity: 0.5, + coefficient: 1.1, + pricingQuantity: 0.5, + unitPrice: input.unitPrice, + subtotal: input.subtotal, + priceSource: input.unitPrice === null ? '' : '公司历史 BOM 中位单价', + sourceSku: 'REF-BOARD', + referenceSkus: input.unitPrice === null ? [] : ['REF-BOARD'], + referenceRowIds: input.unitPrice === null ? [] : ['reference-board'], + sourceFingerprint: input.unitPrice === null ? '' : 'fingerprint-board', + sourceCreatedAt: now, + sourceSyncedAt: now, + calculationRule: 'reference-weighted-median-unit-price/v1', + confidence: input.status === 'INSUFFICIENT_DATA' ? null : 0.82, + status: input.status === 'PROVISIONAL' ? 'FINAL' : input.status, + warning: input.unitPrice === null ? '没有公司价格来源' : '', + rawSnapshot: [], + }, ...(input.secondarySubtotal === undefined ? [] : [{ + id: `${input.id}-secondary-line`, + sourceLineId: 'line-processing', + sourceRowId: 'reference-processing', + category: 'PROCESSING', + partName: '表面处理', + originalMaterial: '木蜡油', + appliedMaterial: '木蜡油', + materialSpec: '', + unit: '套', + quantity: 1, + coefficient: 1, + pricingQuantity: 1, + unitPrice: input.secondarySubtotal, + subtotal: input.secondarySubtotal, + priceSource: '公司历史 BOM 单价', + sourceSku: 'REF-PROCESSING', + referenceSkus: ['REF-PROCESSING'], + referenceRowIds: ['reference-processing'], + sourceFingerprint: 'fingerprint-processing', + sourceCreatedAt: now, + sourceSyncedAt: now, + calculationRule: 'reference-weighted-median-unit-price/v1', + confidence: 0.82, + status: 'FINAL' as const, + warning: '', + rawSnapshot: [], + }])], + }) + const sync = { + state: 'READY' as const, + fresh: true, + dataAsOf: now, + sourceAsOf: now, + lastSuccessfulAt: new Date(Date.now() - 120_000).toISOString(), + lastSuccessfulBatchId: 'run-success', + lastFailedAt: new Date(Date.now() - 60_000).toISOString(), + lastFailedMessage: '上游连接超时', + maxAgeDays: 2, + } + const initialDynamicCosting = { + materials: [{ + id: 'material-rubberwood', + code: 'RUBBERWOOD', + name: '橡胶木', + category: 'BOARD', + aliases: ['rubberwood'], + }], + scenarios: [ + scenario({ + id: 'scenario-same-incomplete', + kind: 'SAME_MATERIAL', + targetMaterialId: null, + targetMaterialName: '', + status: 'INSUFFICIENT_DATA', + totalCost: null, + knownCost: 500, + unresolvedCount: 1, + competitorPrice: 600, + priceDelta: null, + unitPrice: null, + subtotal: null, + }), + scenario({ + id: 'scenario-substitution-old', + kind: 'MATERIAL_SUBSTITUTION', + targetMaterialId: 'material-rubberwood', + targetMaterialName: '橡胶木', + status: 'FINAL', + totalCost: 550, + knownCost: 550, + unresolvedCount: 0, + competitorPrice: 600, + priceDelta: -50, + unitPrice: 80, + subtotal: 44, + }), + ], + sync, + } + const updatedDynamicCosting = { + ...initialDynamicCosting, + scenarios: [ + scenario({ + id: 'scenario-same-updated', + kind: 'SAME_MATERIAL', + targetMaterialId: null, + targetMaterialName: '', + status: 'PROVISIONAL', + totalCost: 1_350, + knownCost: 1_350, + unresolvedCount: 0, + competitorPrice: 600, + priceDelta: 750, + unitPrice: 1_600, + subtotal: 800, + secondarySubtotal: 550, + }), + scenario({ + id: 'scenario-substitution-updated', + kind: 'MATERIAL_SUBSTITUTION', + targetMaterialId: 'material-rubberwood', + targetMaterialName: '橡胶木', + status: 'PROVISIONAL', + totalCost: 1_300, + knownCost: 1_300, + unresolvedCount: 0, + competitorPrice: 600, + priceDelta: 700, + unitPrice: 1_600, + subtotal: 800, + secondarySubtotal: 500, + }), + ], + } + const detail = { + id: 'case-dynamic', + sourceUrl: 'https://item.example.com/item?id=dynamic', + sourceHost: 'item.example.com', + title: '竞品实木书桌', + providerCode: 'market-detail-multimodal', + providerTaskId: 'task-dynamic', + sourceCacheHit: true, + status: 'READY', + progress: 100, + statusMessage: '核算完成', + targetErrorPercent: 10, + currency: 'CNY', + createdById: 'user-1', + processingStartedAt: now, + processingFinishedAt: now, + createdAt: now, + updatedAt: now, + sourceSnapshot: { + id: 'snapshot-dynamic', + status: 'READY', + channel: 'taobao', + externalItemId: 'dynamic', + title: '竞品实木书桌', + shopName: '竞品店铺', + skuCount: 1, + imageCount: 0, + storedImageCount: 0, + failedImageCount: 0, + errorMessage: '', + fetchedAt: now, + completedAt: now, + assets: [], + }, + skus: [{ + id: 'sku-dynamic', + externalSkuId: 'COMPETITOR-SKU-DYNAMIC', + name: '黑胡桃色 120cm', + structureGroupKey: 'desk', + imageUrl: null, + attributes: { marketPriceRaw: '600' }, + lengthMm: 1_200, + widthMm: 600, + heightMm: 750, + weightKg: null, + packageLengthMm: null, + packageWidthMm: null, + packageHeightMm: null, + packageWeightKg: null, + estimatedCost: 1_300, + costCalculatedAt: now, + costSummary: { + material: 1_000, + processing: 100, + labor: 100, + packaging: 100, + lossIncludedTotal: 1_300, + unresolvedLineCount: 0, + missingCostGroups: [], + }, + bomLines: [], + }], + reviewInputs: [], + analysisRuns: [], + taskEvents: [], + dynamicCosting: initialDynamicCosting, + } + global.fetch = jest.fn(async (_url, init) => ({ + ok: true, + json: async () => ({ + success: true, + data: init?.method === 'POST' + ? { dynamicCosting: updatedDynamicCosting } + : { case: detail }, + }), + })) as jest.Mock + + try { + render( + , + ) + + expect(await screen.findByText('已知部分 ¥500.00')).toBeInTheDocument() + expect(screen.getAllByText('数据不足').length).toBeGreaterThan(0) + expect(screen.getByText('1 行没有可验证价格来源')).toBeInTheDocument() + expect(screen.getByText(/最近同步未成功:上游连接超时/)).toBeInTheDocument() + const skuButton = screen.getByRole('button', { name: /黑胡桃色 120cm/ }) + expect(within(skuButton).getByText('已知 ¥500.00')).toBeInTheDocument() + expect(screen.getByText('旧规则留档:¥1,300.00')).toBeInTheDocument() + + await waitFor(() => { + expect(screen.getByLabelText('选择替换目标材质')).toHaveValue( + 'material-rubberwood', + ) + }) + fireEvent.click(screen.getByRole('button', { name: '替换为 橡胶木' })) + expect(screen.getAllByText('¥550.00').length).toBeGreaterThan(0) + + const calculateButton = screen.getByRole('button', { name: '生成替换方案' }) + await waitFor(() => expect(calculateButton).toBeEnabled()) + fireEvent.click(calculateButton) + + await waitFor(() => { + const postCall = (global.fetch as jest.Mock).mock.calls.find( + ([url, init]) => String(url).endsWith('/cases/case-dynamic/scenarios') && init?.method === 'POST', + ) + expect(postCall).toBeDefined() + expect(JSON.parse(postCall?.[1]?.body)).toEqual({ + skuId: 'sku-dynamic', + targetMaterialId: 'material-rubberwood', + }) + }) + expect(await screen.findByText('公司成本 · 橡胶木')).toBeInTheDocument() + const dynamicCostingHeading = screen.getByRole('heading', { + name: '公司动态成本', + level: 2, + }) + const productHeading = screen.getByRole('heading', { + name: detail.title, + level: 2, + }) + const gallery = document.getElementById('bom-product-gallery') + expect(dynamicCostingHeading.closest('section')).toHaveClass( + 'order-2', + 'xl:order-none', + ) + expect(productHeading.closest('aside')).toHaveClass( + 'order-3', + 'xl:order-none', + ) + expect(gallery).toHaveClass('min-h-0') + expect(gallery).not.toHaveClass('min-h-[520px]') + expect(gallery?.firstElementChild).toHaveClass( + 'min-h-[148px]', + 'sm:min-h-[180px]', + ) + expect(screen.queryByText('暂无图片')).not.toBeInTheDocument() + expect(screen.getByRole('heading', { name: '选择 SKU', level: 3 })).toBeInTheDocument() + expect(screen.getAllByText('¥1,300.00').length).toBeGreaterThan(0) + expect(screen.getAllByText('暂估 / 待复核').length).toBeGreaterThan(0) + expect(screen.getByText(/成本高于竞品售价,金额已保留/)).toBeInTheDocument() + expect(screen.getAllByText('¥1,270.00').length).toBeGreaterThan(0) + expect(screen.getAllByText('公司历史 BOM 中位单价').length).toBeGreaterThan(0) + expect(screen.getAllByText(/参考 SKU:REF-BOARD/).length).toBeGreaterThan(0) + expect(screen.getByText('成本贡献明细')).toBeInTheDocument() + expect(screen.getAllByText('最大贡献').length).toBeGreaterThan(0) + expect(screen.getAllByText(/占(?:已知成本 )?62%/).length).toBeGreaterThan(0) + expect(screen.getAllByText('较同材质').length).toBeGreaterThan(0) + expect(screen.getAllByText('节省 ¥50.00').length).toBeGreaterThan(0) + expect(screen.queryByText('-¥50.00')).not.toBeInTheDocument() + + const costSummaryAside = screen.getByText('公司成本 · 橡胶木').closest('aside') + expect(costSummaryAside).not.toBeNull() + expect(within(costSummaryAside as HTMLElement).getByText('竞品售价 ¥600.00')).toBeInTheDocument() + expect(within(costSummaryAside as HTMLElement).getByText(/高于竞品售价 ¥700.00/)).toBeInTheDocument() + + fireEvent.click(screen.getByRole('button', { name: '同材质基准' })) + expect(screen.queryByText('较同材质')).not.toBeInTheDocument() + expect(screen.queryByText('替换后预计')).not.toBeInTheDocument() + expect(screen.queryByText('节省 ¥50.00')).not.toBeInTheDocument() + expect(screen.getAllByText('有价格来源').length).toBeGreaterThan(0) + } finally { + global.fetch = originalFetch + } + }) }) diff --git a/furniture-3d-system/src/app/bom-costing/BomCostingWorkbenchClient.tsx b/furniture-3d-system/src/app/bom-costing/BomCostingWorkbenchClient.tsx index 873f39be..a33d1412 100644 --- a/furniture-3d-system/src/app/bom-costing/BomCostingWorkbenchClient.tsx +++ b/furniture-3d-system/src/app/bom-costing/BomCostingWorkbenchClient.tsx @@ -40,8 +40,11 @@ import type { BomCostingCapabilities, BomCostingCaseDetail, BomCostingCaseSummary, + BomCostingDynamicCostingDetail, + BomCostingDynamicScenarioKindValue, BomCostingLineDetail, BomCostingPriceCandidateDetail, + BomCostingScenarioDetail, BomCostingSkuDetail, } from '@/lib/bom-costing/client-types' import { @@ -100,6 +103,39 @@ interface ManualReviewDraft { note: string } +type ManualReviewField = Exclude + +const MANUAL_REVIEW_FIELD_GROUPS: Array<{ + label: string + fields: Array +}> = [ + { + label: '材质与规格', + fields: [ + ['materialName', '材质名称', '如:橡胶木实木板'], + ['materialSpec', '材质规格', '如:18mm'], + ['materialCode', '材质编码', '可选'], + ], + }, + { + label: '部件尺寸', + fields: [ + ['lengthMm', '长度(mm)', '可选'], + ['widthMm', '宽度(mm)', '可选'], + ['heightMm', '厚度/高度(mm)', '可选'], + ], + }, + { + label: '计价参数', + fields: [ + ['quantity', '数量', '必填'], + ['unitPrice', '单价', '可选'], + ['priceUnit', '价格单位', '㎡ / 件 / 米'], + ['lossFactor', '损耗系数', '默认 1'], + ], + }, +] + const RECALCULATION_OPTIONS: Array<{ value: RecalculationMode label: string @@ -121,11 +157,13 @@ const RECALCULATION_OPTIONS: Array<{ { value: 'REANALYZE_ALL', label: '全部重新分析', - description: '仅在图片资料已经变化时使用,会重新分析全部已归档图片。', - scope: '图片调用覆盖全部图片 · 仅汇总实际 SKU', + description: '重新从竞品链接读取最新标题、文字、SKU 与图片,再分析当前全部有效图片。', + scope: '重新读取竞品资料 · 图片调用覆盖当前全部有效图片 · 仅核算真实 SKU', }, ] +const BOM_CASE_LOAD_TIMEOUT_MS = 15_000 + const STATUS_LABELS: Record = { DRAFT: '草稿', QUEUED: '排队中', @@ -270,6 +308,14 @@ function formatMoney(value: number | null | undefined) { })}` } +function formatScenarioDifference(value: number | null | undefined) { + if (value === null || value === undefined) return '--' + if (Math.abs(value) < 0.005) return '无变化' + return value > 0 + ? `增加 ${formatMoney(value)}` + : `节省 ${formatMoney(Math.abs(value))}` +} + function BomInfoHint({ label, children, @@ -290,7 +336,7 @@ function BomInfoHint({ return ( setOpen(true)} onMouseLeave={() => setOpen(false)} > @@ -298,18 +344,22 @@ function BomInfoHint({ type="button" aria-label={label} aria-describedby={tooltipId} + aria-expanded={open} onFocus={() => setOpen(true)} onBlur={() => setOpen(false)} onClick={(event) => { event.preventDefault() event.stopPropagation() - setOpen((current) => !current) + // Focus opens the hint before the click event fires. Toggling here + // immediately closed it on touch devices, so a first tap appeared + // to do nothing. Blur/Escape still provide the close affordance. + setOpen(true) }} onKeyDown={(event) => { if (event.key === 'Escape') setOpen(false) }} className={cn( - 'inline-flex h-4 w-4 items-center justify-center rounded-full outline-none transition focus-visible:ring-2 focus-visible:ring-offset-1', + 'absolute left-1/2 top-1/2 z-10 inline-flex h-11 w-11 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full outline-none transition focus-visible:ring-2 focus-visible:ring-offset-1', inverse ? 'text-white/70 hover:bg-white/[0.12] hover:text-white focus-visible:ring-white/75 focus-visible:ring-offset-[#2d3335]' : 'text-[#778184] hover:bg-[#edf1f1] hover:text-[#40585d] focus-visible:ring-[#40585d] focus-visible:ring-offset-white', @@ -322,9 +372,9 @@ function BomInfoHint({ role="tooltip" className={cn( open - ? 'absolute z-50 w-64 max-w-[calc(100vw-40px)] rounded-[6px] border border-black/[0.12] bg-[#273134] px-2.5 py-2 text-[10px] leading-4 text-white shadow-[0_12px_28px_rgba(45,51,53,0.18)]' + ? 'absolute z-50 w-64 max-w-[calc(100vw-24px)] rounded-[6px] border border-black/[0.12] bg-[#273134] px-2.5 py-2 text-[10px] leading-4 text-white shadow-[0_12px_28px_rgba(45,51,53,0.18)]' : 'sr-only', - open && (align === 'end' ? 'right-0' : 'left-0'), + open && (align === 'end' ? 'right-0' : 'left-1/2 -translate-x-1/2'), open && (side === 'top' ? 'bottom-[calc(100%+6px)]' : 'top-[calc(100%+6px)]'), )} > @@ -862,6 +912,420 @@ function ProcessInspector({ ) } +function dynamicStatusLabel( + status: BomCostingScenarioDetail['status'], + scope: 'scenario' | 'line' = 'scenario', +) { + return status === 'FINAL' + ? scope === 'line' ? '有价格来源' : '可用' + : status === 'PROVISIONAL' + ? '暂估 / 待复核' + : status === 'STALE' + ? '数据过期' + : '数据不足' +} + +const DYNAMIC_CATEGORY_LABELS: Record = { + BOARD: '板材', + STEEL: '钢材', + ACCESSORY: '配件 / 五金', + PACKAGING: '包材', + PROCESSING: '加工', + LABOR: '人工', + OTHER: '其他', +} + +function dynamicCategoryLabel(category: string) { + return DYNAMIC_CATEGORY_LABELS[category] ?? category +} + +function dynamicStatusClass(status: BomCostingScenarioDetail['status']) { + return status === 'FINAL' + ? 'bg-[#e5efeb] text-[#41665e]' + : status === 'STALE' + ? 'bg-[#f5eadc] text-[#8a5f3f]' + : status === 'INSUFFICIENT_DATA' + ? 'bg-[#f6e7e5] text-[#96504c]' + : 'bg-[#f3eddf] text-[#80613a]' +} + +function dynamicSyncLabel(state: BomCostingDynamicCostingDetail['sync']['state']) { + return state === 'READY' + ? '镜像新鲜' + : state === 'STALE' + ? '镜像已过期' + : state === 'MIXED' + ? '镜像批次不一致' + : '尚无成功镜像' +} + +function DynamicCostingPanel({ + sku, + costing, + scenarioKind, + targetMaterialId, + calculating, + error, + onScenarioKindChange, + onTargetMaterialChange, + onCalculate, +}: { + sku: BomCostingSkuDetail + costing: BomCostingDynamicCostingDetail | undefined + scenarioKind: BomCostingDynamicScenarioKindValue + targetMaterialId: string + calculating: boolean + error: string + onScenarioKindChange: (kind: BomCostingDynamicScenarioKindValue) => void + onTargetMaterialChange: (id: string) => void + onCalculate: () => void +}) { + const skuScenarios = costing?.scenarios.filter((scenario) => scenario.skuId === sku.id) ?? [] + const sameScenario = skuScenarios.find((scenario) => scenario.kind === 'SAME_MATERIAL') ?? null + const substitutionScenario = skuScenarios.find((scenario) => scenario.kind === 'MATERIAL_SUBSTITUTION') ?? null + const selectedScenario = scenarioKind === 'SAME_MATERIAL' ? sameScenario : substitutionScenario + const difference = sameScenario?.totalCost !== null && sameScenario?.totalCost !== undefined && + substitutionScenario?.totalCost !== null && substitutionScenario?.totalCost !== undefined + ? substitutionScenario.totalCost - sameScenario.totalCost + : null + const provisionalLineCount = selectedScenario?.lines.filter((line) => line.status === 'PROVISIONAL').length ?? 0 + const staleLineCount = selectedScenario?.lines.filter((line) => line.status === 'STALE').length ?? 0 + const materialName = costing?.materials.find((material) => material.id === targetMaterialId)?.name ?? '未选择' + const savedTargetMaterialId = substitutionScenario?.targetMaterialId ?? '' + const targetMaterialNeedsRefresh = Boolean( + substitutionScenario && targetMaterialId !== savedTargetMaterialId, + ) + const savedMaterialName = substitutionScenario?.targetMaterialName || materialName + const latestFailedAfterSuccess = Boolean( + costing?.sync.lastFailedAt && + (!costing.sync.lastSuccessfulAt || Date.parse(costing.sync.lastFailedAt) > Date.parse(costing.sync.lastSuccessfulAt)), + ) + const categoryRows: Array<[string, number | null]> = selectedScenario + ? [ + ['材料', selectedScenario.materialCost], + ['加工', selectedScenario.processingCost], + ['人工', selectedScenario.laborCost], + ['包材', selectedScenario.packagingCost], + ['损耗', selectedScenario.lossCost], + ] + : [] + const contributionBase = selectedScenario?.totalCost ?? selectedScenario?.knownCost ?? 0 + const contributionLines = (selectedScenario?.lines ?? []) + .map((line, index) => ({ line, index })) + .sort((left, right) => ( + (right.line.subtotal ?? Number.NEGATIVE_INFINITY) - + (left.line.subtotal ?? Number.NEGATIVE_INFINITY) || + left.index - right.index + )) + .map(({ line }, rank) => ({ + line, + primary: rank === 0 && line.subtotal !== null, + percent: line.subtotal !== null && contributionBase > 0 + ? Math.round(line.subtotal / contributionBase * 100) + : null, + })) + + return ( +
+
+
+
+
+
+ {costing ? ( +
+ + {dynamicSyncLabel(costing.sync.state)} + + + 镜像完成于 {formatActivityTime(costing.sync.dataAsOf)} + +
+ ) : null} +
+ + {!costing ? ( +
+ 这条历史记录还没有公司成本快照。重新核算后会自动生成同材质基准;需要比较时再选择替换材质。 +
+ ) : ( + <> +
+
+ + +
+
+
+ {([ + ['SAME_MATERIAL', '同材质基准'], + ['MATERIAL_SUBSTITUTION', `替换为 ${targetMaterialNeedsRefresh ? materialName : savedMaterialName}${targetMaterialNeedsRefresh ? '(待重新生成)' : ''}`], + ] as const).map(([kind, label]) => ( + + ))} +
+ {targetMaterialNeedsRefresh ? ( +

+ 目标材质已更改,当前替换结果仍是上次保存的 {savedMaterialName},请重新生成。 +

+ ) : null} +
+
+ + {costing.materials.length === 0 ? ( +
+
+ ) : null} + {costing.sync.state !== 'READY' || latestFailedAfterSuccess ? ( +
+
+ ) : null} + {error ? ( +
{error}
+ ) : null} + + {selectedScenario ? ( + <> +
+
+
+ + {scenarioKind === 'SAME_MATERIAL' ? '同材质基准' : `材质替换:${selectedScenario.targetMaterialName || materialName}`} + + + {dynamicStatusLabel(selectedScenario.status)} + +
+
+ + {selectedScenario.totalCost !== null ? formatMoney(selectedScenario.totalCost) : `已知部分 ${formatMoney(selectedScenario.knownCost)}`} + + {selectedScenario.confidence !== null ? ( + 置信度 {Math.round(selectedScenario.confidence * 100)}% + ) : null} +
+
+
+
竞品售价
+
{formatMoney(selectedScenario.competitorPrice)}
+
+ {scenarioKind === 'MATERIAL_SUBSTITUTION' ? ( +
+
较同材质
+
0 ? 'text-[#96504c]' : 'text-[#4d6b63]')}> + {formatScenarioDifference(difference)} +
+
+ ) : null} +
+ {selectedScenario.priceDelta !== null && selectedScenario.competitorPrice !== null && selectedScenario.priceDelta > 0 ? ( +
+
+ ) : null} + {selectedScenario.warning ? ( +

{selectedScenario.warning}

+ ) : null} +
+ {categoryRows.map(([label, value]) => ( +
+ {label} + {formatMoney(value)} +
+ ))} +
+
+ 成本贡献明细 + 按行小计从高到低 +
+
+ {contributionLines.map(({ line, percent, primary }) => ( +
+
+
+
+ {dynamicCategoryLabel(line.category)} + {primary ? 最大贡献 : null} +
+
{line.partName || '未命名部件'}
+
+ {[line.originalMaterial, line.appliedMaterial !== line.originalMaterial ? `→ ${line.appliedMaterial}` : '', line.materialSpec] + .filter(Boolean).join(' · ') || '材质待确认'} +
+
+ + {dynamicStatusLabel(line.status, 'line')} + +
+
+
+
计价数量 · 系数
+
+ {line.pricingQuantity ?? line.quantity ?? '--'} {line.unit || ''} · {line.coefficient ?? '--'} + {line.confidence !== null ? ` · 置信度 ${Math.round(line.confidence * 100)}%` : ''} +
+ {line.quantity !== line.pricingQuantity && line.quantity !== null ? ( +
原始数量 {line.quantity} {line.unit || ''}
+ ) : null} +
+
+
行小计
+
{formatMoney(line.subtotal)}
+ {percent !== null ?
占已知成本 {percent}%
: null} +
+
+
+ {line.unitPrice !== null + ? 公司单价 {formatMoney(line.unitPrice)} / {line.unit || '单位'} + : 没有有效单价来源} +
{line.priceSource || '待匹配公司历史 BOM'}
+ {line.referenceSkus.length > 0 ?
参考 SKU:{line.referenceSkus.slice(0, 3).join('、')}
: null} + {line.warning ?
{line.warning}
: null} + {line.sourceSyncedAt ?
同步 {formatActivityTime(line.sourceSyncedAt)}
: null} +
+
+ ))} +
+
+ + + + + + + + + + + + + + {contributionLines.map(({ line, percent, primary }) => ( + + + + + + + + + ))} + +
成本贡献明细,按行小计从高到低排列
分类部件 / 材质数量 · 系数公司价格来源状态行小计
+ {dynamicCategoryLabel(line.category)} + {primary ?
最大贡献
: null} +
+
{line.partName || '未命名部件'}
+
+ {[line.originalMaterial, line.appliedMaterial !== line.originalMaterial ? `→ ${line.appliedMaterial}` : '', line.materialSpec] + .filter(Boolean).join(' · ') || '材质待确认'} +
+ {line.warning ?
{line.warning}
: null} +
+ {line.pricingQuantity ?? line.quantity ?? '--'} {line.unit || ''} +
系数 {line.coefficient ?? '--'}
+
+ {line.unitPrice !== null ?
{formatMoney(line.unitPrice)} / {line.unit || '单位'}
:
没有有效单价来源
} +
{line.priceSource || '待匹配公司历史 BOM'}
+ {line.referenceSkus.length > 0 ?
参考 SKU:{line.referenceSkus.slice(0, 3).join('、')}
: null} +
+ {dynamicStatusLabel(line.status, 'line')} + {line.confidence !== null ?
置信度 {Math.round(line.confidence * 100)}%
: null} + {line.sourceCreatedAt ?
来源 {formatActivityTime(line.sourceCreatedAt)}
: null} + {line.sourceSyncedAt ?
同步 {formatActivityTime(line.sourceSyncedAt)}
: null} +
+ {formatMoney(line.subtotal)} + {percent !== null ?
占 {percent}%
: null} +
+
+
+ + {selectedScenario.unresolvedCount > 0 + ? `${selectedScenario.unresolvedCount} 行没有可验证价格来源` + : selectedScenario.status === 'FINAL' + ? '所有行均有可验证价格来源' + : staleLineCount > 0 + ? `${staleLineCount} 行价格已过期,汇总结果需复核` + : provisionalLineCount > 0 + ? `${provisionalLineCount} 行采用暂估或推导数量,汇总结果需复核` + : '明细均有价格来源,但汇总含暂估判断,需复核主要驱动项'} + + 规则 {selectedScenario.rulesetVersion} · 批次 {selectedScenario.syncRunId || '--'} +
+ + ) : ( +
+ 选择目标材质并点击“生成双场景”,系统会保存同材质基准和替换材质的完整明细。 +
+ )} + + )} +
+ ) +} + function ResultCanvas({ detail, selectedSku, @@ -904,6 +1368,7 @@ function ResultCanvas({ () => [...mainAssets, ...selectedSkuAssets], [mainAssets, selectedSkuAssets], ) + const hasGalleryAssets = galleryAssets.length > 0 const detailAssets = useMemo( () => sourceAssets.filter((asset) => asset.kind === 'DETAIL'), [sourceAssets], @@ -931,6 +1396,11 @@ function ResultCanvas({ null, ) const [priceEditorError, setPriceEditorError] = useState('') + const [dynamicScenarioKind, setDynamicScenarioKind] = + useState('SAME_MATERIAL') + const [dynamicTargetMaterialId, setDynamicTargetMaterialId] = useState('') + const [dynamicCalculating, setDynamicCalculating] = useState(false) + const [dynamicCalculationError, setDynamicCalculationError] = useState('') const [recalculationOpen, setRecalculationOpen] = useState(false) const [reviewArchiveOpen, setReviewArchiveOpen] = useState(false) const [recalculationMode, setRecalculationMode] = @@ -938,6 +1408,8 @@ function ResultCanvas({ const [selectedReanalysisAssetIds, setSelectedReanalysisAssetIds] = useState([]) const [recalculationInstruction, setRecalculationInstruction] = useState('') + const [recalculationConfirmationOpen, setRecalculationConfirmationOpen] = + useState(false) const [failedFactDetailsOpen, setFailedFactDetailsOpen] = useState(false) const scrollIntoView = useBomGsapScrollIntoView() const assetIdByStoredUrl = new Map() @@ -954,6 +1426,65 @@ function ResultCanvas({ galleryAssets[0] ?? null + const dynamicCosting = detail.dynamicCosting + const selectedSkuDynamicScenarios = dynamicCosting?.scenarios.filter( + (scenario) => scenario.skuId === selectedSku.id, + ) ?? [] + const sameMaterialScenario = selectedSkuDynamicScenarios.find( + (scenario) => scenario.kind === 'SAME_MATERIAL', + ) ?? null + const substitutionScenario = selectedSkuDynamicScenarios.find( + (scenario) => scenario.kind === 'MATERIAL_SUBSTITUTION', + ) ?? null + const selectedDynamicScenario = dynamicScenarioKind === 'SAME_MATERIAL' + ? sameMaterialScenario + : substitutionScenario + const dynamicScenarioDifference = sameMaterialScenario?.totalCost !== null && sameMaterialScenario?.totalCost !== undefined && + substitutionScenario?.totalCost !== null && substitutionScenario?.totalCost !== undefined + ? substitutionScenario.totalCost - sameMaterialScenario.totalCost + : null + + useEffect(() => { + const materials = dynamicCosting?.materials ?? [] + const savedTargetId = substitutionScenario?.targetMaterialId ?? '' + setDynamicTargetMaterialId((current) => { + if (current && materials.some((material) => material.id === current)) return current + if (savedTargetId && materials.some((material) => material.id === savedTargetId)) return savedTargetId + return materials[0]?.id ?? '' + }) + setDynamicCalculationError('') + }, [detail.id, dynamicCosting?.materials, selectedSku.id, substitutionScenario?.targetMaterialId]) + + const calculateDynamicCosting = async () => { + if (!dynamicTargetMaterialId || dynamicCalculating) return + setDynamicCalculating(true) + setDynamicCalculationError('') + try { + const response = await fetch( + `/api/bom-costing/cases/${encodeURIComponent(detail.id)}/scenarios`, + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + skuId: selectedSku.id, + targetMaterialId: dynamicTargetMaterialId, + }), + }, + ) + const data = await readApiData<{ + dynamicCosting: BomCostingDynamicCostingDetail + }>(response) + onCaseUpdated({ ...detail, dynamicCosting: data.dynamicCosting }) + setDynamicScenarioKind('MATERIAL_SUBSTITUTION') + } catch (error) { + setDynamicCalculationError( + error instanceof Error ? error.message : '双场景成本生成失败,请重试', + ) + } finally { + setDynamicCalculating(false) + } + } + const setSelectedAssetId = (assetId: string) => { setSelectedAssetIdBySku((current) => ({ ...current, @@ -1018,7 +1549,7 @@ function ResultCanvas({ ) } - const submitRecalculation = async () => { + const submitRecalculation = async (confirmedAllImages = false) => { if ( recalculating || ( @@ -1028,6 +1559,10 @@ function ResultCanvas({ ) { return } + if (recalculationMode === 'REANALYZE_ALL' && !confirmedAllImages) { + setRecalculationConfirmationOpen(true) + return + } const started = await onRecalculate({ mode: recalculationMode, selectedAssetIds: @@ -1037,6 +1572,7 @@ function ResultCanvas({ instruction: recalculationInstruction.trim(), }) if (!started) return + setRecalculationConfirmationOpen(false) setRecalculationOpen(false) setSelectedReanalysisAssetIds([]) setRecalculationInstruction('') @@ -1270,6 +1806,15 @@ function ResultCanvas({ missing: requiresRecalculation || missingCostGroups.has('PACKAGING'), }, ] + const displayedCostSummaryRows = selectedDynamicScenario + ? [ + { label: '材料', value: selectedDynamicScenario.materialCost, unresolved: selectedDynamicScenario.materialCost === null, missing: selectedDynamicScenario.materialCost === null }, + { label: '加工', value: selectedDynamicScenario.processingCost, unresolved: selectedDynamicScenario.processingCost === null, missing: selectedDynamicScenario.processingCost === null }, + { label: '人工', value: selectedDynamicScenario.laborCost, unresolved: selectedDynamicScenario.laborCost === null, missing: selectedDynamicScenario.laborCost === null }, + { label: '包材', value: selectedDynamicScenario.packagingCost, unresolved: selectedDynamicScenario.packagingCost === null, missing: selectedDynamicScenario.packagingCost === null }, + { label: '损耗', value: selectedDynamicScenario.lossCost, unresolved: selectedDynamicScenario.lossCost === null, missing: selectedDynamicScenario.lossCost === null }, + ] + : costSummaryRows const currentSkuReviewInputs = (detail.reviewInputs ?? []).slice(0, 8) const recalculationPanelOpen = recalculationOpen && detail.status === 'READY' @@ -1312,76 +1857,85 @@ function ResultCanvas({
+ ) : null} -
+
-
+ void calculateDynamicCosting()} + /> + +
-

商品详情图

+

商品详情图

共 {detailAssets.length} 张,按竞品页面原顺序展示

@@ -1474,11 +2040,11 @@ function ResultCanvas({
-

BOM 核算明细

+

BOM 核算明细

当前 SKU:{selectedSku.name}

@@ -1487,19 +2053,20 @@ function ResultCanvas({ {selectedSku.bomLines.length} 项
-
- - +
+
+ + - - - - - - + + + + + + - + {selectedSku.bomLines.map((line) => { const evidence = (line.evidence ?? [])[0] const evidenceAssetId = evidence?.imageUrl @@ -1527,23 +2094,23 @@ function ResultCanvas({ : candidates return ( - - + - - - - - {editing ? ( - - +
BOM 核算明细
分类部件 / 材质尺寸数量价格来源小计分类部件 / 材质尺寸数量价格来源小计
+
{line.categoryLabel} +
{line.partName}
-
+
{[line.materialName, line.materialSpec, line.processName] .filter(Boolean) .join(' · ') || '--'}
{evidence?.note ? ( -
+
{evidence.note} {evidenceAssetId ? ( @@ -1558,7 +2125,8 @@ function ResultCanvas({
) : null}
+ +
尺寸
{[line.lengthMm, line.widthMm, line.heightMm] .filter((value) => value !== null) .join(' × ') || '--'} @@ -1568,10 +2136,12 @@ function ResultCanvas({ ) : null}
+ +
数量
{line.quantity} {line.unit}
+ +
价格来源
{line.category === 'PROCESSING' || @@ -1587,7 +2157,7 @@ function ResultCanvas({ onClick={() => void openPriceEditor(line)} aria-expanded={editing && editingLineMode === 'LIBRARY'} className={cn( - 'flex max-w-full items-center gap-1 rounded-[4px] px-1.5 py-1 text-left font-semibold outline-none transition focus-visible:ring-2 focus-visible:ring-[#40585d]', + 'flex min-h-11 max-w-full items-center gap-1 rounded-[4px] px-1.5 py-1 text-left font-semibold outline-none transition focus-visible:ring-2 focus-visible:ring-[#40585d] md:min-h-0', line.matchedLibraryType === 'MANUAL_REVIEW' ? 'text-[#4c625f] hover:bg-[#edf1f1]' : line.matchStatus === 'MATCHED' @@ -1613,7 +2183,7 @@ function ResultCanvas({ ) : null} {line.resolvedUnitPrice !== null ? ( -
+
{formatMoney(line.resolvedUnitPrice)}/{line.resolvedPriceUnit || line.unit}
) : null} @@ -1625,7 +2195,7 @@ function ResultCanvas({ aria-expanded={editing && editingLineMode === 'MANUAL'} title="记录人工复核" className={cn( - 'mt-0.5 shrink-0 rounded-[4px] p-1 text-[#758083] outline-none transition hover:bg-[#edf1f1] hover:text-[#40585d] focus-visible:ring-2 focus-visible:ring-[#40585d]', + 'mt-0.5 flex h-11 w-11 shrink-0 items-center justify-center rounded-[4px] text-[#657174] outline-none transition hover:bg-[#edf1f1] hover:text-[#40585d] focus-visible:ring-2 focus-visible:ring-[#40585d] md:h-auto md:w-auto md:p-1', editing && editingLineMode === 'MANUAL' && 'bg-[#e7efed] text-[#40585d]', )} > @@ -1633,13 +2203,14 @@ function ResultCanvas({
+ +
小计
{formatMoney(line.subtotal)}
+
{editingLineMode === 'MANUAL' && manualReviewDraft ? ( @@ -1655,51 +2226,52 @@ function ResultCanvas({ 不改资料库
-
- {([ - ['materialName', '材质名称', '如:橡胶木实木板'], - ['materialSpec', '材质规格', '如:18mm'], - ['materialCode', '材质编码', '可选'], - ['priceUnit', '价格单位', '㎡ / 件 / 米'], - ['lengthMm', '长度 mm', '可选'], - ['widthMm', '宽度 mm', '可选'], - ['heightMm', '厚度/高度 mm', '可选'], - ['quantity', '数量', '必填'], - ['unitPrice', '单价', '可选'], - ['lossFactor', '损耗系数', '默认 1'], - ] as const).map(([field, label, placeholder]) => ( - - setManualReviewDraft((current) => - current - ? { ...current, [field]: event.target.value } - : current, - ) - } - aria-label={label} - placeholder={placeholder} - type={field === 'priceUnit' || field.startsWith('material') ? 'text' : 'number'} - step="any" - containerClassName="!space-y-0" - className="!min-h-9 !rounded-[5px] !bg-white !px-2.5 !py-1.5 text-[10px]" - /> +
+ {MANUAL_REVIEW_FIELD_GROUPS.map((group) => ( +
+ + {group.label} + +
+ {group.fields.map(([field, label, placeholder]) => ( + + setManualReviewDraft((current) => + current + ? { ...current, [field]: event.target.value } + : current, + ) + } + label={label} + required={field === 'quantity'} + placeholder={placeholder} + type={field === 'priceUnit' || field.startsWith('material') ? 'text' : 'number'} + step="any" + containerClassName="!space-y-1 [&>label]:!mb-0 [&>label]:!text-[11px] [&>label]:!leading-4 [&>label]:!tracking-normal [&>label]:!text-[#4f5c5f]" + className="!min-h-11 !rounded-[5px] !bg-white !px-2.5 !py-1.5 text-[12px] sm:!min-h-9" + /> + ))} +
+
))}
-