修复(成本中心): 接单模板商品被商品接口误归档导致与接单模板数量不一致
生产只读核对(2026-12-03):接单模板 972 条,商品与成本中心「接单平台」只有 957 个, 差的 15 个模板商品被 admin_audit_logs 中的 cost_product_updated 记录逐条对上,操作人来自 售后账号,时间分布到 2026-11-28,说明该路径仍在持续制造不一致。 根因: - updateAdminProduct 只改 product_catalog.status,不校验商品是否被接单模板引用,也不写归档原因; - 商品归档后列表默认只查 active、前端无 archived 入口,运营再也看不到也点不回来; - 迁移 164 的回填要求商品当时 active,更早归档的模板 canonical_product_id 永久为 NULL; - 保存模板的 ON CONFLICT DO UPDATE 不含 status、「修复历史商品/映射」不写关联也不重置状态, 所以人工修几次都只会得到“链接修好、状态仍是 archived”的中间态。 改动: - 新增迁移 192:按 tpl:<rule_key> 唯一身份公式回填关联、恢复被误归档的模板商品 (保留 previousStatus/repairedAt/repairReason 供回滚),假草稿与已删模板商品不动; 末尾断言启用模板与商品一一对齐、同一 SKU 不得命中多条模板,任一不满足整份回滚。 - 商品接口拒绝归档/删除仍被模板引用的商品(409 cost_product_template_bound); attributes_json 改为合并,避免编辑商品时抹掉模板属性。 - 保存模板一律把商品置为 active 并写回关联,模板删除才归档;模板商品 SKU 已被 非模板商品占用时 409 cost_template_sku_occupied,不再劫持他人商品。 - 「修复历史商品/映射」统一走模板同步入口,默认包含停用模板。 - 模板成本版本与模板标识统一用同一条身份公式,去掉 LIKE 'tpl:%' + substring 旧写法。 - 前端:模板商品状态开关禁用并提示;跨页缓存失效补齐。 - 权威文档 3.4.4 落地新口径(模板存在 ⇒ 商品 active,只有删除模板才归档)。 - 新增 7 个真实 PostgreSQL 集成测试。 验证:backend check 通过(1559 用例 / fail 0)、frontend check 通过、集成测试 7/7 通过、 迁移 192 在生产同形态夹具上验证幂等且断言通过;生产上线前只读预检 4 项均为 0 行。
This commit is contained in:
@@ -21,6 +21,7 @@ import {
|
||||
import {
|
||||
buildTemplateProductSku,
|
||||
inferTemplateUnitName,
|
||||
syncWorkOrderTemplateProduct,
|
||||
} from './work-order-template-product-service.js'
|
||||
import { attachFulfillmentConfigurations } from '../fulfillment/fulfillment-state-service.js'
|
||||
|
||||
@@ -89,8 +90,11 @@ export async function applyAdminTemplateProductBootstrap(
|
||||
_session?: AdminSession,
|
||||
) {
|
||||
const repair = payload.repair !== false
|
||||
// 「修复历史商品/映射」默认纳入停用模板:模板存在就必须有 active 的 tpl: 商品,
|
||||
// 否则停用模板的商品永远不会被建出来、也不能先配成本再启用(3.4.4)。
|
||||
// 仍允许显式传 includeDisabledTemplates: false 只同步启用模板。
|
||||
const includeDisabledTemplates =
|
||||
payload.includeDisabledTemplates === true || payload.includeDisabled === true
|
||||
payload.includeDisabledTemplates !== false && payload.includeDisabled !== false
|
||||
const range = resolveBootstrapDateRange(payload)
|
||||
const resetResult = repair
|
||||
? await resetImportedTemplateProductBootstrap(range)
|
||||
@@ -111,7 +115,8 @@ export async function applyAdminTemplateProductBootstrap(
|
||||
const now = nowIso()
|
||||
let createdProductCount = 0
|
||||
let updatedProductCount = 0
|
||||
let reusedProductCount = 0
|
||||
// 模板商品恒由模板同步生成/刷新,不再出现「复用其他来源同名商品」的分支。
|
||||
const reusedProductCount = 0
|
||||
let createdMappingCount = 0
|
||||
let skippedMappingCount = 0
|
||||
let mappedOrderItemCount = 0
|
||||
@@ -120,82 +125,17 @@ export async function applyAdminTemplateProductBootstrap(
|
||||
const productIdByRuleKey = new Map<string, number>()
|
||||
for (const template of productTemplates) {
|
||||
const canonicalSku = buildTemplateProductSku(template.rule_key)
|
||||
const attributes = {
|
||||
source: 'work_product_rule',
|
||||
ruleId: Number(template.id),
|
||||
ruleKey: template.rule_key,
|
||||
mappingId: template.mapping_id ? Number(template.mapping_id) : null,
|
||||
mappingType: template.mapping_type,
|
||||
skuNick: template.sku_nick,
|
||||
relSkuId: template.rel_sku_id,
|
||||
sellerIds: template.seller_ids_json,
|
||||
pricingMode: template.pricing_mode === 'unit' ? 'unit' : 'fixed',
|
||||
unitPriceFen: Number(template.unit_price_fen || 0),
|
||||
rewardAmountFen: Number(template.reward_amount || 0),
|
||||
templateEnabled: template.enabled,
|
||||
}
|
||||
const existing = data.productByRuleKey.get(template.rule_key)
|
||||
if (existing) {
|
||||
// 模板改名/改价后刷新接单模板自己的商品;其他来源的同名商品只复用,不改写。
|
||||
const refreshed = await client.query(
|
||||
`
|
||||
UPDATE product_catalog
|
||||
SET canonical_name = $1,
|
||||
category = $2,
|
||||
unit_name = $3,
|
||||
attributes_json = COALESCE(attributes_json, '{}'::jsonb) || $4::jsonb,
|
||||
updated_at = $5
|
||||
WHERE id = $6 AND canonical_sku LIKE 'tpl:%'
|
||||
`,
|
||||
[
|
||||
template.product_name,
|
||||
template.category,
|
||||
inferTemplateUnitName(template.product_name),
|
||||
JSON.stringify(attributes),
|
||||
now,
|
||||
existing,
|
||||
],
|
||||
)
|
||||
if (refreshed.rowCount) {
|
||||
updatedProductCount += 1
|
||||
} else {
|
||||
reusedProductCount += 1
|
||||
}
|
||||
productIdByRuleKey.set(template.rule_key, existing)
|
||||
continue
|
||||
}
|
||||
|
||||
const inserted = await client.query<{ id: number }>(
|
||||
`
|
||||
INSERT INTO product_catalog (
|
||||
canonical_sku, canonical_name, category, unit_name, source_kind, status,
|
||||
attributes_json, created_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, 'work_order', $5, $6::jsonb, $7, $7)
|
||||
ON CONFLICT (canonical_sku) DO NOTHING
|
||||
RETURNING id
|
||||
`,
|
||||
[
|
||||
canonicalSku,
|
||||
template.product_name,
|
||||
template.category,
|
||||
inferTemplateUnitName(template.product_name),
|
||||
template.enabled ? 'active' : 'archived',
|
||||
JSON.stringify(attributes),
|
||||
now,
|
||||
],
|
||||
const before = await client.query<{ id: number }>(
|
||||
'SELECT id FROM product_catalog WHERE canonical_sku = $1 LIMIT 1',
|
||||
[canonicalSku],
|
||||
)
|
||||
let productId = inserted.rows[0]?.id ? Number(inserted.rows[0].id) : 0
|
||||
if (productId) {
|
||||
createdProductCount += 1
|
||||
} else {
|
||||
const existingResult = await client.query<{ id: number }>(
|
||||
'SELECT id FROM product_catalog WHERE canonical_sku = $1 LIMIT 1',
|
||||
[canonicalSku],
|
||||
)
|
||||
productId = Number(existingResult.rows[0]?.id || 0)
|
||||
if (productId) reusedProductCount += 1
|
||||
}
|
||||
if (productId) productIdByRuleKey.set(template.rule_key, productId)
|
||||
// 商品状态与模板关联只有一个写入口:syncWorkOrderTemplateProduct。
|
||||
// 模板存在 ⇒ 商品 active(与 enabled 无关,停用模板也要能先配成本),
|
||||
// 且 work_product_rules.canonical_product_id 始终指向该商品。
|
||||
const projection = await syncWorkOrderTemplateProduct(Number(template.id), client)
|
||||
productIdByRuleKey.set(template.rule_key, projection.productId)
|
||||
if (before.rows[0]?.id) updatedProductCount += 1
|
||||
else createdProductCount += 1
|
||||
}
|
||||
|
||||
for (const row of plan.candidates) {
|
||||
@@ -750,9 +690,7 @@ async function loadTemplateProductBootstrapData(range: { fromDate: string; toDat
|
||||
`,
|
||||
[range.fromDate, range.toDate],
|
||||
),
|
||||
query<{ id: number; canonical_sku: string; canonical_name: string }>(
|
||||
'SELECT id, canonical_sku, canonical_name FROM product_catalog',
|
||||
),
|
||||
query<{ id: number; canonical_sku: string }>('SELECT id, canonical_sku FROM product_catalog'),
|
||||
query<{
|
||||
provider: string
|
||||
shop_id: string
|
||||
@@ -774,24 +712,13 @@ async function loadTemplateProductBootstrapData(range: { fromDate: string; toDat
|
||||
const productByCanonicalSku = new Map(
|
||||
productsResult.rows.map((row) => [row.canonical_sku, Number(row.id)]),
|
||||
)
|
||||
const productByCanonicalName = new Map<string, number>()
|
||||
for (const row of productsResult.rows) {
|
||||
const key = normalizeProductNameKey(row.canonical_name)
|
||||
if (key && !productByCanonicalName.has(key)) {
|
||||
productByCanonicalName.set(key, Number(row.id))
|
||||
}
|
||||
}
|
||||
const productByRuleKey = new Map<string, number>()
|
||||
// 预览只统计「还没有 tpl 商品」的模板;商品状态和关联统一由执行阶段的
|
||||
// syncWorkOrderTemplateProduct 写入,这里不再维护第二套同名商品复用关系。
|
||||
// 「已存在」的唯一口径是精确 tpl:<rule_key> 标准 SKU,与执行阶段保持一致。
|
||||
const productsToCreate: TemplateBootstrapTemplateRow[] = []
|
||||
for (const template of enabledTemplates) {
|
||||
const existing =
|
||||
productByCanonicalSku.get(buildTemplateProductSku(template.rule_key)) ||
|
||||
productByCanonicalName.get(normalizeProductNameKey(template.product_name))
|
||||
if (existing) {
|
||||
productByRuleKey.set(template.rule_key, existing)
|
||||
} else {
|
||||
productsToCreate.push(template)
|
||||
}
|
||||
const existing = productByCanonicalSku.get(buildTemplateProductSku(template.rule_key))
|
||||
if (!existing) productsToCreate.push(template)
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -800,7 +727,6 @@ async function loadTemplateProductBootstrapData(range: { fromDate: string; toDat
|
||||
templatesWithEvidence,
|
||||
evidenceRows: evidenceResult.rows,
|
||||
productsToCreate,
|
||||
productByRuleKey,
|
||||
existingMappingKeys: new Set(
|
||||
mappingsResult.rows.map((row) =>
|
||||
mappingKey(
|
||||
@@ -822,10 +748,3 @@ function resolveBootstrapDateRange(payload: JsonObject) {
|
||||
)
|
||||
return { fromDate: range.fromDate, toDate: range.toDate }
|
||||
}
|
||||
|
||||
function normalizeProductNameKey(value: unknown) {
|
||||
return String(value || '')
|
||||
.normalize('NFKC')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user