修复(成本中心): 接单模板商品被商品接口误归档导致与接单模板数量不一致
生产只读核对(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:
@@ -0,0 +1,203 @@
|
||||
-- 192_work_order_template_product_alignment.sql
|
||||
--
|
||||
-- 日期:2026-12-03
|
||||
--
|
||||
-- 根因(2026-12-03 核对生产 admin_audit_logs 与成本异常后确证):
|
||||
-- 运营在「商品与成本中心」用「状态」开关归档商品时,商品接口只改 product_catalog.status,
|
||||
-- 既不校验该商品是否被接单模板引用,也不写归档原因。接单模板商品被误归档后:
|
||||
-- 1. v_product_current.active_primary_channel 仍按 work_product_rules.canonical_product_id
|
||||
-- 反查(迁移 164),但商品列表默认只查 status = 'active',前端没有 archived 筛选,
|
||||
-- 运营在页面上再也看不到、也点不回来;
|
||||
-- 2. 迁移 164 的回填只覆盖当时 active 的商品,更早归档的模板 canonical_product_id 永久为 NULL;
|
||||
-- 3. 保存模板的 ON CONFLICT DO UPDATE 不含 status,「保存模板」只修链接不复活状态;
|
||||
-- 4. 「修复历史商品/映射」既不写 canonical_product_id 也不重置 status。
|
||||
--
|
||||
-- 依据:docs/统一订单履约与财务模型-权威版.md 3.4.4「接单模板标准商品归属」。
|
||||
-- 口径:只要 work_product_rules 该行存在,它的 tpl:<rule_key> 商品就必须存在且为 active,
|
||||
-- 与模板 enabled 无关(未启用模板也要我先配成本);只有模板被删除才归档商品。
|
||||
--
|
||||
-- 关联判定只用精确公式(与迁移 164/166 一致):
|
||||
-- product.canonical_sku = LEFT('tpl:' || BTRIM(rule.rule_key), 64)
|
||||
-- 模板商品身份只由这一条唯一编码公式确定;不得用商品名、模板名、分类或 tpl: 的任意后缀
|
||||
-- 去猜归属。该公式用于决策、回填和一致性校验,属于身份规则,不是前缀推断。
|
||||
--
|
||||
-- 本迁移全量扫描,不针对个别商品:
|
||||
-- (a) 模板仍存在、商品 source_kind = 'work_order' 且 archived、attributes 不含
|
||||
-- templateDeleted = true、也不是 draft = true 的假草稿时,恢复 status = 'active',并追加
|
||||
-- previousStatus / repairedAt / repairReason(保留原有键,不整体覆盖 attributes_json);
|
||||
-- (b) canonical_product_id IS NULL 且能按精确公式匹配到 source_kind = 'work_order' 商品的模板,
|
||||
-- 回填该关联(与迁移 164 视图 template_product 的 join 口径一致);
|
||||
-- (c) 模板已删除(无对应 rule)的商品完全不处理,status 保持现状;
|
||||
-- (d) 末尾断言,任一情况都 RAISE EXCEPTION 并整份回滚:
|
||||
-- 1) 「启用模板的商品未对齐」(缺失 / 错指 / 非 work_order 来源 / 非 active);
|
||||
-- 2) 「模板存在但商品仍 archived 且无 templateDeleted」(假草稿除外);
|
||||
-- 3) 「同一 tpl: SKU 命中多条模板」(rule_key 被 64 位截断后碰撞会让 JOIN 出现重复行)。
|
||||
--
|
||||
-- 上线前只读预检(在只读事务里逐条执行;**任一结果非空时先人工定性,不要直接执行本迁移**):
|
||||
--
|
||||
-- 1) 错指关联:canonical_product_id 指向的商品不是精确公式商品,或不是接单模板商品
|
||||
-- SELECT rule.id, rule.rule_key, rule.canonical_product_id, product.canonical_sku,
|
||||
-- product.source_kind
|
||||
-- FROM work_product_rules rule
|
||||
-- LEFT JOIN product_catalog product ON product.id = rule.canonical_product_id
|
||||
-- WHERE rule.canonical_product_id IS NOT NULL
|
||||
-- AND (product.id IS NULL
|
||||
-- OR product.source_kind <> 'work_order'
|
||||
-- OR product.canonical_sku <> LEFT('tpl:' || BTRIM(rule.rule_key), 64));
|
||||
--
|
||||
-- 2) 模板仍存在、但商品已归档且属于「非 work_order 来源」或「draft = true 假草稿」
|
||||
-- (这些商品本迁移故意不复活,需要人工判断是保留假草稿还是重配模板)
|
||||
-- SELECT product.id, product.canonical_sku, product.source_kind,
|
||||
-- product.attributes_json ->> 'draft' AS draft
|
||||
-- FROM work_product_rules rule
|
||||
-- JOIN product_catalog product
|
||||
-- ON product.canonical_sku = LEFT('tpl:' || BTRIM(rule.rule_key), 64)
|
||||
-- WHERE product.status = 'archived'
|
||||
-- AND COALESCE(product.attributes_json ->> 'templateDeleted', 'false') <> 'true'
|
||||
-- AND (product.source_kind <> 'work_order'
|
||||
-- OR COALESCE(product.attributes_json ->> 'draft', 'false') = 'true');
|
||||
--
|
||||
-- 3) rule_key 超长被截断,或截断后与其他模板撞同一个 64 位标准 SKU
|
||||
-- SELECT LEFT('tpl:' || BTRIM(rule_key), 64) AS product_sku,
|
||||
-- COUNT(*) AS rule_count,
|
||||
-- string_agg(rule_key, ', ' ORDER BY rule_key) AS rule_keys
|
||||
-- FROM work_product_rules
|
||||
-- GROUP BY 1
|
||||
-- HAVING COUNT(*) > 1;
|
||||
--
|
||||
-- SELECT id, rule_key, LENGTH('tpl:' || BTRIM(rule_key)) AS sku_length
|
||||
-- FROM work_product_rules
|
||||
-- WHERE LENGTH('tpl:' || BTRIM(rule_key)) > 64;
|
||||
--
|
||||
-- 4) 模板仍存在,但商品已归档且带 templateDeleted = true(口径冲突:删除模板与保留模板矛盾)
|
||||
-- SELECT product.id, product.canonical_sku, product.attributes_json ->> 'templateDeleted'
|
||||
-- FROM work_product_rules rule
|
||||
-- JOIN product_catalog product
|
||||
-- ON product.canonical_sku = LEFT('tpl:' || BTRIM(rule.rule_key), 64)
|
||||
-- WHERE product.status = 'archived'
|
||||
-- AND COALESCE(product.attributes_json ->> 'templateDeleted', 'false') = 'true';
|
||||
--
|
||||
-- 幂等:所有写入都带状态条件,重复执行不会再改任何行,也不会覆盖 attributes_json 的其他键。
|
||||
--
|
||||
-- 可回滚:被恢复的商品在 attributes_json 里保留了 previousStatus = 'archived' 和 repairedAt,
|
||||
-- 需要回退时按 repairReason = 'template_product_aligned_192' 取出 repairedAt,把这些商品
|
||||
-- 恢复成 status = 'archived' 并删除这三个修复键即可,不删除任何商品或成本事实。
|
||||
|
||||
-- (b) 先回填模板到标准商品的显式关联。
|
||||
UPDATE work_product_rules rule
|
||||
SET canonical_product_id = product.id,
|
||||
updated_at = NOW()
|
||||
FROM product_catalog product
|
||||
WHERE rule.canonical_product_id IS NULL
|
||||
AND product.source_kind = 'work_order'
|
||||
AND product.canonical_sku = LEFT('tpl:' || BTRIM(rule.rule_key), 64);
|
||||
|
||||
-- (a) 恢复被商品接口误归档的接单模板商品,并留下可回滚痕迹。
|
||||
UPDATE product_catalog product
|
||||
SET status = 'active',
|
||||
attributes_json = COALESCE(product.attributes_json, '{}'::jsonb)
|
||||
|| CASE
|
||||
WHEN COALESCE(product.attributes_json, '{}'::jsonb) ? 'previousStatus' THEN '{}'::jsonb
|
||||
ELSE jsonb_build_object('previousStatus', 'archived')
|
||||
END
|
||||
|| CASE
|
||||
WHEN COALESCE(product.attributes_json, '{}'::jsonb) ? 'repairedAt' THEN '{}'::jsonb
|
||||
ELSE jsonb_build_object(
|
||||
'repairedAt',
|
||||
to_char(NOW() AT TIME ZONE 'Asia/Shanghai', 'YYYY-MM-DD HH24:MI:SS')
|
||||
)
|
||||
END
|
||||
|| jsonb_build_object('repairReason', 'template_product_aligned_192'),
|
||||
updated_at = NOW()
|
||||
WHERE product.source_kind = 'work_order'
|
||||
AND product.status = 'archived'
|
||||
AND COALESCE(product.attributes_json ->> 'templateDeleted', 'false') <> 'true'
|
||||
-- 3.4.5:tpl:<内部 SKU> 假草稿商品一律不复活。
|
||||
AND COALESCE(product.attributes_json ->> 'draft', 'false') <> 'true'
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM work_product_rules rule
|
||||
WHERE product.canonical_sku = LEFT('tpl:' || BTRIM(rule.rule_key), 64)
|
||||
);
|
||||
|
||||
-- (d) 断言:迁移后启用模板与商品必须一一对齐、不再存在「模板存在但商品 archived」、
|
||||
-- 且同一 tpl: SKU 不能命中多条模板。
|
||||
DO $$
|
||||
DECLARE
|
||||
broken_template_count INTEGER := 0;
|
||||
broken_template_sample TEXT := '';
|
||||
broken_product_count INTEGER := 0;
|
||||
broken_product_sample TEXT := '';
|
||||
duplicated_sku_count INTEGER := 0;
|
||||
duplicated_sku_sample TEXT := '';
|
||||
BEGIN
|
||||
-- 断言 3:截断碰撞会让模板与商品的 JOIN 出现重复行,必须在比对前先拦住。
|
||||
SELECT
|
||||
COUNT(*),
|
||||
COALESCE(
|
||||
string_agg(product_sku || ' ← ' || rule_keys, '; ' ORDER BY product_sku),
|
||||
''
|
||||
)
|
||||
INTO duplicated_sku_count, duplicated_sku_sample
|
||||
FROM (
|
||||
SELECT
|
||||
LEFT('tpl:' || BTRIM(rule_key), 64) AS product_sku,
|
||||
string_agg(rule_key, ', ' ORDER BY rule_key) AS rule_keys
|
||||
FROM work_product_rules
|
||||
GROUP BY 1
|
||||
HAVING COUNT(*) > 1
|
||||
) duplicated;
|
||||
|
||||
IF duplicated_sku_count > 0 THEN
|
||||
RAISE EXCEPTION
|
||||
'迁移 192 断言失败:% 个 tpl: 标准 SKU 命中多条接单模板(%)',
|
||||
duplicated_sku_count,
|
||||
LEFT(duplicated_sku_sample, 300)
|
||||
USING HINT = 'rule_key 被 64 位截断后发生碰撞;先人工定性模板 key,不要手工改商品或迁移公式。';
|
||||
END IF;
|
||||
|
||||
SELECT
|
||||
COUNT(*),
|
||||
COALESCE(string_agg(rule.rule_key, ', ' ORDER BY rule.rule_key), '')
|
||||
INTO broken_template_count, broken_template_sample
|
||||
FROM work_product_rules rule
|
||||
LEFT JOIN product_catalog product
|
||||
ON product.canonical_sku = LEFT('tpl:' || BTRIM(rule.rule_key), 64)
|
||||
WHERE rule.enabled = TRUE
|
||||
AND (
|
||||
rule.canonical_product_id IS NULL
|
||||
OR product.id IS NULL
|
||||
OR product.id <> rule.canonical_product_id
|
||||
OR product.source_kind <> 'work_order'
|
||||
OR product.status <> 'active'
|
||||
);
|
||||
|
||||
IF broken_template_count > 0 THEN
|
||||
RAISE EXCEPTION
|
||||
'迁移 192 断言失败:% 个启用中的接单模板商品未对齐(rule_key 示例:%)',
|
||||
broken_template_count,
|
||||
LEFT(broken_template_sample, 200)
|
||||
USING HINT = '按 3.4.4 先保存模板或重新执行「修复历史商品/映射」,不要手工改商品状态。';
|
||||
END IF;
|
||||
|
||||
SELECT
|
||||
COUNT(*),
|
||||
COALESCE(string_agg(product.canonical_sku, ', ' ORDER BY product.canonical_sku), '')
|
||||
INTO broken_product_count, broken_product_sample
|
||||
FROM work_product_rules rule
|
||||
JOIN product_catalog product
|
||||
ON product.canonical_sku = LEFT('tpl:' || BTRIM(rule.rule_key), 64)
|
||||
WHERE product.status = 'archived'
|
||||
AND COALESCE(product.attributes_json ->> 'templateDeleted', 'false') <> 'true'
|
||||
-- 假草稿(3.4.5)不在本迁移恢复范围,也不参与本断言。
|
||||
AND COALESCE(product.attributes_json ->> 'draft', 'false') <> 'true';
|
||||
|
||||
IF broken_product_count > 0 THEN
|
||||
RAISE EXCEPTION
|
||||
'迁移 192 断言失败:% 个模板商品仍为归档状态(canonical_sku 示例:%)',
|
||||
broken_product_count,
|
||||
LEFT(broken_product_sample, 200)
|
||||
USING HINT = '模板存在时商品必须是 active;只有删除模板才归档商品。';
|
||||
END IF;
|
||||
END
|
||||
$$;
|
||||
@@ -122,6 +122,10 @@ export function mapProduct(row: ProductRow) {
|
||||
activeCostEffectiveFrom: row.active_cost_effective_from
|
||||
? String(row.active_cost_effective_from)
|
||||
: null,
|
||||
templateRuleId:
|
||||
row.template_rule_id === null || row.template_rule_id === undefined
|
||||
? null
|
||||
: Number(row.template_rule_id),
|
||||
templatePricingMode: row.template_pricing_mode || null,
|
||||
templateEnabled:
|
||||
row.template_enabled === null || row.template_enabled === undefined
|
||||
|
||||
@@ -26,6 +26,7 @@ export type ProductRow = {
|
||||
cost_version_count?: number
|
||||
active_cost_amount_fen?: number | null
|
||||
active_cost_effective_from?: string | null
|
||||
template_rule_id?: number | null
|
||||
template_pricing_mode?: string | null
|
||||
template_enabled?: boolean | null
|
||||
template_sharing_enabled?: boolean | null
|
||||
|
||||
@@ -86,6 +86,14 @@ function resolveProductSourceKind(canonicalSku: string) {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 模板成本版本归属的精确标准 SKU 公式(与迁移 164/192 及下方列表 JOIN 同一口径)。
|
||||
*
|
||||
* 不使用 `LIKE 'tpl:%'`,也不看 canonical_product_id:模板商品身份只由
|
||||
* `LEFT('tpl:' || BTRIM(rule_key), 64)` 这一条公式确定,避免其他前缀/后缀被误认。
|
||||
*/
|
||||
const TEMPLATE_RULE_SKU_MATCH_SQL = "p.canonical_sku = LEFT('tpl:' || BTRIM(wpr.rule_key), 64)"
|
||||
|
||||
export async function listAdminProducts(payload: JsonObject = {}) {
|
||||
const page = normalizePage(payload.page)
|
||||
const pageSize = normalizePageSize(payload.pageSize)
|
||||
@@ -152,6 +160,7 @@ export async function listAdminProducts(payload: JsonObject = {}) {
|
||||
`
|
||||
SELECT
|
||||
p.*,
|
||||
tpl_rule.id AS template_rule_id,
|
||||
tpl_rule.pricing_mode AS template_pricing_mode,
|
||||
tpl_rule.enabled AS template_enabled,
|
||||
tpl_rule.sharing_enabled AS template_sharing_enabled,
|
||||
@@ -171,8 +180,7 @@ export async function listAdminProducts(payload: JsonObject = {}) {
|
||||
JOIN work_product_rules wpr ON wpr.id = v.work_product_rule_id
|
||||
WHERE v.status = 'active'
|
||||
AND v.scope_type = 'rule'
|
||||
AND p.canonical_sku LIKE 'tpl:%'
|
||||
AND wpr.rule_key = substring(p.canonical_sku from 5)
|
||||
AND ${TEMPLATE_RULE_SKU_MATCH_SQL}
|
||||
) AS cost_version_count,
|
||||
COALESCE(
|
||||
(
|
||||
@@ -189,8 +197,7 @@ export async function listAdminProducts(payload: JsonObject = {}) {
|
||||
JOIN work_product_rules wpr ON wpr.id = v.work_product_rule_id
|
||||
WHERE v.status = 'active'
|
||||
AND v.scope_type = 'rule'
|
||||
AND p.canonical_sku LIKE 'tpl:%'
|
||||
AND wpr.rule_key = substring(p.canonical_sku from 5)
|
||||
AND ${TEMPLATE_RULE_SKU_MATCH_SQL}
|
||||
ORDER BY v.effective_from DESC, v.id DESC
|
||||
LIMIT 1
|
||||
)
|
||||
@@ -210,8 +217,7 @@ export async function listAdminProducts(payload: JsonObject = {}) {
|
||||
JOIN work_product_rules wpr ON wpr.id = v.work_product_rule_id
|
||||
WHERE v.status = 'active'
|
||||
AND v.scope_type = 'rule'
|
||||
AND p.canonical_sku LIKE 'tpl:%'
|
||||
AND wpr.rule_key = substring(p.canonical_sku from 5)
|
||||
AND ${TEMPLATE_RULE_SKU_MATCH_SQL}
|
||||
ORDER BY v.effective_from DESC, v.id DESC
|
||||
LIMIT 1
|
||||
)
|
||||
@@ -220,8 +226,7 @@ export async function listAdminProducts(payload: JsonObject = {}) {
|
||||
FROM v_product_current p
|
||||
${PRODUCT_CATEGORY_JOINS}
|
||||
LEFT JOIN work_product_rules tpl_rule
|
||||
ON p.canonical_sku LIKE 'tpl:%'
|
||||
AND tpl_rule.rule_key = substring(p.canonical_sku from 5)
|
||||
ON p.canonical_sku = LEFT('tpl:' || BTRIM(tpl_rule.rule_key), 64)
|
||||
${affiliateTaskJoinSql}
|
||||
${where}
|
||||
ORDER BY
|
||||
@@ -373,6 +378,31 @@ export async function createAdminProduct(payload: JsonObject, _session: AdminSes
|
||||
return { product: mapProduct(inserted) }
|
||||
}
|
||||
|
||||
/**
|
||||
* 该商品是否由接单模板管理。
|
||||
*
|
||||
* 只认两条正式关系:模板的 canonical_product_id 显式指向该商品,或该商品的标准 SKU
|
||||
* 精确等于模板的 tpl:<rule_key> 身份公式。模板商品身份只由这条公式确定,不从商品名、
|
||||
* 分类或 tpl: 的任意后缀反推。
|
||||
*/
|
||||
async function countTemplateBindingsForProduct(id: number) {
|
||||
const result = await query<{ rule_count: number }>(
|
||||
`
|
||||
SELECT COUNT(*)::int AS rule_count
|
||||
FROM work_product_rules rule
|
||||
WHERE rule.canonical_product_id = $1
|
||||
OR EXISTS (
|
||||
SELECT 1
|
||||
FROM product_catalog product
|
||||
WHERE product.id = $1
|
||||
AND product.canonical_sku = LEFT('tpl:' || BTRIM(rule.rule_key), 64)
|
||||
)
|
||||
`,
|
||||
[id],
|
||||
)
|
||||
return toNumber(result.rows[0]?.rule_count)
|
||||
}
|
||||
|
||||
export async function updateAdminProduct(productId: number | string, payload: JsonObject) {
|
||||
const id = normalizeId(productId, '商品 ID')
|
||||
const current = await getProductRow(id)
|
||||
@@ -396,11 +426,28 @@ export async function updateAdminProduct(productId: number | string, payload: Js
|
||||
? parseJsonObject(current.attributes_json)
|
||||
: normalizeJsonObject(payload.attributes ?? payload.attributesJson)
|
||||
|
||||
// 归档/停用模板商品必须先改模板:模板存在时商品必须是 active(3.4.4)。
|
||||
// 只有「请求显式把状态改成非 active 且与当前状态不同」才算改状态;
|
||||
// 已归档模板商品的改名/改分类不受此守卫影响(状态仍只能由模板写回)。
|
||||
const requestedStatus = payload.status === undefined ? null : status
|
||||
if (
|
||||
requestedStatus !== null &&
|
||||
requestedStatus !== current.status &&
|
||||
requestedStatus !== 'active' &&
|
||||
(await countTemplateBindingsForProduct(id)) > 0
|
||||
) {
|
||||
throw createHttpError(
|
||||
'该商品由接单模板管理,请到「接单平台 → 接单模板」停用或删除模板;删除模板后商品会自动归档',
|
||||
{ statusCode: 409, errorCode: 'cost_product_template_bound' },
|
||||
)
|
||||
}
|
||||
|
||||
const result = await query<ProductRow>(
|
||||
`
|
||||
UPDATE product_catalog
|
||||
SET canonical_name = $1, category = $2, unit_name = $3, status = $4,
|
||||
attributes_json = $5::jsonb, updated_at = $6
|
||||
attributes_json = COALESCE(attributes_json, '{}'::jsonb) || $5::jsonb,
|
||||
updated_at = $6
|
||||
WHERE id = $7
|
||||
RETURNING *
|
||||
`,
|
||||
@@ -429,8 +476,17 @@ export async function deleteAdminProduct(productId: number | string) {
|
||||
(SELECT COUNT(*)::int FROM cost_versions WHERE canonical_product_id = $1) AS version_count,
|
||||
(SELECT COUNT(*)::int FROM cost_snapshots WHERE canonical_product_id = $1) AS snapshot_count,
|
||||
(SELECT COUNT(*)::int FROM fulfillments WHERE canonical_product_id = $1) AS order_item_count,
|
||||
(SELECT COUNT(*)::int FROM work_product_rules WHERE canonical_product_id = $1)
|
||||
AS template_rule_count
|
||||
(
|
||||
SELECT COUNT(*)::int
|
||||
FROM work_product_rules rule
|
||||
WHERE rule.canonical_product_id = $1
|
||||
OR EXISTS (
|
||||
SELECT 1
|
||||
FROM product_catalog product
|
||||
WHERE product.id = $1
|
||||
AND product.canonical_sku = LEFT('tpl:' || BTRIM(rule.rule_key), 64)
|
||||
)
|
||||
) AS template_rule_count
|
||||
`,
|
||||
[id],
|
||||
)
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -78,7 +78,9 @@ async function hasActiveWorkOrderCost(ruleId: number, client?: DbClient) {
|
||||
/**
|
||||
* 接单模板的商品投影。
|
||||
*
|
||||
* 模板负责名称、分类和匹配配置;商品状态仍由运营在成本中心显式启停。
|
||||
* 模板是商品身份、状态和匹配配置的唯一来源(3.4.4):只要模板存在,它的
|
||||
* tpl:<rule_key> 商品就必须是 active,并且 work_product_rules.canonical_product_id
|
||||
* 始终指向该商品;停用模板也建 active 商品,才能先在成本中心配置成本。
|
||||
* 这里只写商品身份和模板属性,不修改成本版本金额,避免模板入口成为价格真源。
|
||||
*/
|
||||
export async function syncWorkOrderTemplateProduct(
|
||||
@@ -105,6 +107,7 @@ export async function syncWorkOrderTemplateProduct(
|
||||
sharingUnitReward: Number(rule.sharing_unit_reward || 0),
|
||||
sharingAutoFromOrder: rule.sharing_auto_from_order === true,
|
||||
}
|
||||
const templateSku = buildTemplateProductSku(rule.rule_key)
|
||||
const result = await runQuery<{ id: number; status: string }>(
|
||||
client,
|
||||
`
|
||||
@@ -117,12 +120,15 @@ export async function syncWorkOrderTemplateProduct(
|
||||
category = EXCLUDED.category,
|
||||
unit_name = EXCLUDED.unit_name,
|
||||
source_kind = EXCLUDED.source_kind,
|
||||
attributes_json = COALESCE(product_catalog.attributes_json, '{}'::jsonb) || EXCLUDED.attributes_json,
|
||||
status = 'active',
|
||||
attributes_json = (COALESCE(product_catalog.attributes_json, '{}'::jsonb) - 'templateDeleted')
|
||||
|| EXCLUDED.attributes_json,
|
||||
updated_at = EXCLUDED.updated_at
|
||||
WHERE product_catalog.source_kind = 'work_order'
|
||||
RETURNING id, status
|
||||
`,
|
||||
[
|
||||
buildTemplateProductSku(rule.rule_key),
|
||||
templateSku,
|
||||
rule.product_name,
|
||||
rule.category_name || '',
|
||||
inferTemplateUnitName(rule.product_name),
|
||||
@@ -132,20 +138,35 @@ export async function syncWorkOrderTemplateProduct(
|
||||
)
|
||||
const productId = Number(result.rows[0]?.id || 0)
|
||||
if (!productId) {
|
||||
// ON CONFLICT 命中但 DO UPDATE 的 WHERE 不成立:该标准 SKU 已被非接单模板商品占用。
|
||||
// 模板不得劫持这类商品(来源、成本版本、渠道映射都可能属于别的业务),必须人工先处理。
|
||||
const occupied = await runQuery<{ source_kind: string | null }>(
|
||||
client,
|
||||
'SELECT source_kind FROM product_catalog WHERE canonical_sku = $1 LIMIT 1',
|
||||
[templateSku],
|
||||
)
|
||||
if (occupied.rows[0]) {
|
||||
throw createHttpError(`标准 SKU ${templateSku} 已被非接单模板商品占用,请先处理该商品`, {
|
||||
statusCode: 409,
|
||||
errorCode: 'cost_template_sku_occupied',
|
||||
})
|
||||
}
|
||||
throw createHttpError('接单模板标准商品投影失败', { statusCode: 500 })
|
||||
}
|
||||
await runQuery(
|
||||
client,
|
||||
`UPDATE work_product_rules
|
||||
SET canonical_product_id = $1
|
||||
WHERE id = $2`,
|
||||
[productId, rule.id],
|
||||
SET canonical_product_id = $1,
|
||||
updated_at = $2
|
||||
WHERE id = $3`,
|
||||
[productId, now, rule.id],
|
||||
)
|
||||
return {
|
||||
rule,
|
||||
productId,
|
||||
hasActiveCost,
|
||||
status: result.rows[0]?.status === 'archived' ? 'archived' : 'active',
|
||||
// 模板存在就恒为 active:归档只在模板删除时发生。
|
||||
status: 'active' as const,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+328
@@ -0,0 +1,328 @@
|
||||
/**
|
||||
* 接单模板商品状态对齐集成测试(需要真实 PostgreSQL)。
|
||||
*
|
||||
* 口径:docs/统一订单履约与财务模型-权威版.md 3.4.4
|
||||
* 模板存在 ⇒ 其 tpl:<rule_key> 商品必须存在、canonical_product_id 指向它、且 status = 'active';
|
||||
* 只有删除模板才归档商品;商品接口不得归档或删除仍被模板引用的商品。
|
||||
*
|
||||
* WORK_ORDER_TEMPLATE_COST_TEST_DATABASE_URL=postgres://... \
|
||||
* npx tsx --test src/services/cost-center/work-order-template-product.integration.test.ts
|
||||
*/
|
||||
import assert from 'node:assert/strict'
|
||||
import { after, test } from 'node:test'
|
||||
|
||||
const TEST_DATABASE_URL = String(
|
||||
process.env.WORK_ORDER_TEMPLATE_COST_TEST_DATABASE_URL || '',
|
||||
).trim()
|
||||
if (TEST_DATABASE_URL) {
|
||||
process.env.DATABASE_URL = TEST_DATABASE_URL
|
||||
}
|
||||
const SKIP = !TEST_DATABASE_URL ? '未设置 WORK_ORDER_TEMPLATE_COST_TEST_DATABASE_URL' : false
|
||||
|
||||
if (TEST_DATABASE_URL) {
|
||||
after(async () => {
|
||||
const { closeDb } = await import('../../db/client.js')
|
||||
await closeDb()
|
||||
})
|
||||
}
|
||||
|
||||
type TemplateFixture = {
|
||||
ruleId: number
|
||||
productId: number
|
||||
ruleKey: string
|
||||
productName: string
|
||||
}
|
||||
|
||||
async function createTemplateFixture(label: string): Promise<TemplateFixture> {
|
||||
const { saveAdminWorkProductRule } =
|
||||
await import('../worker-platform/admin-worker-catalog-service.js')
|
||||
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
||||
const productName = `模板商品对齐测试-${label}-${suffix}`
|
||||
const created = await saveAdminWorkProductRule({
|
||||
productName,
|
||||
itemTitle: productName,
|
||||
itemTitleMatchType: 'exact',
|
||||
matchType: 'exact',
|
||||
enabled: true,
|
||||
autoCreate: true,
|
||||
})
|
||||
const fixture = {
|
||||
ruleId: Number(created.rule.ruleId),
|
||||
productId: Number(created.productId),
|
||||
ruleKey: created.rule.ruleKey,
|
||||
productName,
|
||||
}
|
||||
assert.ok(fixture.ruleId > 0)
|
||||
assert.ok(fixture.productId > 0)
|
||||
return fixture
|
||||
}
|
||||
|
||||
/** 只清理本用例自己创建的数据,不触碰既有记录。 */
|
||||
async function cleanupTemplateFixture(fixture: TemplateFixture) {
|
||||
const { query } = await import('../../db/client.js')
|
||||
await query('DELETE FROM cost_snapshots WHERE canonical_product_id = $1', [fixture.productId])
|
||||
await query(
|
||||
`DELETE FROM cost_versions
|
||||
WHERE work_product_rule_id = $1 OR canonical_product_id = $2`,
|
||||
[fixture.ruleId, fixture.productId],
|
||||
)
|
||||
await query('DELETE FROM channel_product_mappings WHERE canonical_product_id = $1', [
|
||||
fixture.productId,
|
||||
])
|
||||
await query('DELETE FROM product_channel_capabilities WHERE product_id = $1', [fixture.productId])
|
||||
await query(
|
||||
'UPDATE sku_channel_routes SET canonical_product_id = NULL WHERE canonical_product_id = $1',
|
||||
[fixture.productId],
|
||||
)
|
||||
await query('DELETE FROM work_product_rules WHERE id = $1', [fixture.ruleId])
|
||||
await query('DELETE FROM product_catalog WHERE id = $1', [fixture.productId])
|
||||
}
|
||||
|
||||
test('接单模板商品不允许通过商品接口归档', { skip: SKIP }, async () => {
|
||||
const { updateAdminProduct } = await import('./product-catalog-service.js')
|
||||
const { query } = await import('../../db/client.js')
|
||||
let fixture: TemplateFixture | null = null
|
||||
try {
|
||||
fixture = await createTemplateFixture('archive-blocked')
|
||||
|
||||
await assert.rejects(
|
||||
() => updateAdminProduct(fixture!.productId, { status: 'archived' }),
|
||||
(error: unknown) => {
|
||||
const current = error as { statusCode?: number; errorCode?: string; message?: string }
|
||||
assert.equal(current.statusCode, 409)
|
||||
assert.equal(current.errorCode, 'cost_product_template_bound')
|
||||
assert.match(String(current.message || ''), /请到「接单平台 → 接单模板」/)
|
||||
return true
|
||||
},
|
||||
)
|
||||
|
||||
const archived = await query<{ status: string }>(
|
||||
'SELECT status FROM product_catalog WHERE id = $1',
|
||||
[fixture.productId],
|
||||
)
|
||||
assert.equal(archived.rows[0]?.status, 'active')
|
||||
|
||||
// 启用(改回 active)必须允许,并且保留模板写进 attributes 的键。
|
||||
const enabled = await updateAdminProduct(fixture.productId, { status: 'active' })
|
||||
assert.equal(enabled.product.status, 'active')
|
||||
assert.equal(Number(enabled.product.attributes.ruleId), fixture.ruleId)
|
||||
} finally {
|
||||
if (fixture) await cleanupTemplateFixture(fixture)
|
||||
}
|
||||
})
|
||||
|
||||
test(
|
||||
'保存模板会把已归档的模板商品恢复为 active 并回填 canonical_product_id',
|
||||
{
|
||||
skip: SKIP,
|
||||
},
|
||||
async () => {
|
||||
const { saveAdminWorkProductRule } =
|
||||
await import('../worker-platform/admin-worker-catalog-service.js')
|
||||
const { query } = await import('../../db/client.js')
|
||||
let fixture: TemplateFixture | null = null
|
||||
try {
|
||||
fixture = await createTemplateFixture('self-heal')
|
||||
await query(`UPDATE product_catalog SET status = 'archived' WHERE id = $1`, [
|
||||
fixture.productId,
|
||||
])
|
||||
await query('UPDATE work_product_rules SET canonical_product_id = NULL WHERE id = $1', [
|
||||
fixture.ruleId,
|
||||
])
|
||||
|
||||
const saved = await saveAdminWorkProductRule({
|
||||
ruleId: fixture.ruleId,
|
||||
productName: fixture.productName,
|
||||
})
|
||||
assert.equal(saved.productStatus, 'active')
|
||||
|
||||
const product = await query<{ status: string; canonical_sku: string }>(
|
||||
'SELECT status, canonical_sku FROM product_catalog WHERE id = $1',
|
||||
[fixture.productId],
|
||||
)
|
||||
assert.equal(product.rows[0]?.canonical_sku, `tpl:${fixture.ruleKey}`)
|
||||
assert.equal(product.rows[0]?.status, 'active')
|
||||
|
||||
const relation = await query<{ canonical_product_id: number | null }>(
|
||||
'SELECT canonical_product_id FROM work_product_rules WHERE id = $1',
|
||||
[fixture.ruleId],
|
||||
)
|
||||
assert.equal(Number(relation.rows[0]?.canonical_product_id), fixture.productId)
|
||||
} finally {
|
||||
if (fixture) await cleanupTemplateFixture(fixture)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
test('停用模板不会归档商品', { skip: SKIP }, async () => {
|
||||
const { saveAdminWorkProductRule } =
|
||||
await import('../worker-platform/admin-worker-catalog-service.js')
|
||||
const { query } = await import('../../db/client.js')
|
||||
let fixture: TemplateFixture | null = null
|
||||
try {
|
||||
fixture = await createTemplateFixture('disable-keeps-product')
|
||||
// 直接置为启用,绕开「启用前必须先配成本」的前置校验(该口径不在本用例范围内)。
|
||||
await query('UPDATE work_product_rules SET enabled = TRUE WHERE id = $1', [fixture.ruleId])
|
||||
|
||||
const saved = await saveAdminWorkProductRule({
|
||||
ruleId: fixture.ruleId,
|
||||
productName: fixture.productName,
|
||||
enabled: false,
|
||||
})
|
||||
assert.equal(saved.rule.enabled, false)
|
||||
assert.equal(saved.productStatus, 'active')
|
||||
|
||||
const product = await query<{ status: string; template_deleted: string | null }>(
|
||||
`SELECT status, attributes_json ->> 'templateDeleted' AS template_deleted
|
||||
FROM product_catalog WHERE id = $1`,
|
||||
[fixture.productId],
|
||||
)
|
||||
assert.equal(product.rows[0]?.status, 'active')
|
||||
assert.equal(product.rows[0]?.template_deleted, null)
|
||||
} finally {
|
||||
if (fixture) await cleanupTemplateFixture(fixture)
|
||||
}
|
||||
})
|
||||
|
||||
test('删除模板会归档商品并写 templateDeleted', { skip: SKIP }, async () => {
|
||||
const { deleteAdminWorkProductRule } =
|
||||
await import('../worker-platform/admin-worker-catalog-service.js')
|
||||
const { query } = await import('../../db/client.js')
|
||||
let fixture: TemplateFixture | null = null
|
||||
try {
|
||||
fixture = await createTemplateFixture('delete-archives-product')
|
||||
await deleteAdminWorkProductRule(fixture.ruleId)
|
||||
|
||||
const product = await query<{ status: string; template_deleted: string | null }>(
|
||||
`SELECT status, attributes_json ->> 'templateDeleted' AS template_deleted
|
||||
FROM product_catalog WHERE id = $1`,
|
||||
[fixture.productId],
|
||||
)
|
||||
assert.equal(product.rows[0]?.status, 'archived')
|
||||
assert.equal(product.rows[0]?.template_deleted, 'true')
|
||||
} finally {
|
||||
if (fixture) await cleanupTemplateFixture(fixture)
|
||||
}
|
||||
})
|
||||
|
||||
test(
|
||||
'canonical_product_id 为 NULL 但 SKU 公式命中模板时,仍不允许归档',
|
||||
{ skip: SKIP },
|
||||
async () => {
|
||||
const { updateAdminProduct } = await import('./product-catalog-service.js')
|
||||
const { query } = await import('../../db/client.js')
|
||||
let fixture: TemplateFixture | null = null
|
||||
try {
|
||||
fixture = await createTemplateFixture('archive-blocked-null-relation')
|
||||
// 守卫的第二条分支:显式关联丢失(历史 164 回填前的数据形态),
|
||||
// 只剩 tpl:<rule_key> 精确 SKU 关系,同样必须拦住归档。
|
||||
await query('UPDATE work_product_rules SET canonical_product_id = NULL WHERE id = $1', [
|
||||
fixture.ruleId,
|
||||
])
|
||||
|
||||
await assert.rejects(
|
||||
() => updateAdminProduct(fixture!.productId, { status: 'archived' }),
|
||||
(error: unknown) => {
|
||||
const current = error as { statusCode?: number; errorCode?: string; message?: string }
|
||||
assert.equal(current.statusCode, 409)
|
||||
assert.equal(current.errorCode, 'cost_product_template_bound')
|
||||
assert.match(String(current.message || ''), /请到「接单平台 → 接单模板」/)
|
||||
return true
|
||||
},
|
||||
)
|
||||
|
||||
const product = await query<{ status: string }>(
|
||||
'SELECT status FROM product_catalog WHERE id = $1',
|
||||
[fixture.productId],
|
||||
)
|
||||
assert.equal(product.rows[0]?.status, 'active')
|
||||
} finally {
|
||||
if (fixture) await cleanupTemplateFixture(fixture)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
test(
|
||||
'已归档的模板商品仍允许改名,但改名不会改变 enabled 模板的状态口径',
|
||||
{ skip: SKIP },
|
||||
async () => {
|
||||
const { updateAdminProduct } = await import('./product-catalog-service.js')
|
||||
const { query } = await import('../../db/client.js')
|
||||
let fixture: TemplateFixture | null = null
|
||||
try {
|
||||
fixture = await createTemplateFixture('rename-archived')
|
||||
// 直接置为启用(绕开「启用前必须先配成本」的前置校验)并模拟历史误归档。
|
||||
await query('UPDATE work_product_rules SET enabled = TRUE WHERE id = $1', [fixture.ruleId])
|
||||
await query(`UPDATE product_catalog SET status = 'archived' WHERE id = $1`, [
|
||||
fixture.productId,
|
||||
])
|
||||
|
||||
// 请求不带 status:只是改名,不能被「本来就是 archived」误拦。
|
||||
const renamed = `已归档改名-${fixture.ruleKey}-${Date.now()}`
|
||||
const updated = await updateAdminProduct(fixture.productId, { canonicalName: renamed })
|
||||
assert.equal(updated.product.canonicalName, renamed)
|
||||
assert.equal(updated.product.status, 'archived')
|
||||
assert.equal(Number(updated.product.attributes.ruleId), fixture.ruleId)
|
||||
|
||||
// 改名不得改动模板状态口径:模板仍启用,商品仍 archived(只有模板写入口能复活它)。
|
||||
const rule = await query<{ enabled: boolean }>(
|
||||
'SELECT enabled FROM work_product_rules WHERE id = $1',
|
||||
[fixture.ruleId],
|
||||
)
|
||||
assert.equal(rule.rows[0]?.enabled, true)
|
||||
|
||||
// 回写同一个 archived 状态是无操作(不跨状态),不应拦。
|
||||
const noop = await updateAdminProduct(fixture!.productId, { status: 'archived' })
|
||||
assert.equal(noop.product.status, 'archived')
|
||||
|
||||
// 显式改回 active 允许(等于运营手工修回误归档)。
|
||||
const restored = await updateAdminProduct(fixture!.productId, { status: 'active' })
|
||||
assert.equal(restored.product.status, 'active')
|
||||
|
||||
// 真正把 active 改成 archived 仍要拦。
|
||||
await assert.rejects(
|
||||
() =>
|
||||
updateAdminProduct(fixture!.productId, { canonicalName: renamed, status: 'archived' }),
|
||||
(error: unknown) => {
|
||||
const current = error as { statusCode?: number; errorCode?: string }
|
||||
assert.equal(current.statusCode, 409)
|
||||
assert.equal(current.errorCode, 'cost_product_template_bound')
|
||||
return true
|
||||
},
|
||||
)
|
||||
} finally {
|
||||
if (fixture) await cleanupTemplateFixture(fixture)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
test('模板商品不允许被删除商品接口硬删', { skip: SKIP }, async () => {
|
||||
const { deleteAdminProduct } = await import('./product-catalog-service.js')
|
||||
const { query } = await import('../../db/client.js')
|
||||
let fixture: TemplateFixture | null = null
|
||||
try {
|
||||
fixture = await createTemplateFixture('delete-blocked')
|
||||
// 历史数据的 canonical_product_id 可能是 NULL,只有精确 tpl SKU 关系仍成立。
|
||||
await query('UPDATE work_product_rules SET canonical_product_id = NULL WHERE id = $1', [
|
||||
fixture.ruleId,
|
||||
])
|
||||
|
||||
await assert.rejects(
|
||||
() => deleteAdminProduct(fixture!.productId),
|
||||
(error: unknown) => {
|
||||
const current = error as { statusCode?: number; errorCode?: string; message?: string }
|
||||
assert.equal(current.statusCode, 409)
|
||||
assert.equal(current.errorCode, 'cost_product_in_use')
|
||||
assert.match(String(current.message || ''), /1 个接单模板/)
|
||||
return true
|
||||
},
|
||||
)
|
||||
|
||||
const product = await query<{ id: number }>('SELECT id FROM product_catalog WHERE id = $1', [
|
||||
fixture.productId,
|
||||
])
|
||||
assert.equal(Number(product.rows[0]?.id), fixture.productId)
|
||||
} finally {
|
||||
if (fixture) await cleanupTemplateFixture(fixture)
|
||||
}
|
||||
})
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
Switch,
|
||||
Tabs,
|
||||
Tag,
|
||||
Tooltip,
|
||||
Typography,
|
||||
} from 'antd'
|
||||
import type { TableColumnsType } from 'antd'
|
||||
@@ -63,7 +64,7 @@ import {
|
||||
type ProductFormValues,
|
||||
} from './shared'
|
||||
|
||||
/** 全量同步选项:停用模板默认不建商品,勾选后建成「归档」商品。 */
|
||||
/** 全量同步选项:默认同时同步停用模板(否则停用模板的商品永远建不出来、也不能先配成本)。 */
|
||||
type BootstrapSyncOptions = { includeDisabledTemplates: boolean }
|
||||
|
||||
function DisabledTemplateSyncOption({
|
||||
@@ -82,9 +83,10 @@ function DisabledTemplateSyncOption({
|
||||
onChange(event.target.checked)
|
||||
}}
|
||||
>
|
||||
<strong>同时为停用模板建商品(归档状态,不参与成本统计)</strong>
|
||||
<strong>同时为停用模板建商品(用于先配成本)</strong>
|
||||
<div style={{ color: '#64748b', fontSize: 12, marginTop: 2 }}>
|
||||
默认只同步启用模板;停用模板一般是历史遗留,建出来的商品会以「归档」出现在商品列表里。
|
||||
默认同时同步停用模板;取消勾选则只同步启用模板。停用模板的商品同样建成启用状态,
|
||||
方便先配成本再启用模板。
|
||||
</div>
|
||||
</Checkbox>
|
||||
)
|
||||
@@ -108,7 +110,7 @@ export function ProductCatalogPanel() {
|
||||
const [productStatusUpdatingId, setProductStatusUpdatingId] = useState<number | null>(null)
|
||||
const [bootstrapPreviewing, setBootstrapPreviewing] = useState(false)
|
||||
const [bootstrapApplying, setBootstrapApplying] = useState(false)
|
||||
const bootstrapSyncOptionsRef = useRef<BootstrapSyncOptions>({ includeDisabledTemplates: false })
|
||||
const bootstrapSyncOptionsRef = useRef<BootstrapSyncOptions>({ includeDisabledTemplates: true })
|
||||
const [productPage, setProductPage] = useState(1)
|
||||
const [productPageSize, setProductPageSize] = useState(ADMIN_DEFAULT_PAGE_SIZE)
|
||||
const [productModalOpen, setProductModalOpen] = useState(false)
|
||||
@@ -176,7 +178,7 @@ export function ProductCatalogPanel() {
|
||||
try {
|
||||
const response = await previewAdminTemplateProductBootstrap(backfillPayload())
|
||||
const data = response.data
|
||||
bootstrapSyncOptionsRef.current.includeDisabledTemplates = false
|
||||
bootstrapSyncOptionsRef.current.includeDisabledTemplates = true
|
||||
modal.confirm({
|
||||
title: '修复接单模板历史商品与映射',
|
||||
width: 720,
|
||||
@@ -193,7 +195,8 @@ export function ProductCatalogPanel() {
|
||||
<strong>{data.disabledTemplateCount}</strong>)。
|
||||
</span>
|
||||
<span>
|
||||
启用模板全部建标准商品:将新建 <strong>{data.productCreateCount}</strong> 个、复用{' '}
|
||||
启用模板全部建标准商品(停用模板可勾选一并建):将新建{' '}
|
||||
<strong>{data.productCreateCount}</strong> 个、复用{' '}
|
||||
<strong>{data.productExistingCount}</strong>{' '}
|
||||
个(已有模板商品会同步刷新名称、分类、发单金额)。
|
||||
</span>
|
||||
@@ -215,7 +218,7 @@ export function ProductCatalogPanel() {
|
||||
</span>
|
||||
{data.disabledTemplateCount > 0 ? (
|
||||
<DisabledTemplateSyncOption
|
||||
initialValue={false}
|
||||
initialValue={true}
|
||||
onChange={(value) => {
|
||||
bootstrapSyncOptionsRef.current = { includeDisabledTemplates: value }
|
||||
}}
|
||||
@@ -274,10 +277,13 @@ export function ProductCatalogPanel() {
|
||||
: ''
|
||||
const disabledText =
|
||||
applied.disabledTemplateCount > 0
|
||||
? `(含停用模板 ${applied.disabledTemplateCount} 个,已建为归档商品)`
|
||||
? `(含停用模板 ${applied.disabledTemplateCount} 个,商品同样建成启用状态)`
|
||||
: ''
|
||||
// 「复用」只在真的复用时才提示:模板商品恒由模板同步生成,恒显示 0 会误导运营。
|
||||
const reusedText =
|
||||
applied.reusedProductCount > 0 ? `、复用 ${applied.reusedProductCount} 个` : ''
|
||||
message.success(
|
||||
`已同步 ${applied.templateCount} 个模板商品:新建 ${applied.createdProductCount} 个、刷新 ${applied.updatedProductCount} 个、复用 ${applied.reusedProductCount} 个${disabledText};新增 ${applied.createdMappingCount} 条映射,回填 ${applied.mappedOrderItemCount} 个订单项${rebuildText}${conflictText}`,
|
||||
`已同步 ${applied.templateCount} 个模板商品:新建 ${applied.createdProductCount} 个、刷新 ${applied.updatedProductCount} 个${reusedText}${disabledText};新增 ${applied.createdMappingCount} 条映射,回填 ${applied.mappedOrderItemCount} 个订单项${rebuildText}${conflictText}`,
|
||||
)
|
||||
refreshAll()
|
||||
} catch (error) {
|
||||
@@ -317,6 +323,21 @@ export function ProductCatalogPanel() {
|
||||
setProductModalOpen(true)
|
||||
}
|
||||
|
||||
/**
|
||||
* 商品编辑/改状态/删除后的统一失效。
|
||||
*
|
||||
* 成本中心用前缀谓词(含 admin-cost-center-exceptions* 等子查询),
|
||||
* 商品的模板归属由模板写回,所以同时失效接单模板列表。
|
||||
*/
|
||||
async function invalidateProductQueries() {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (query) => String(query.queryKey[0] || '').startsWith('admin-cost-center'),
|
||||
}),
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-product-rules'] }),
|
||||
])
|
||||
}
|
||||
|
||||
async function submitProduct(values: ProductFormValues) {
|
||||
try {
|
||||
if (editingProduct) {
|
||||
@@ -332,7 +353,7 @@ export function ProductCatalogPanel() {
|
||||
message.success('标准商品已创建')
|
||||
}
|
||||
setProductModalOpen(false)
|
||||
refreshAll()
|
||||
await invalidateProductQueries()
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : '保存标准商品失败')
|
||||
}
|
||||
@@ -442,9 +463,7 @@ export function ProductCatalogPanel() {
|
||||
try {
|
||||
await updateAdminProductCatalog(row.id, { status: checked ? 'active' : 'archived' })
|
||||
message.success(checked ? '标准商品已启用' : '标准商品已归档')
|
||||
await queryClient.invalidateQueries({ queryKey: ['admin-cost-center-products'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-cost-center-overview'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-cost-center-options'] })
|
||||
await invalidateProductQueries()
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : '更新商品状态失败')
|
||||
} finally {
|
||||
@@ -467,7 +486,7 @@ export function ProductCatalogPanel() {
|
||||
try {
|
||||
await deleteAdminProductCatalog(item.id)
|
||||
message.success('标准商品已删除')
|
||||
refreshAll()
|
||||
await invalidateProductQueries()
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : '删除标准商品失败')
|
||||
}
|
||||
@@ -630,25 +649,39 @@ export function ProductCatalogPanel() {
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 110,
|
||||
render: (value: ProductCatalogItem['status'], row) => (
|
||||
<Space size={6}>
|
||||
render: (value: ProductCatalogItem['status'], row) => {
|
||||
const templateManaged = row.templateRuleId != null
|
||||
const switchNode = (
|
||||
<Switch
|
||||
size="small"
|
||||
checked={value === 'active'}
|
||||
loading={productStatusUpdatingId === row.id}
|
||||
disabled={
|
||||
!canConfig || (productStatusUpdatingId !== null && productStatusUpdatingId !== row.id)
|
||||
templateManaged ||
|
||||
!canConfig ||
|
||||
(productStatusUpdatingId !== null && productStatusUpdatingId !== row.id)
|
||||
}
|
||||
onChange={(checked) => void toggleProductStatus(row, checked)}
|
||||
/>
|
||||
<Typography.Text
|
||||
type={value === 'active' ? 'success' : 'secondary'}
|
||||
style={{ fontSize: 12 }}
|
||||
>
|
||||
{value === 'active' ? '启用' : '归档'}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
),
|
||||
)
|
||||
return (
|
||||
<Space size={6}>
|
||||
{templateManaged ? (
|
||||
<Tooltip title="接单模板商品的状态由模板管理;删除模板后自动归档">
|
||||
<span style={{ display: 'inline-block' }}>{switchNode}</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
switchNode
|
||||
)}
|
||||
<Typography.Text
|
||||
type={value === 'active' ? 'success' : 'secondary'}
|
||||
style={{ fontSize: 12 }}
|
||||
>
|
||||
{value === 'active' ? '启用' : '归档'}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
@@ -931,8 +964,15 @@ export function ProductCatalogPanel() {
|
||||
<Form.Item name="unitName" label="单位">
|
||||
<Input placeholder="件 / 个 / 颗" />
|
||||
</Form.Item>
|
||||
<Form.Item name="status" label="状态">
|
||||
<Form.Item
|
||||
name="status"
|
||||
label="状态"
|
||||
extra={
|
||||
editingProduct?.templateRuleId != null ? '接单模板商品的状态由模板管理' : undefined
|
||||
}
|
||||
>
|
||||
<Select
|
||||
disabled={editingProduct?.templateRuleId != null}
|
||||
options={[
|
||||
{ value: 'active', label: '启用' },
|
||||
{ value: 'archived', label: '归档' },
|
||||
|
||||
@@ -318,6 +318,20 @@ export default function ProductRulesPanel() {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 模板写入口会同步写回标准商品(状态 / 名称 / 成本口径),
|
||||
* 所以保存、启停、删除模板后都要按前缀失效整个成本中心(含 admin-cost-center-exceptions*),
|
||||
* 不再逐个列举查询键。
|
||||
*/
|
||||
async function invalidateAfterTemplateWrite() {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-product-rules'] }),
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (query) => String(query.queryKey[0] || '').startsWith('admin-cost-center'),
|
||||
}),
|
||||
])
|
||||
}
|
||||
|
||||
async function saveRule(values: {
|
||||
ruleId?: number
|
||||
ruleKey?: string
|
||||
@@ -392,15 +406,10 @@ export default function ProductRulesPanel() {
|
||||
resetRuleForm()
|
||||
}
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['admin-worker-platform-product-rules'],
|
||||
}),
|
||||
invalidateAfterTemplateWrite(),
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['admin-worker-platform-summary'],
|
||||
}),
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (query) => String(query.queryKey[0] || '').startsWith('admin-cost-center'),
|
||||
}),
|
||||
])
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : '保存失败')
|
||||
@@ -441,12 +450,7 @@ export default function ProductRulesPanel() {
|
||||
autoCreate: rule.autoCreate,
|
||||
})
|
||||
message.success(`规则「${rule.ruleKey}」已${enabled ? '启用' : '停用'}`)
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: ['admin-worker-platform-product-rules'],
|
||||
})
|
||||
await queryClient.invalidateQueries({
|
||||
predicate: (query) => String(query.queryKey[0] || '').startsWith('admin-cost-center'),
|
||||
})
|
||||
await invalidateAfterTemplateWrite()
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : '修改状态失败')
|
||||
}
|
||||
@@ -459,12 +463,12 @@ export default function ProductRulesPanel() {
|
||||
resetRuleForm()
|
||||
}
|
||||
message.success('接单模板已删除')
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: ['admin-worker-platform-product-rules'],
|
||||
})
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: ['admin-worker-platform-product-mappings'],
|
||||
})
|
||||
await Promise.all([
|
||||
invalidateAfterTemplateWrite(),
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['admin-worker-platform-product-mappings'],
|
||||
}),
|
||||
])
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : '删除失败')
|
||||
}
|
||||
|
||||
@@ -66,6 +66,8 @@ export interface ProductCatalogItem {
|
||||
costVersionCount: number
|
||||
activeCostAmountFen?: number | null
|
||||
activeCostEffectiveFrom?: string | null
|
||||
/** 接管该商品的接单模板 id;非空表示状态由模板管理。 */
|
||||
templateRuleId?: number | null
|
||||
templatePricingMode?: 'fixed' | 'unit' | null
|
||||
templateEnabled?: boolean | null
|
||||
templateSharingEnabled?: boolean | null
|
||||
|
||||
Reference in New Issue
Block a user