Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fac6437bc0 | ||
|
|
375c10162a | ||
|
|
dafa45f348 | ||
|
|
7c7810261b |
@@ -44,3 +44,6 @@ send_code/
|
||||
|
||||
artifacts/
|
||||
har/
|
||||
|
||||
# 扩展构建产物(本地打包给客服安装,不入库)
|
||||
apps/extensions/*.zip
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
@@ -35,14 +35,36 @@ test('外部 Connector 状态快照复用统一绑定写入和确认门禁', ()
|
||||
assert.match(customerService, /if \(!decision\.canConfirmBinding\)/)
|
||||
})
|
||||
|
||||
test('后台半自动任务列表使用创建顺序,页面刷新不会按状态或更新时间重排', () => {
|
||||
test('后台半自动任务列表按待办队列排序:先归属分桶,再按最近真实变更倒序', () => {
|
||||
const adminService = source('semi-auto-admin-service.ts')
|
||||
const listStart = adminService.indexOf('export async function listAdminSemiAutoTasks')
|
||||
const listEnd = adminService.indexOf('export async function getAdminSemiAutoTask')
|
||||
assert.ok(listStart > 0)
|
||||
assert.ok(listEnd > listStart)
|
||||
const listBody = adminService.slice(listStart, listEnd)
|
||||
assert.match(listBody, /ORDER BY task\.created_at DESC, task\.id DESC/)
|
||||
assert.doesNotMatch(listBody, /CASE task\.execution_status/)
|
||||
assert.doesNotMatch(listBody, /task\.updated_at DESC/)
|
||||
// 列表必须引用同一个排序常量,不能各自拼一份 ORDER BY。
|
||||
assert.match(listBody, /\$\{SEMI_AUTO_TASK_QUEUE_ORDER_SQL\}/)
|
||||
|
||||
const orderStart = adminService.indexOf('const SEMI_AUTO_TASK_QUEUE_ORDER_SQL')
|
||||
const orderEnd = adminService.indexOf('export async function listAdminSemiAutoTasks')
|
||||
assert.ok(orderStart > 0)
|
||||
assert.ok(orderEnd > orderStart)
|
||||
const orderSql = adminService.slice(orderStart, orderEnd)
|
||||
|
||||
// 分桶只看正式状态字段:客户已就绪 > 客服处理中 > 需修复 > 客户处理中 > 客户未开始 > 已完成/已取消。
|
||||
assert.match(orderSql, /WHEN task\.execution_status = 'waiting_operator' THEN 0/)
|
||||
assert.match(orderSql, /WHEN task\.execution_status = 'processing' THEN 1/)
|
||||
assert.match(orderSql, /WHEN task\.execution_status = 'failed' THEN 2/)
|
||||
assert.match(orderSql, /WHEN task\.execution_status = 'waiting_customer'\s+AND \(/)
|
||||
assert.match(orderSql, /THEN 3/)
|
||||
assert.match(orderSql, /WHEN task\.execution_status = 'waiting_customer' THEN 4/)
|
||||
assert.match(orderSql, /WHEN task\.execution_status = 'completed' THEN 8/)
|
||||
assert.match(orderSql, /WHEN task\.execution_status = 'cancelled' THEN 9/)
|
||||
|
||||
// 同桶按最近一次真实状态变更倒序,并带 id 做确定性兜底。
|
||||
assert.match(orderSql, /task\.updated_at DESC,\s*\n\s*task\.id DESC/)
|
||||
// 创建顺序不再是主排序键(否则新订单会盖掉正在等客服处理的任务)。
|
||||
assert.doesNotMatch(orderSql, /task\.created_at DESC/)
|
||||
// 分桶不得复制 displayStatus 的完整判定链:待办文案仍由 displayStatus 单点输出。
|
||||
assert.doesNotMatch(orderSql, /bind_confirm_state|rebind_block_scope|binding_flow_state/)
|
||||
})
|
||||
|
||||
@@ -62,6 +62,38 @@ import {
|
||||
SEMI_AUTO_NOW,
|
||||
} from './semi-auto-task-state-service.js'
|
||||
|
||||
/**
|
||||
* 后台半自动任务列表的队列顺序。
|
||||
*
|
||||
* 这是运营待办队列,不是审计流水:先按「谁在等我」分桶,同桶内按最近一次真实状态变更倒序。
|
||||
* 分桶只读正式状态字段(execution_status / login_status / binding_status /
|
||||
* customer_link_opened_at),不复制 displayStatus 的判定链;具体待办文案仍由
|
||||
* displayStatus 单点输出,页面不重新解释状态。
|
||||
*
|
||||
* 之前按 `created_at DESC` 排序,而页面展示的是「更新时间」,且 `updated_at` 会被
|
||||
* 无变化的轮询/对账推进,导致列表既与展示列不一致、又每次刷新都重排;
|
||||
* `updated_at` 已在写入口收敛为「真实状态变更」,可以直接作为同桶排序键。
|
||||
*/
|
||||
const SEMI_AUTO_TASK_QUEUE_ORDER_SQL = `
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN task.execution_status = 'waiting_operator' THEN 0
|
||||
WHEN task.execution_status = 'processing' THEN 1
|
||||
WHEN task.execution_status = 'failed' THEN 2
|
||||
WHEN task.execution_status = 'waiting_customer'
|
||||
AND (
|
||||
task.login_status <> 'waiting_login'
|
||||
OR task.binding_status <> 'not_started'
|
||||
OR task.customer_link_opened_at IS NOT NULL
|
||||
) THEN 3
|
||||
WHEN task.execution_status = 'waiting_customer' THEN 4
|
||||
WHEN task.execution_status = 'completed' THEN 8
|
||||
WHEN task.execution_status = 'cancelled' THEN 9
|
||||
ELSE 5
|
||||
END,
|
||||
task.updated_at DESC,
|
||||
task.id DESC`
|
||||
|
||||
export async function listAdminSemiAutoTasks(input: Record<string, unknown> = {}) {
|
||||
await ensureSemiAutoTasksForAdminList()
|
||||
const page = Math.max(1, Math.trunc(Number(input.page) || 1))
|
||||
@@ -116,7 +148,7 @@ export async function listAdminSemiAutoTasks(input: Record<string, unknown> = {}
|
||||
const result = await query<TaskRow>(
|
||||
`${TASK_SELECT}
|
||||
WHERE ${where}
|
||||
ORDER BY task.created_at DESC, task.id DESC
|
||||
${SEMI_AUTO_TASK_QUEUE_ORDER_SQL}
|
||||
LIMIT $${listParams.length - 1} OFFSET $${listParams.length}`,
|
||||
listParams,
|
||||
)
|
||||
|
||||
@@ -690,7 +690,10 @@ export async function startPublicBinding(
|
||||
decision.allowedActions.includes('start_rebind') ||
|
||||
decision.allowedActions.includes('refresh_rebind_qr')
|
||||
// 首次绑定允许自动出码(页面进入第一步就要码);换绑必须由客户显式点「重新扫码换绑」触发。
|
||||
const wantsFirstBinding = canStartFirstBinding
|
||||
// 已经有一张有效二维码时,未显式要求刷新的调用直接复用,避免任何轮询/重入路径反复重开码。
|
||||
const explicitRefresh = input.intent === 'rebind' || input.forceRebind === true
|
||||
const reuseFirstBindingQr = decision.flowState === 'first_bind_qr_pending' && !explicitRefresh
|
||||
const wantsFirstBinding = canStartFirstBinding && !reuseFirstBindingQr
|
||||
const wantsRebind = (input.intent === 'rebind' || input.forceRebind === true) && canStartRebind
|
||||
if (!wantsFirstBinding && !wantsRebind) {
|
||||
return {
|
||||
|
||||
@@ -279,13 +279,20 @@ function deriveEventTypeFromReason(reason: string): string {
|
||||
return normalized || 'semi_auto_state_converged'
|
||||
}
|
||||
|
||||
/** 行锁只取状态收敛需要的列,避免在轮询热路径上重复做 TASK_SELECT 的 join。 */
|
||||
/**
|
||||
* 行锁只取任务表本行的全部列,不做 TASK_SELECT 的 join。
|
||||
*
|
||||
* 需要整行是因为「本次补丁是否真的改变了任务」要靠补丁列与当前值逐列比较:
|
||||
* 无变化的轮询、Connector 对账、绑定决策重算都不得推进 `updated_at`,
|
||||
* 否则后台列表的「更新时间」会自己跳动,任何按更新时间的排序都不可信。
|
||||
*/
|
||||
type SemiAutoTaskLockedRow = {
|
||||
id: number
|
||||
platform: SemiAutoPlatform
|
||||
login_status: LoginStatus
|
||||
binding_status: BindingStatus
|
||||
execution_status: ExecutionStatus
|
||||
[column: string]: unknown
|
||||
}
|
||||
|
||||
async function lockSemiAutoTaskRow(
|
||||
@@ -293,7 +300,7 @@ async function lockSemiAutoTaskRow(
|
||||
taskId: number,
|
||||
): Promise<SemiAutoTaskLockedRow> {
|
||||
const result = await client.query<SemiAutoTaskLockedRow>(
|
||||
`SELECT id, platform, login_status, binding_status, execution_status
|
||||
`SELECT *
|
||||
FROM semi_auto_tasks
|
||||
WHERE id = $1
|
||||
FOR UPDATE`,
|
||||
@@ -309,6 +316,94 @@ async function lockSemiAutoTaskRow(
|
||||
return row
|
||||
}
|
||||
|
||||
/**
|
||||
* 空串与 NULL 在任务状态里同义:页面、门禁和查询都只判断「有没有值」。
|
||||
* 补丁把 NULL 写成空串时不推进 updated_at,也不产生无意义写入。
|
||||
*/
|
||||
function normalizeStateScalar(value: unknown): string {
|
||||
if (value === null || value === undefined) return ''
|
||||
if (typeof value === 'boolean') return value ? 'true' : 'false'
|
||||
if (typeof value === 'number' || typeof value === 'bigint') return String(value)
|
||||
return String(value)
|
||||
}
|
||||
|
||||
function stateScalarEquals(current: unknown, next: unknown): boolean {
|
||||
return normalizeStateScalar(current) === normalizeStateScalar(next)
|
||||
}
|
||||
|
||||
/** JSON 列按内容比较,键顺序不同不算变化。 */
|
||||
function stableStateJson(value: unknown): string {
|
||||
if (value === null || value === undefined) return ''
|
||||
const normalize = (input: unknown): unknown => {
|
||||
if (Array.isArray(input)) return input.map(normalize)
|
||||
if (input && typeof input === 'object') {
|
||||
return Object.fromEntries(
|
||||
Object.keys(input as Record<string, unknown>)
|
||||
.sort()
|
||||
.map((key) => [key, normalize((input as Record<string, unknown>)[key])]),
|
||||
)
|
||||
}
|
||||
return input ?? null
|
||||
}
|
||||
return JSON.stringify(normalize(value))
|
||||
}
|
||||
|
||||
/**
|
||||
* 时间列比较:
|
||||
* - null 只在当前也是空时算「没变化」;
|
||||
* - 静态时间按绝对时间点比较;
|
||||
* - `coalesce_now` 当前已有值即没变化(原 CASE COALESCE 语义);
|
||||
* - `now` 与秒级偏移会生成新的时间点,一律算变化。
|
||||
*/
|
||||
function stateTimeEquals(current: unknown, next: SemiAutoTaskTimeValue): boolean {
|
||||
if (next === null) return current === null || current === undefined
|
||||
if (typeof next === 'string') {
|
||||
if (current === null || current === undefined) return false
|
||||
const currentTime = new Date(String(current)).getTime()
|
||||
const nextTime = new Date(next).getTime()
|
||||
return Number.isFinite(currentTime) && Number.isFinite(nextTime) && currentTime === nextTime
|
||||
}
|
||||
if (next.kind === 'now') return false
|
||||
// coalesce_now 只在当前为空时才写入,已有值说明本次不会变化。
|
||||
if (next.kind === 'coalesce_now') return current !== null && current !== undefined
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* 本次补丁是否真的改变了任务。
|
||||
*
|
||||
* 只比较补丁里出现的列;`extra` 的每列同样参与比较(例如 connector_state_version
|
||||
* 推进代表 Connector 真的推了新的平台快照)。未登记字段在写库阶段报错,这里跳过。
|
||||
*/
|
||||
export function semiAutoTaskPatchChangesState(
|
||||
current: Record<string, unknown>,
|
||||
patch: SemiAutoTaskStatePatch,
|
||||
): boolean {
|
||||
for (const [key, value] of Object.entries(patch)) {
|
||||
if (value === undefined) continue
|
||||
if (key === 'extra') {
|
||||
const extra = (value || {}) as Record<string, unknown>
|
||||
for (const [column, extraValue] of Object.entries(extra)) {
|
||||
if (extraValue === undefined) continue
|
||||
if (!stateScalarEquals(current[column], extraValue)) return true
|
||||
}
|
||||
continue
|
||||
}
|
||||
const meta = PATCH_COLUMN_MAP[key]
|
||||
if (!meta) continue
|
||||
if (meta.kind === 'time') {
|
||||
if (!stateTimeEquals(current[meta.column], value as SemiAutoTaskTimeValue)) return true
|
||||
continue
|
||||
}
|
||||
if (meta.kind === 'json') {
|
||||
if (stableStateJson(current[meta.column]) !== stableStateJson(value)) return true
|
||||
continue
|
||||
}
|
||||
if (!stateScalarEquals(current[meta.column], value)) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function assertExpectedGuard(
|
||||
current: SemiAutoTaskLockedRow,
|
||||
expected: ConvergeSemiAutoTaskStateInput['expected'],
|
||||
@@ -459,6 +554,14 @@ export async function convergeSemiAutoTaskState(
|
||||
pushParam(meta.column, value)
|
||||
}
|
||||
for (const [column, value] of Object.entries(patch.extra || {})) {
|
||||
if (assignments.some((item) => item.startsWith(`${column} = `))) {
|
||||
// 同一列在类型化字段与 extra 里同时出现会拼出 `col = $1, col = $2`,PG 直接报错。
|
||||
throw createHttpError('半自动任务状态补丁包含重复列', {
|
||||
statusCode: 500,
|
||||
errorCode: 'semi_auto_task_patch_column_duplicated',
|
||||
context: { column },
|
||||
})
|
||||
}
|
||||
if (!EXTRA_WRITABLE_COLUMNS.has(column)) {
|
||||
throw createHttpError('半自动任务状态补丁包含未登记列', {
|
||||
statusCode: 500,
|
||||
@@ -469,16 +572,22 @@ export async function convergeSemiAutoTaskState(
|
||||
if (value === undefined) continue
|
||||
pushParam(column, value)
|
||||
}
|
||||
pushExpression('updated_at', 'NOW()')
|
||||
|
||||
await client.query(
|
||||
`
|
||||
// ⓪ 无变化不写库:轮询、Connector 对账、绑定决策重算经常带着与库内完全相同的值调用,
|
||||
// 如果照常 UPDATE,`updated_at` 会被无意义地推进,后台列表的「更新时间」和排序都会抖。
|
||||
// 补丁确实改变了任务时才推进 updated_at,它就等价于「最近一次真实状态变更」。
|
||||
const stateChanged = semiAutoTaskPatchChangesState(current, patch)
|
||||
if (stateChanged) {
|
||||
pushExpression('updated_at', 'NOW()')
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET ${assignments.join(',\n ')}
|
||||
WHERE id = $1
|
||||
`,
|
||||
params,
|
||||
)
|
||||
params,
|
||||
)
|
||||
}
|
||||
|
||||
// ④ 事件:from*/to* 由行锁前后的值自动生成,detail.reason 必填。
|
||||
const event =
|
||||
|
||||
@@ -958,7 +958,7 @@ test(
|
||||
)
|
||||
|
||||
test(
|
||||
'半自动后台列表按任务创建顺序稳定分页,状态刷新不会导致行跳位',
|
||||
'半自动后台列表按待办队列排序:等客服优先,同组按最近真实变更倒序',
|
||||
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
||||
async () => {
|
||||
process.env.DATABASE_URL = TEST_DATABASE_URL
|
||||
@@ -967,13 +967,13 @@ test(
|
||||
const { createSemiAutoMock } = await import('../dev-mock/dev-mock-service.js')
|
||||
const { listAdminSemiAutoTasks } = await import('./semi-auto-task-service.js')
|
||||
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
||||
const keyword = `IT-SEMI-AUTO-STABLE-${suffix}`
|
||||
const keyword = `IT-SEMI-AUTO-QUEUE-${suffix}`
|
||||
const created: Array<{ orderId: number; configId: number; taskId: number }> = []
|
||||
try {
|
||||
for (const label of ['A', 'B']) {
|
||||
for (const label of ['A', 'B', 'C', 'D']) {
|
||||
const result = await createSemiAutoMock({
|
||||
orderNo: `${keyword}-${label}`,
|
||||
skuName: `半自动稳定排序-${suffix}-${label}`,
|
||||
skuName: `半自动队列排序-${suffix}-${label}`,
|
||||
quantity: 1,
|
||||
connectorMode: 'embedded',
|
||||
})
|
||||
@@ -983,33 +983,65 @@ test(
|
||||
taskId: result.taskId,
|
||||
})
|
||||
}
|
||||
const first = created[0]!
|
||||
const second = created[1]!
|
||||
const [first, second, third, fourth] = created as [
|
||||
(typeof created)[number],
|
||||
(typeof created)[number],
|
||||
(typeof created)[number],
|
||||
(typeof created)[number],
|
||||
]
|
||||
|
||||
// A:客户已就绪、等客服履约,但已经放了 90 分钟。
|
||||
await query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET created_at = NOW() - INTERVAL '2 minutes',
|
||||
updated_at = NOW() + INTERVAL '2 minutes',
|
||||
SET created_at = NOW() - INTERVAL '3 minutes',
|
||||
updated_at = NOW() - INTERVAL '90 minutes',
|
||||
execution_status = 'waiting_operator'
|
||||
WHERE id = $1
|
||||
`,
|
||||
[first.taskId],
|
||||
)
|
||||
// B:客户已打开过客户链接,仍在等客户自己登录。
|
||||
await query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET created_at = NOW() - INTERVAL '1 minute',
|
||||
updated_at = NOW() - INTERVAL '1 minute',
|
||||
execution_status = 'waiting_customer'
|
||||
SET created_at = NOW() - INTERVAL '2 minutes',
|
||||
updated_at = NOW() - INTERVAL '10 minutes',
|
||||
execution_status = 'waiting_customer',
|
||||
customer_link_opened_at = NOW() - INTERVAL '10 minutes'
|
||||
WHERE id = $1
|
||||
`,
|
||||
[second.taskId],
|
||||
)
|
||||
// C:客户从未开始,但它是最近创建、更新时间也最新的行。
|
||||
await query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET created_at = NOW() - INTERVAL '1 minute',
|
||||
updated_at = NOW() + INTERVAL '5 minutes',
|
||||
execution_status = 'waiting_customer',
|
||||
customer_link_opened_at = NULL
|
||||
WHERE id = $1
|
||||
`,
|
||||
[third.taskId],
|
||||
)
|
||||
// D:同样是等客服履约,但刚发生变更,应在同组内排在 A 前面。
|
||||
await query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET created_at = NOW() - INTERVAL '4 minutes',
|
||||
updated_at = NOW() - INTERVAL '1 minute',
|
||||
execution_status = 'waiting_operator'
|
||||
WHERE id = $1
|
||||
`,
|
||||
[fourth.taskId],
|
||||
)
|
||||
|
||||
const result = await listAdminSemiAutoTasks({ keyword, page: 1, pageSize: 20 })
|
||||
// 桶序优先于时间:C 即使更新时间最新也排在最后;同桶内按最近变更倒序。
|
||||
assert.deepEqual(
|
||||
result.items.map((item) => item.id),
|
||||
[second.taskId, first.taskId],
|
||||
[fourth.taskId, first.taskId, second.taskId, third.taskId],
|
||||
)
|
||||
} finally {
|
||||
for (const item of created.reverse()) {
|
||||
@@ -1022,6 +1054,83 @@ test(
|
||||
},
|
||||
)
|
||||
|
||||
test(
|
||||
'无变化的状态收敛不推进 updated_at,真实变更才推进',
|
||||
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
||||
async () => {
|
||||
process.env.DATABASE_URL = TEST_DATABASE_URL
|
||||
process.env.ENABLE_DEV_MOCK = '1'
|
||||
const { closeDb, query, withTransaction } = await import('../../db/client.js')
|
||||
const { createSemiAutoMock } = await import('../dev-mock/dev-mock-service.js')
|
||||
const { convergeSemiAutoTaskState } = await import('./semi-auto-task-state-service.js')
|
||||
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
||||
let orderId = 0
|
||||
let configId = 0
|
||||
let taskId = 0
|
||||
try {
|
||||
const mock = await createSemiAutoMock({
|
||||
orderNo: `IT-SEMI-AUTO-NOOP-${suffix}`,
|
||||
skuName: `半自动无变化写入-${suffix}`,
|
||||
quantity: 1,
|
||||
connectorMode: 'embedded',
|
||||
})
|
||||
orderId = mock.orderId
|
||||
configId = mock.configId
|
||||
taskId = mock.taskId
|
||||
|
||||
const before = await query<{ updated_at: string; login_status: string }>(
|
||||
'SELECT updated_at, login_status FROM semi_auto_tasks WHERE id = $1',
|
||||
[taskId],
|
||||
)
|
||||
// 与库内完全一致的补丁:轮询/对账就是这种形状,必须整条 UPDATE 都不发。
|
||||
await withTransaction((client) =>
|
||||
convergeSemiAutoTaskState(client, taskId, {
|
||||
reason: 'connector_poll_noop',
|
||||
actor: 'connector',
|
||||
patch: {
|
||||
loginStatus: before.rows[0]!.login_status as 'waiting_login',
|
||||
lastError: '',
|
||||
pendingRoleObservedAt: null,
|
||||
},
|
||||
event: null,
|
||||
}),
|
||||
)
|
||||
const afterNoop = await query<{ updated_at: string }>(
|
||||
'SELECT updated_at FROM semi_auto_tasks WHERE id = $1',
|
||||
[taskId],
|
||||
)
|
||||
assert.equal(
|
||||
new Date(afterNoop.rows[0]!.updated_at).getTime(),
|
||||
new Date(before.rows[0]!.updated_at).getTime(),
|
||||
)
|
||||
|
||||
// 真实变更必须推进 updated_at,列表的「最近变更」才有意义。
|
||||
await withTransaction((client) =>
|
||||
convergeSemiAutoTaskState(client, taskId, {
|
||||
reason: 'customer_link_opened',
|
||||
actor: 'customer',
|
||||
patch: { customerLinkOpenedAt: { kind: 'now' } },
|
||||
}),
|
||||
)
|
||||
const afterChange = await query<{ updated_at: string }>(
|
||||
'SELECT updated_at FROM semi_auto_tasks WHERE id = $1',
|
||||
[taskId],
|
||||
)
|
||||
assert.notEqual(
|
||||
new Date(afterChange.rows[0]!.updated_at).getTime(),
|
||||
new Date(before.rows[0]!.updated_at).getTime(),
|
||||
)
|
||||
} finally {
|
||||
if (orderId > 0) await query('DELETE FROM orders WHERE id = $1', [orderId])
|
||||
if (configId > 0) {
|
||||
await query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
||||
}
|
||||
delete process.env.ENABLE_DEV_MOCK
|
||||
await closeDb()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
test(
|
||||
'微博账号 CK 以账号级 Cookie JSON 保存并可加载',
|
||||
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
SEMI_AUTO_COALESCE_NOW,
|
||||
SEMI_AUTO_NOW,
|
||||
semiAutoNowPlusSeconds,
|
||||
semiAutoTaskPatchChangesState,
|
||||
} from './semi-auto-task-state-service.js'
|
||||
|
||||
const root = path.dirname(fileURLToPath(import.meta.url))
|
||||
@@ -213,7 +214,7 @@ test('event 传 null 时保持"原来不发事件"的入口行为', async () =>
|
||||
})
|
||||
|
||||
test('event.emit=false 时只写字段不写事件(轮询去噪)', async () => {
|
||||
const fake = createFakeClient(baseTaskRow({ login_status: 'authenticated' }))
|
||||
const fake = createFakeClient(baseTaskRow({ login_status: 'qr_pending' }))
|
||||
await convergeSemiAutoTaskState(fake.client, 42, {
|
||||
reason: 'login_status_changed',
|
||||
actor: 'connector',
|
||||
@@ -224,6 +225,98 @@ test('event.emit=false 时只写字段不写事件(轮询去噪)', async ()
|
||||
assert.equal(fake.events().length, 0)
|
||||
})
|
||||
|
||||
test('补丁与库内完全一致时不写库,updated_at 不被无变化轮询推进', async () => {
|
||||
// Connector 对账、绑定决策重算每次都带着一整套值调用,实际没有任何变化。
|
||||
const fake = createFakeClient(
|
||||
baseTaskRow({
|
||||
login_status: 'authenticated',
|
||||
binding_status: 'role_ready',
|
||||
execution_status: 'waiting_customer',
|
||||
bind_game_role: '角色A',
|
||||
pending_bind_game_role: '',
|
||||
last_error: null,
|
||||
}),
|
||||
)
|
||||
const result = await convergeSemiAutoTaskState(fake.client, 42, {
|
||||
reason: 'binding_status_changed',
|
||||
actor: 'connector',
|
||||
patch: {
|
||||
bindingStatus: 'role_ready',
|
||||
bindGameRole: '角色A',
|
||||
pendingBindGameRole: '',
|
||||
lastError: '',
|
||||
pendingRoleObservedAt: null,
|
||||
boundAt: null,
|
||||
},
|
||||
event: { eventType: 'binding_status_changed', emit: false },
|
||||
})
|
||||
assert.equal(result, null)
|
||||
assert.equal(fake.updates().length, 0)
|
||||
assert.equal(fake.events().length, 0)
|
||||
})
|
||||
|
||||
test('coalesce_now 在已有值时不算变化,静态时间按时间点比较', () => {
|
||||
assert.equal(
|
||||
semiAutoTaskPatchChangesState(
|
||||
{ auth_started_at: '2026-01-01T00:00:00.000Z' },
|
||||
{ authStartedAt: SEMI_AUTO_COALESCE_NOW },
|
||||
),
|
||||
false,
|
||||
)
|
||||
assert.equal(
|
||||
semiAutoTaskPatchChangesState(
|
||||
{ auth_started_at: null },
|
||||
{ authStartedAt: SEMI_AUTO_COALESCE_NOW },
|
||||
),
|
||||
true,
|
||||
)
|
||||
assert.equal(
|
||||
semiAutoTaskPatchChangesState(
|
||||
{ auth_started_at: '2026-01-01T00:00:00.000Z' },
|
||||
{ authStartedAt: SEMI_AUTO_NOW },
|
||||
),
|
||||
true,
|
||||
)
|
||||
assert.equal(
|
||||
semiAutoTaskPatchChangesState(
|
||||
{ auth_started_at: '2026-01-01T00:00:00.000Z' },
|
||||
{ authStartedAt: '2026-01-01T08:00:00+08:00' },
|
||||
),
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
test('数值列与 bigint 返回字符串、空串与 NULL 都算未变化', () => {
|
||||
assert.equal(
|
||||
semiAutoTaskPatchChangesState(
|
||||
{ assigned_admin_user_id: '23', last_error: null },
|
||||
{ assignedAdminUserId: 23, lastError: '' },
|
||||
),
|
||||
false,
|
||||
)
|
||||
assert.equal(
|
||||
semiAutoTaskPatchChangesState({ assigned_admin_user_id: '23' }, { assignedAdminUserId: 24 }),
|
||||
true,
|
||||
)
|
||||
})
|
||||
|
||||
test('JSON 列按内容比较,extra 列同样参与变化判定', () => {
|
||||
assert.equal(
|
||||
semiAutoTaskPatchChangesState(
|
||||
{ completion_evidence_json: { a: 1, b: 2 } },
|
||||
{ completionEvidence: { b: 2, a: 1 } },
|
||||
),
|
||||
false,
|
||||
)
|
||||
assert.equal(
|
||||
semiAutoTaskPatchChangesState(
|
||||
{ connector_state_version: 3 },
|
||||
{ extra: { connector_state_version: 4 } },
|
||||
),
|
||||
true,
|
||||
)
|
||||
})
|
||||
|
||||
test('乐观守卫和转换规则不满足时抛 409,且不写库', async () => {
|
||||
const fake = createFakeClient(baseTaskRow({ execution_status: 'completed' }))
|
||||
await assert.rejects(
|
||||
|
||||
@@ -704,6 +704,13 @@ export default function AdminSemiAutoTasksPage() {
|
||||
刷新
|
||||
</Button>
|
||||
</Space>
|
||||
<Typography.Text
|
||||
type="secondary"
|
||||
style={{ display: 'block', marginBottom: 12, fontSize: 12 }}
|
||||
>
|
||||
队列排序:等客服履约 → 客服处理中 → 需客服修复 → 客户处理中 → 客户未开始 →
|
||||
已结束;同一组内按最近变更倒序(系统轮询不会刷新这个时间)。
|
||||
</Typography.Text>
|
||||
<PercentTable<SemiAutoTask>
|
||||
rowKey="id"
|
||||
loading={listQuery.isLoading}
|
||||
|
||||
@@ -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
|
||||
|
||||
+30
-3
@@ -315,6 +315,17 @@ manual fulfillment
|
||||
- `fulfillments.channel` 仍为 `manual`;成本、销售与总账口径不变。
|
||||
- 是否启用半自动履约由 `manual_fulfillment_configs.semi_auto_*` 显式配置,不能按商品名或平台前缀猜测。
|
||||
- 半自动任务必须绑定 `order_item_id`、`fulfillments.id` 和人工履约配置,不得伪造接单平台工单。
|
||||
- 后台半自动履约列表是运营待办队列,不是审计流水,排序固定为:
|
||||
`waiting_operator`(客户已就绪、等客服履约)→ `processing`(客服处理中)→ `failed`(需客服修复)→
|
||||
`waiting_customer` 且客户已参与(已登录/已扫码/已打开过客户链接)→ `waiting_customer` 且客户尚未开始 →
|
||||
`completed` → `cancelled`;同一组内按最近一次真实状态变更倒序,并以任务 ID 兜底保证分页确定。
|
||||
分组只读 `execution_status`、`login_status`、`binding_status`、`customer_link_opened_at` 这些正式字段,
|
||||
具体待办文案继续由 `displayStatus` 单点输出,页面不得再判断一套。
|
||||
- `semi_auto_tasks.updated_at` 只代表「最近一次真实状态变更」:写入口
|
||||
`convergeSemiAutoTaskState` 必须先比对补丁列与库内当前值,完全相同就整条 UPDATE 都不执行。
|
||||
客户页轮询、Connector 定时对账、绑定决策重算这类无变化写入不得推进 `updated_at`,
|
||||
否则「更新时间」会自己跳动、队列排序不可信(历史反例:2026-12-03 对账把 18 条任务的
|
||||
`updated_at` 全部推进到 13:04,其中 16 条没有任何状态变化)。
|
||||
- 半自动任务必须在 manual 渠道判定、人工配置保存/重匹配或 Carrier 补配成功后按订单项主动物化,
|
||||
不能依赖客户先打开 `/c/<订单号>` 或客服先打开半自动任务列表。后台和客户页的幂等回填仅作为兜底。
|
||||
- 虎牙客户页流程固定为「填写资料 → 登录虎牙账号 → 绑定角色 → 客服处理」:
|
||||
@@ -538,9 +549,25 @@ manual fulfillment
|
||||
“商品与成本中心 → 接单平台”范围,能够先配置成本再启用模板。
|
||||
- 模板商品不得因为缺少内部 SKU 路由而显示为“未路由”;“未路由”只用于确实等待渠道配置的内部
|
||||
SKU 商品。
|
||||
- 不得从 `tpl:` 前缀、商品名或模板名称反推该关系。
|
||||
- 已有模板商品在迁移 `164` 中按模板生成的标准 SKU 一次性回填关联;删除仍被模板引用的商品时
|
||||
必须拒绝并提示改为归档。
|
||||
- 模板存在 ⇒ 它的 `tpl:<rule_key>` 商品必须存在、`work_product_rules.canonical_product_id`
|
||||
指向该商品、且 `product_catalog.status = 'active'`,与模板 `enabled` 无关;未启用模板同样
|
||||
必须先建出 active 商品,才能先配置成本再启用模板。
|
||||
- 只有删除模板才归档商品,并在 `attributes_json` 写 `templateDeleted = true`;商品接口不得归档
|
||||
或删除仍被模板引用的商品,命中必须拒绝(归档返回 `cost_product_template_bound`,删除按
|
||||
“N 个接单模板”阻断),运营只能到「接单平台 → 接单模板」停用或删除模板。
|
||||
- 保存模板、「修复历史商品/映射」必须同时修复关联和状态(模板商品一律 `active`,
|
||||
关联一律写回 `canonical_product_id`),不能只修链接不复活状态;「修复历史商品/映射」
|
||||
默认包含停用模板(只同步启用模板需显式传 `includeDisabledTemplates: false`)。
|
||||
- 模板商品身份由 `tpl:<rule_key>` 这一唯一编码公式确定(决策、回填、一致性校验统一用
|
||||
`product.canonical_sku = LEFT('tpl:' || BTRIM(rule.rule_key), 64)`);不得用商品名、分类、
|
||||
其他前缀或 `tpl:` 的任意后缀去猜归属。
|
||||
- 已有模板商品在迁移 `164` 中按模板生成的标准 SKU 一次性回填关联;迁移 `192`
|
||||
(2026-12-03 在生产核对 `admin_audit_logs` 的 `cost_product_updated` 与 15 条模板商品
|
||||
成本异常后编写,来源:生产只读审计 + 迁移 164/166 口径)已按上述口径全量对齐:
|
||||
按 `product.canonical_sku = LEFT('tpl:' || BTRIM(rule.rule_key), 64)` 精确匹配回填关联、
|
||||
恢复被误归档的模板商品(保留 `previousStatus`、`repairedAt`、`repairReason` 供回滚)、
|
||||
末尾断言启用模板与商品一一对齐。
|
||||
- 未来不得再让商品状态接口单独改模板商品状态;模板商品的状态只有一个写入口:接单模板。
|
||||
|
||||
### 3.4.5 接单平台动态模板路由
|
||||
|
||||
|
||||
Reference in New Issue
Block a user