Merge branch 'main' into dev_match

This commit is contained in:
2026-11-06 10:14:43 +08:00
63 changed files with 7027 additions and 954 deletions
@@ -0,0 +1,190 @@
-- 135_reconcile_manual_standard_products.sql
--
-- 人工标准商品归一:
-- 1. 同一内部 SKU 因大小写/全半角残留出多条 active man: 商品时,只保留最早一条;
-- 2. 订单项、人工配置、成本版本、成本快照、渠道映射和渠道能力统一指向保留商品;
-- 3. 重复商品只归档,不删除历史成本与订单数据。
-- 已有配置/登记但缺少 man: 标准商品的 SKU,先补标准商品。
-- 若该 SKU 已有其他启用主渠道,则不再补人工商品,避免重新制造跨渠道重复。
WITH raw_keys AS (
SELECT canonicalize_internal_sku(sku_key) AS sku_key, sku_key AS display_name
FROM manual_fulfillment_configs
UNION ALL
SELECT canonicalize_internal_sku(sku_key) AS sku_key, sku_key AS display_name
FROM manual_sku_registry
),
keys AS (
SELECT sku_key, MAX(display_name) AS display_name
FROM raw_keys
GROUP BY 1
),
missing AS (
SELECT keys.*
FROM keys
WHERE keys.sku_key <> ''
AND NOT EXISTS (
SELECT 1
FROM product_catalog product
WHERE product.status = 'active'
AND product.canonical_sku LIKE 'man:%'
AND canonicalize_internal_sku(substring(product.canonical_sku from 5)) = keys.sku_key
)
AND NOT EXISTS (
SELECT 1
FROM internal_sku_channels channel
WHERE channel.enabled = TRUE
AND channel.is_fallback = FALSE
AND channel.channel <> 'manual'
AND canonicalize_internal_sku(channel.internal_sku) = keys.sku_key
)
)
INSERT INTO product_catalog (
canonical_sku, canonical_name, category, unit_name, status,
attributes_json, created_at, updated_at
)
SELECT
'man:' || sku_key,
COALESCE(NULLIF(display_name, ''), sku_key),
'人工',
'件',
'active',
'{"source":"manual_config","auto_created":true,"reconciled":true}'::jsonb,
NOW(),
NOW()
FROM missing
ON CONFLICT (canonical_sku) DO UPDATE SET
status = 'active',
canonical_name = CASE
WHEN BTRIM(product_catalog.canonical_name) = '' THEN EXCLUDED.canonical_name
ELSE product_catalog.canonical_name
END,
updated_at = EXCLUDED.updated_at;
DROP TABLE IF EXISTS pg_temp.tmp_manual_product_merge;
CREATE TEMP TABLE tmp_manual_product_merge AS
WITH ranked AS (
SELECT
id,
FIRST_VALUE(id) OVER (
PARTITION BY canonicalize_internal_sku(substring(canonical_sku from 5))
ORDER BY id
) AS keeper_id,
ROW_NUMBER() OVER (
PARTITION BY canonicalize_internal_sku(substring(canonical_sku from 5))
ORDER BY id
) AS candidate_rank
FROM product_catalog
WHERE status = 'active' AND canonical_sku LIKE 'man:%'
)
SELECT id AS duplicate_id, keeper_id
FROM ranked
WHERE candidate_rank > 1;
CREATE UNIQUE INDEX ON tmp_manual_product_merge (duplicate_id);
UPDATE order_items oi
SET canonical_product_id = merge.keeper_id,
updated_at = NOW()
FROM tmp_manual_product_merge merge
WHERE oi.canonical_product_id = merge.duplicate_id;
UPDATE manual_fulfillment_configs cfg
SET canonical_product_id = merge.keeper_id,
updated_at = NOW()
FROM tmp_manual_product_merge merge
WHERE cfg.canonical_product_id = merge.duplicate_id;
UPDATE cost_snapshots snapshot
SET canonical_product_id = merge.keeper_id
FROM tmp_manual_product_merge merge
WHERE snapshot.canonical_product_id = merge.duplicate_id;
-- 无冲突版本迁到保留商品;若生效时间等唯一范围冲突,则留在归档商品上供历史快照追溯。
UPDATE cost_versions version
SET canonical_product_id = merge.keeper_id,
updated_at = NOW()
FROM tmp_manual_product_merge merge
WHERE version.canonical_product_id = merge.duplicate_id
AND NOT EXISTS (
SELECT 1
FROM cost_versions keeper
WHERE keeper.canonical_product_id = merge.keeper_id
AND keeper.cost_item_id = version.cost_item_id
AND keeper.scope_type = version.scope_type
AND keeper.provider = version.provider
AND keeper.shop_id = version.shop_id
AND keeper.work_product_rule_id IS NOT DISTINCT FROM version.work_product_rule_id
AND keeper.effective_from = version.effective_from
);
DELETE FROM channel_product_mappings duplicate
USING tmp_manual_product_merge merge, channel_product_mappings keeper
WHERE duplicate.canonical_product_id = merge.duplicate_id
AND keeper.canonical_product_id = merge.keeper_id
AND keeper.provider = duplicate.provider
AND keeper.shop_id = duplicate.shop_id
AND keeper.platform_sku_code = duplicate.platform_sku_code
AND keeper.match_type = duplicate.match_type
AND keeper.platform_sku_name_key = duplicate.platform_sku_name_key;
UPDATE channel_product_mappings mapping
SET canonical_product_id = merge.keeper_id,
updated_at = NOW()
FROM tmp_manual_product_merge merge
WHERE mapping.canonical_product_id = merge.duplicate_id;
DELETE FROM product_channel_capabilities duplicate
USING tmp_manual_product_merge merge, product_channel_capabilities keeper
WHERE duplicate.product_id = merge.duplicate_id
AND keeper.product_id = merge.keeper_id
AND keeper.channel = duplicate.channel;
UPDATE product_channel_capabilities capability
SET product_id = merge.keeper_id,
updated_at = NOW()
FROM tmp_manual_product_merge merge
WHERE capability.product_id = merge.duplicate_id;
UPDATE internal_sku_channels channel
SET canonical_product_id = merge.keeper_id,
updated_at = NOW()
FROM tmp_manual_product_merge merge
WHERE channel.canonical_product_id = merge.duplicate_id;
UPDATE product_catalog product
SET status = 'archived',
attributes_json = product.attributes_json || jsonb_build_object(
'reconciledIntoProductId', merge.keeper_id,
'reconciledAt', NOW()
),
updated_at = NOW()
FROM tmp_manual_product_merge merge
WHERE product.id = merge.duplicate_id;
-- 人工配置统一挂到唯一 active man: 标准商品。
UPDATE manual_fulfillment_configs cfg
SET canonical_product_id = product.id,
updated_at = NOW()
FROM product_catalog product
WHERE product.status = 'active'
AND product.canonical_sku LIKE 'man:%'
AND canonicalize_internal_sku(substring(product.canonical_sku from 5))
= canonicalize_internal_sku(cfg.sku_key)
AND cfg.canonical_product_id IS DISTINCT FROM product.id;
UPDATE manual_sku_registry registry
SET config_id = cfg.id,
updated_at = NOW()
FROM manual_fulfillment_configs cfg
JOIN product_catalog product ON product.id = cfg.canonical_product_id
WHERE product.status = 'active'
AND product.canonical_sku LIKE 'man:%'
AND canonicalize_internal_sku(registry.sku_key)
= canonicalize_internal_sku(substring(product.canonical_sku from 5));
COMMENT ON COLUMN product_catalog.attributes_json IS
'标准商品扩展信息;人工商品归档时记录 reconciledIntoProductId 便于追溯';
DROP TABLE IF EXISTS pg_temp.tmp_manual_product_merge;
@@ -0,0 +1,139 @@
-- 136_reconcile_channel_products_and_work_costs.sql
--
-- 渠道商品与成本模型归一:
-- 1. 已启用的第三方卡券规则必须有 active tpv: 标准商品;
-- 2. 接单报酬成本版本不得挂在 man: 人工商品上;无快照引用的历史错误版本退休;
-- 3. 保留有快照引用的历史数据,不删除订单、成本版本或成本快照。
-- 卡券规则已有、但标准商品缺失时补建商品。
INSERT INTO product_catalog (
canonical_sku, canonical_name, category, unit_name, status,
attributes_json, created_at, updated_at
)
SELECT
'tpv:' || canonicalize_internal_sku(channel.internal_sku),
BTRIM(channel.internal_sku),
'卡券',
'张',
'active',
'{"source":"voucher_rule","auto_created":true,"reconciled":true}'::jsonb,
NOW(),
NOW()
FROM internal_sku_channels channel
WHERE channel.channel = 'third_party_voucher'
AND channel.enabled = TRUE
AND canonicalize_internal_sku(channel.internal_sku) <> ''
AND char_length('tpv:' || canonicalize_internal_sku(channel.internal_sku)) <= 64
AND NOT EXISTS (
SELECT 1
FROM product_catalog product
WHERE product.status = 'active'
AND product.canonical_sku LIKE 'tpv:%'
AND canonicalize_internal_sku(substring(product.canonical_sku from 5))
= canonicalize_internal_sku(channel.internal_sku)
)
AND NOT EXISTS (
SELECT 1
FROM internal_sku_channels other
WHERE other.enabled = TRUE
AND other.is_fallback = FALSE
AND other.channel <> 'third_party_voucher'
AND canonicalize_internal_sku(other.internal_sku)
= canonicalize_internal_sku(channel.internal_sku)
)
ON CONFLICT (canonical_sku) DO UPDATE SET
status = 'active',
canonical_name = CASE
WHEN BTRIM(product_catalog.canonical_name) = '' THEN EXCLUDED.canonical_name
ELSE product_catalog.canonical_name
END,
updated_at = EXCLUDED.updated_at;
-- 卡券规则统一挂到 active 标准商品,并补齐商品渠道能力。
UPDATE internal_sku_channels channel
SET canonical_product_id = product.id,
priority = 10,
is_fallback = FALSE,
config_json = channel.config_json || jsonb_build_object(
'voucherSku',
canonicalize_internal_sku(channel.internal_sku)
),
updated_at = NOW()
FROM product_catalog product
WHERE channel.channel = 'third_party_voucher'
AND channel.enabled = TRUE
AND product.status = 'active'
AND product.canonical_sku LIKE 'tpv:%'
AND canonicalize_internal_sku(substring(product.canonical_sku from 5))
= canonicalize_internal_sku(channel.internal_sku)
AND (
channel.canonical_product_id IS DISTINCT FROM product.id
OR channel.priority <> 10
OR channel.is_fallback
);
INSERT INTO product_channel_capabilities (
product_id, channel, priority, is_fallback, enabled, source, created_at, updated_at
)
SELECT
channel.canonical_product_id,
'third_party_voucher',
10,
FALSE,
TRUE,
'voucher',
NOW(),
NOW()
FROM internal_sku_channels channel
JOIN product_catalog product
ON product.id = channel.canonical_product_id
AND product.status = 'active'
WHERE channel.channel = 'third_party_voucher'
AND channel.enabled = TRUE
AND channel.canonical_product_id IS NOT NULL
ON CONFLICT (product_id, channel) DO UPDATE SET
enabled = TRUE,
priority = 10,
is_fallback = FALSE,
updated_at = EXCLUDED.updated_at;
-- 无法补齐标准商品的启用卡券规则必须停用,否则会继续把订单路由到无商品渠道。
UPDATE internal_sku_channels channel
SET enabled = FALSE,
is_fallback = FALSE,
note = CASE
WHEN BTRIM(channel.note) = '' THEN '标准商品缺失,迁移 136 自动停用'
ELSE channel.note
END,
updated_at = NOW()
WHERE channel.channel = 'third_party_voucher'
AND channel.enabled = TRUE
AND NOT EXISTS (
SELECT 1
FROM product_catalog product
WHERE product.id = channel.canonical_product_id
AND product.status = 'active'
AND product.canonical_sku LIKE 'tpv:%'
);
-- 早期错误地把“接单报酬”成本挂到了人工商品。无快照引用时直接退休。
UPDATE cost_versions version
SET status = 'retired',
change_reason = CASE
WHEN version.change_reason = '' THEN '清理错误挂到人工商品的接单报酬成本版本'
ELSE version.change_reason
END,
updated_at = NOW()
FROM cost_items item,
product_catalog product
WHERE version.cost_item_id = item.id
AND version.canonical_product_id = product.id
AND version.status = 'active'
AND item.cost_model = 'work_order_reward'
AND product.canonical_sku LIKE 'man:%'
AND NOT EXISTS (
SELECT 1 FROM cost_snapshots snapshot WHERE snapshot.cost_version_id = version.id
);
COMMENT ON COLUMN internal_sku_channels.canonical_product_id IS
'渠道规则关联的标准商品;启用规则必须指向 active 标准商品,历史归档仍保留关联';
@@ -0,0 +1,358 @@
-- 137_fulfillment_item_state_view.sql
--
-- 履约统一读模型:
-- 1. 每个订单项只有一行当前履约状态;
-- 2. 渠道、载体、最新尝试、异常、锁定原因分别表达;
-- 3. 退款、取消、人工复核、配置缺失不再混写成“无履约载体”。
CREATE OR REPLACE VIEW v_fulfillment_item_state AS
WITH active_items AS (
SELECT
oi.*,
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS internal_sku
FROM order_items oi
WHERE oi.fulfillment_status IN ('pending', 'assigned')
),
base AS (
SELECT
oi.id AS order_item_id,
oi.order_id,
o.id AS local_order_id,
o.provider,
o.platform,
o.shop_id,
o.shop_name,
o.platform_order_id,
o.pay_status,
o.order_status,
oi.fulfillment_status AS item_fulfillment_status,
oi.fulfillment_channel AS stored_channel,
oi.fulfillment_source,
oi.fulfillment_locked,
oi.fulfillment_pending_reason,
oi.fulfillment_pending_detail,
oi.sku_code,
oi.sku_name,
oi.quantity,
oi.revenue_amount_fen,
oi.created_at,
oi.updated_at,
oi.internal_sku,
channel_plan.channel AS configured_channel,
channel_plan.config_json AS configured_channel_config,
COALESCE(channel_stats.channel_count, 0) AS channel_count,
COALESCE(latest_task.task_id, 0) AS latest_task_id,
latest_task.executor_key AS latest_task_executor_key,
latest_task.task_status AS latest_task_status,
latest_task.result_code AS latest_task_result_code,
latest_task.result_message AS latest_task_result_message,
latest_task.updated_at AS latest_task_updated_at,
COALESCE(latest_work_order.work_order_id, 0) AS latest_work_order_id,
latest_work_order.status AS latest_work_order_status,
latest_work_order.result_code AS latest_work_order_result_code,
latest_work_order.updated_at AS latest_work_order_updated_at,
EXISTS (
SELECT 1
FROM fulfillment_tasks active_task
WHERE active_task.order_item_id = oi.id
AND active_task.executor_key IN ('affiliate_dash', 'manual_dispatch')
AND active_task.task_status NOT IN (
'closed', 'expired', 'failed', 'manual_review', 'retry_pending', 'cancelled'
)
) AS has_active_task,
EXISTS (
SELECT 1
FROM work_orders active_work_order
WHERE active_work_order.order_item_id = oi.id
AND active_work_order.status <> 'cancelled'
) AS has_active_work_order,
EXISTS (
SELECT 1
FROM manual_fulfillment_configs cfg
WHERE cfg.enabled = TRUE
AND canonicalize_internal_sku(cfg.sku_key) = oi.internal_sku
) AS has_manual_config
FROM active_items oi
JOIN orders o ON o.id = oi.order_id
LEFT JOIN LATERAL (
SELECT channel.channel, channel.config_json
FROM internal_sku_channels channel
WHERE channel.enabled = TRUE
AND canonicalize_internal_sku(channel.internal_sku) = oi.internal_sku
ORDER BY channel.is_fallback, channel.priority, channel.channel, channel.id
LIMIT 1
) channel_plan ON TRUE
LEFT JOIN LATERAL (
SELECT COUNT(*)::int AS channel_count
FROM internal_sku_channels channel
WHERE channel.enabled = TRUE
AND canonicalize_internal_sku(channel.internal_sku) = oi.internal_sku
) channel_stats ON TRUE
LEFT JOIN LATERAL (
SELECT
task.id AS task_id,
task.executor_key,
task.task_status,
task.result_code,
task.result_message,
task.updated_at
FROM fulfillment_tasks task
WHERE task.order_item_id = oi.id
ORDER BY task.id DESC
LIMIT 1
) latest_task ON TRUE
LEFT JOIN LATERAL (
SELECT
work_order.id AS work_order_id,
work_order.status,
''::text AS result_code,
work_order.updated_at
FROM work_orders work_order
WHERE work_order.order_item_id = oi.id
ORDER BY work_order.id DESC
LIMIT 1
) latest_work_order ON TRUE
),
classified AS (
SELECT
base.*,
COALESCE(base.stored_channel, base.configured_channel) AS intended_channel,
CASE
WHEN base.pay_status = 'refunded'
OR base.order_status IN ('refunded', 'cancelled')
OR base.latest_task_result_code = 'USER_APPLY_REFUND'
THEN TRUE
ELSE FALSE
END AS is_user_refund,
CASE
WHEN base.pay_status = 'cancelled'
OR base.order_status = 'cancelled'
OR base.latest_task_result_code = 'affiliate_dash_cancelled'
THEN TRUE
ELSE FALSE
END AS is_platform_cancelled
FROM base
),
current_attempt AS (
SELECT
classified.*,
CASE
WHEN classified.latest_task_id > 0
AND (
classified.latest_work_order_id = 0
OR classified.latest_task_updated_at >= classified.latest_work_order_updated_at
)
THEN 'task'
WHEN classified.latest_work_order_id > 0 THEN 'work_order'
ELSE ''
END AS current_attempt_type,
CASE
WHEN classified.latest_task_id > 0
AND (
classified.latest_work_order_id = 0
OR classified.latest_task_updated_at >= classified.latest_work_order_updated_at
)
THEN classified.latest_task_id
WHEN classified.latest_work_order_id > 0 THEN classified.latest_work_order_id
ELSE 0
END AS current_attempt_id,
CASE
WHEN classified.latest_task_id > 0
AND (
classified.latest_work_order_id = 0
OR classified.latest_task_updated_at >= classified.latest_work_order_updated_at
)
THEN classified.latest_task_status
WHEN classified.latest_work_order_id > 0 THEN classified.latest_work_order_status
ELSE ''
END AS current_attempt_status,
CASE
WHEN classified.latest_task_id > 0
AND (
classified.latest_work_order_id = 0
OR classified.latest_task_updated_at >= classified.latest_work_order_updated_at
)
THEN classified.latest_task_result_code
WHEN classified.latest_work_order_id > 0 THEN classified.latest_work_order_result_code
ELSE ''
END AS current_attempt_result_code
FROM classified
),
state_classified AS (
SELECT
current_attempt.*,
CASE
WHEN current_attempt.intended_channel IN ('third_party_voucher', 'on_account')
THEN 'not_required'
WHEN current_attempt.intended_channel = 'manual'
AND current_attempt.has_manual_config
THEN 'ready'
WHEN current_attempt.has_active_task OR current_attempt.has_active_work_order
THEN 'ready'
WHEN current_attempt.latest_task_status IN (
'closed', 'expired', 'failed', 'manual_review', 'retry_pending', 'cancelled'
)
THEN 'terminal'
WHEN current_attempt.latest_work_order_status = 'cancelled'
THEN 'terminal'
WHEN current_attempt.intended_channel IS NOT NULL
THEN 'missing'
ELSE 'missing'
END AS carrier_status,
CASE
WHEN COALESCE(current_attempt.internal_sku, '') = ''
THEN 'missing_internal_sku'
WHEN current_attempt.channel_count = 0
THEN 'missing_channel'
ELSE 'configured'
END AS route_status
FROM current_attempt
),
issue_classified AS (
SELECT
state_classified.*,
CASE
WHEN state_classified.is_user_refund THEN 'user_refund'
WHEN state_classified.is_platform_cancelled THEN 'platform_cancelled'
WHEN state_classified.route_status = 'missing_internal_sku' THEN 'missing_internal_sku'
WHEN state_classified.route_status = 'missing_channel' THEN 'missing_channel'
WHEN state_classified.intended_channel = 'manual'
AND NOT state_classified.has_manual_config
THEN 'manual_config_missing'
WHEN state_classified.intended_channel = 'work_order'
AND BTRIM(COALESCE(
state_classified.configured_channel_config->>'workRuleKey',
''
)) = ''
THEN 'work_rule_missing'
WHEN state_classified.intended_channel = 'affiliate_dash'
AND BTRIM(COALESCE(
state_classified.configured_channel_config->>'affiliateSku',
''
)) = ''
THEN 'affiliate_mapping_missing'
WHEN state_classified.carrier_status IN ('ready', 'not_required') THEN ''
WHEN state_classified.latest_task_status = 'manual_review'
THEN 'carrier_manual_review'
WHEN state_classified.latest_task_status IN ('failed', 'retry_pending')
THEN 'carrier_retry_pending'
WHEN state_classified.latest_task_status = 'expired' THEN 'carrier_expired'
WHEN state_classified.latest_task_status = 'closed'
OR state_classified.latest_work_order_status = 'cancelled'
THEN 'carrier_closed'
WHEN state_classified.item_fulfillment_status = 'assigned'
THEN 'state_inconsistent'
WHEN state_classified.intended_channel IN (
'affiliate_dash', 'work_order', 'manual'
)
THEN 'carrier_missing'
ELSE 'state_inconsistent'
END AS issue_code
FROM state_classified
),
categorized AS (
SELECT
issue_classified.*,
CASE
WHEN issue_code = '' THEN ''
WHEN issue_code IN ('user_refund', 'platform_cancelled') THEN 'after_sales'
WHEN issue_code = 'carrier_manual_review' THEN 'manual_review'
WHEN issue_code IN ('missing_internal_sku', 'missing_channel') THEN 'classification'
WHEN issue_code IN (
'manual_config_missing', 'work_rule_missing', 'affiliate_mapping_missing'
) THEN 'configuration'
WHEN issue_code = 'state_inconsistent' THEN 'system'
ELSE 'carrier'
END AS issue_category
FROM issue_classified
)
SELECT
order_item_id,
order_id,
local_order_id,
provider,
platform,
shop_id,
shop_name,
platform_order_id,
pay_status,
order_status,
item_fulfillment_status AS fulfillment_status,
internal_sku,
intended_channel,
stored_channel,
configured_channel,
route_status,
carrier_status,
current_attempt_type,
current_attempt_id,
current_attempt_status,
current_attempt_result_code,
latest_task_id,
latest_task_executor_key,
latest_task_status,
latest_task_result_code,
latest_work_order_id,
latest_work_order_status,
issue_code,
issue_category,
CASE
WHEN issue_code = '' THEN FALSE
WHEN issue_code IN (
'user_refund', 'platform_cancelled', 'carrier_manual_review',
'manual_config_missing', 'work_rule_missing', 'affiliate_mapping_missing',
'missing_internal_sku', 'missing_channel'
) THEN FALSE
ELSE TRUE
END AS retryable,
CASE
WHEN issue_code IN ('carrier_missing', 'state_inconsistent') THEN TRUE
ELSE FALSE
END AS auto_retryable,
CASE
WHEN issue_code IN ('user_refund', 'platform_cancelled', 'carrier_manual_review')
THEN 'support'
WHEN issue_code IN (
'missing_internal_sku', 'missing_channel', 'manual_config_missing',
'work_rule_missing', 'affiliate_mapping_missing'
) THEN 'operator'
WHEN issue_code = '' THEN ''
ELSE 'system'
END AS owner_role,
fulfillment_locked,
CASE
WHEN NOT fulfillment_locked THEN ''
ELSE COALESCE(
NULLIF(fulfillment_pending_detail->>'carrierIssue', ''),
NULLIF(fulfillment_pending_detail->>'reason', ''),
'operator_assigned'
)
END AS lock_reason,
fulfillment_pending_reason,
fulfillment_pending_detail,
fulfillment_source,
sku_code,
sku_name,
quantity,
revenue_amount_fen,
created_at,
updated_at,
GREATEST(
0,
FLOOR(EXTRACT(EPOCH FROM (NOW() - created_at)) / 60)
)::bigint AS age_minutes
FROM categorized;
COMMENT ON VIEW v_fulfillment_item_state IS
'履约统一读模型:每个订单项一行,拆分渠道、载体、当前尝试、结构化异常与锁定原因';
CREATE INDEX IF NOT EXISTS idx_order_items_active_fulfillment_state
ON order_items (id)
WHERE fulfillment_status IN ('pending', 'assigned');
CREATE INDEX IF NOT EXISTS idx_fulfillment_tasks_order_item_latest
ON fulfillment_tasks (order_item_id, id DESC);
CREATE INDEX IF NOT EXISTS idx_work_orders_order_item_latest
ON work_orders (order_item_id, id DESC)
WHERE order_item_id IS NOT NULL;
@@ -0,0 +1,54 @@
-- 138_fulfillment_current_attempt.sql
--
-- 履约尝试指针:
-- 1. 每个订单项单元显式记录尝试序号;
-- 2. 同一订单项单元只允许一个当前尝试;
-- 3. 新尝试创建时自动把旧尝试标为非当前,历史仍完整保留。
ALTER TABLE fulfillment_tasks
ADD COLUMN IF NOT EXISTS attempt_no INTEGER NOT NULL DEFAULT 1,
ADD COLUMN IF NOT EXISTS is_current BOOLEAN NOT NULL DEFAULT TRUE;
WITH ranked AS (
SELECT
id,
order_item_id,
unit_index,
ROW_NUMBER() OVER (
PARTITION BY order_item_id, unit_index
ORDER BY id
)::int AS attempt_no,
ROW_NUMBER() OVER (
PARTITION BY order_item_id, unit_index
ORDER BY id DESC
) AS current_rank
FROM fulfillment_tasks
),
duplicate_units AS (
SELECT order_item_id, unit_index
FROM fulfillment_tasks
GROUP BY order_item_id, unit_index
HAVING COUNT(*) > 1
)
UPDATE fulfillment_tasks task
SET attempt_no = ranked.attempt_no,
is_current = ranked.current_rank = 1
FROM ranked
JOIN duplicate_units duplicate
ON duplicate.order_item_id = ranked.order_item_id
AND duplicate.unit_index = ranked.unit_index
WHERE task.id = ranked.id
;
CREATE UNIQUE INDEX IF NOT EXISTS uq_fulfillment_tasks_current_unit
ON fulfillment_tasks (order_item_id, unit_index)
WHERE is_current = TRUE;
CREATE INDEX IF NOT EXISTS idx_fulfillment_tasks_attempt_history
ON fulfillment_tasks (order_item_id, unit_index, attempt_no DESC, id DESC);
COMMENT ON COLUMN fulfillment_tasks.attempt_no IS
'同一订单项单元的履约尝试序号,从 1 开始递增';
COMMENT ON COLUMN fulfillment_tasks.is_current IS
'是否为该订单项单元当前尝试;历史尝试保留但不再标记为当前';
@@ -0,0 +1,30 @@
-- 139_fulfillment_automation_cutoff.sql
--
-- 历史履约数据已完成人工处置,不再参与自动判定、自动补载体或自动重试。
-- 从本迁移执行时间起,只自动处理之后新建的订单。
INSERT INTO app_config_entries (
config_key,
config_json,
source_file_path,
migrated_from_file,
created_at,
updated_at
) VALUES (
'fulfillment_automation_cutoff',
jsonb_build_object(
'cutoff',
to_char(
NOW() AT TIME ZONE 'Asia/Shanghai',
'YYYY-MM-DD"T"HH24:MI:SS.MS+08:00'
)
),
'',
FALSE,
NOW(),
NOW()
)
ON CONFLICT (config_key) DO NOTHING;
COMMENT ON TABLE app_config_entries IS
'运行时配置中心,保存从 JSON 文件迁移来的平台和系统配置;fulfillment_automation_cutoff 是履约自动化生效边界';
@@ -0,0 +1,212 @@
-- 140_fulfillment_state_events.sql
--
-- 履约状态事件:
-- 1. 订单项履约核心字段每次真实变化都追加一条事件;
-- 2. 状态写入口可写入操作者、动作和原因,遗留直写至少留下 system 事件;
-- 3. 事件表不允许应用更新;父订单删除时允许随外键级联清理。
CREATE TABLE IF NOT EXISTS fulfillment_state_events (
id BIGSERIAL PRIMARY KEY,
order_item_id BIGINT NOT NULL REFERENCES order_items(id) ON DELETE CASCADE,
order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
event_type TEXT NOT NULL,
actor_type TEXT NOT NULL DEFAULT 'system',
actor_id TEXT NOT NULL DEFAULT '',
reason TEXT NOT NULL DEFAULT '',
previous_status TEXT,
next_status TEXT,
previous_channel TEXT,
next_channel TEXT,
previous_source TEXT,
next_source TEXT,
previous_locked BOOLEAN,
next_locked BOOLEAN,
previous_pending_reason TEXT,
next_pending_reason TEXT,
previous_pending_detail JSONB,
next_pending_detail JSONB,
payload_json JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_fulfillment_state_events_item
ON fulfillment_state_events (order_item_id, id DESC);
CREATE INDEX IF NOT EXISTS idx_fulfillment_state_events_order
ON fulfillment_state_events (order_id, created_at DESC, id DESC);
COMMENT ON TABLE fulfillment_state_events IS
'履约状态追加事件:记录订单项履约状态、渠道、锁定和待办原因的真实变化';
COMMENT ON COLUMN fulfillment_state_events.payload_json IS
'本次变化字段的前后值;空对象表示仅有未知扩展字段变化';
CREATE OR REPLACE FUNCTION record_fulfillment_state_event()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
DECLARE
event_type_value TEXT;
actor_type_value TEXT;
actor_id_value TEXT;
reason_value TEXT;
changed_fields JSONB;
BEGIN
IF ROW(
OLD.fulfillment_status,
OLD.fulfillment_channel,
OLD.fulfillment_source,
OLD.fulfillment_locked,
OLD.fulfillment_pending_reason,
OLD.fulfillment_pending_detail,
OLD.fulfillment_reason,
OLD.fulfillment_decided_by,
OLD.fulfillment_decided_at,
OLD.original_channel,
OLD.channel_switch_reason,
OLD.channel_switched_at
) IS NOT DISTINCT FROM ROW(
NEW.fulfillment_status,
NEW.fulfillment_channel,
NEW.fulfillment_source,
NEW.fulfillment_locked,
NEW.fulfillment_pending_reason,
NEW.fulfillment_pending_detail,
NEW.fulfillment_reason,
NEW.fulfillment_decided_by,
NEW.fulfillment_decided_at,
NEW.original_channel,
NEW.channel_switch_reason,
NEW.channel_switched_at
) THEN
RETURN NEW;
END IF;
event_type_value := COALESCE(
NULLIF(BTRIM(current_setting('app.fulfillment_event_type', TRUE)), ''),
'fulfillment_state_changed'
);
actor_type_value := COALESCE(
NULLIF(BTRIM(current_setting('app.fulfillment_actor_type', TRUE)), ''),
'system'
);
actor_id_value := COALESCE(
current_setting('app.fulfillment_actor_id', TRUE),
''
);
reason_value := COALESCE(
current_setting('app.fulfillment_reason', TRUE),
''
);
changed_fields := jsonb_strip_nulls(jsonb_build_object(
'fulfillmentStatus', CASE
WHEN OLD.fulfillment_status IS DISTINCT FROM NEW.fulfillment_status
THEN jsonb_build_object('from', OLD.fulfillment_status, 'to', NEW.fulfillment_status)
END,
'fulfillmentChannel', CASE
WHEN OLD.fulfillment_channel IS DISTINCT FROM NEW.fulfillment_channel
THEN jsonb_build_object('from', OLD.fulfillment_channel, 'to', NEW.fulfillment_channel)
END,
'fulfillmentSource', CASE
WHEN OLD.fulfillment_source IS DISTINCT FROM NEW.fulfillment_source
THEN jsonb_build_object('from', OLD.fulfillment_source, 'to', NEW.fulfillment_source)
END,
'fulfillmentLocked', CASE
WHEN OLD.fulfillment_locked IS DISTINCT FROM NEW.fulfillment_locked
THEN jsonb_build_object('from', OLD.fulfillment_locked, 'to', NEW.fulfillment_locked)
END,
'fulfillmentPendingReason', CASE
WHEN OLD.fulfillment_pending_reason IS DISTINCT FROM NEW.fulfillment_pending_reason
THEN jsonb_build_object(
'from', OLD.fulfillment_pending_reason,
'to', NEW.fulfillment_pending_reason
)
END,
'fulfillmentPendingDetail', CASE
WHEN OLD.fulfillment_pending_detail IS DISTINCT FROM NEW.fulfillment_pending_detail
THEN jsonb_build_object(
'from', OLD.fulfillment_pending_detail,
'to', NEW.fulfillment_pending_detail
)
END
));
INSERT INTO fulfillment_state_events (
order_item_id,
order_id,
event_type,
actor_type,
actor_id,
reason,
previous_status,
next_status,
previous_channel,
next_channel,
previous_source,
next_source,
previous_locked,
next_locked,
previous_pending_reason,
next_pending_reason,
previous_pending_detail,
next_pending_detail,
payload_json
) VALUES (
NEW.id,
NEW.order_id,
LEFT(event_type_value, 100),
LEFT(actor_type_value, 32),
LEFT(actor_id_value, 200),
LEFT(reason_value, 500),
OLD.fulfillment_status,
NEW.fulfillment_status,
OLD.fulfillment_channel,
NEW.fulfillment_channel,
OLD.fulfillment_source,
NEW.fulfillment_source,
OLD.fulfillment_locked,
NEW.fulfillment_locked,
OLD.fulfillment_pending_reason,
NEW.fulfillment_pending_reason,
OLD.fulfillment_pending_detail,
NEW.fulfillment_pending_detail,
changed_fields
);
RETURN NEW;
END;
$$;
DROP TRIGGER IF EXISTS trg_order_items_fulfillment_state_event ON order_items;
CREATE TRIGGER trg_order_items_fulfillment_state_event
AFTER UPDATE OF
fulfillment_status,
fulfillment_channel,
fulfillment_source,
fulfillment_locked,
fulfillment_pending_reason,
fulfillment_pending_detail,
fulfillment_reason,
fulfillment_decided_by,
fulfillment_decided_at,
original_channel,
channel_switch_reason,
channel_switched_at
ON order_items
FOR EACH ROW
EXECUTE FUNCTION record_fulfillment_state_event();
CREATE OR REPLACE FUNCTION reject_fulfillment_state_event_mutation()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
RAISE EXCEPTION 'fulfillment_state_events is append-only';
END;
$$;
DROP TRIGGER IF EXISTS trg_fulfillment_state_events_append_only ON fulfillment_state_events;
CREATE TRIGGER trg_fulfillment_state_events_append_only
BEFORE UPDATE ON fulfillment_state_events
FOR EACH ROW
EXECUTE FUNCTION reject_fulfillment_state_event_mutation();
@@ -0,0 +1,810 @@
-- 141_fulfillment_shadow_model.sql
--
-- 正式履约影子模型:
-- 1. fulfillments 保存订单项当前履约事实;
-- 2. fulfillment_attempts 保存任务/工单的执行尝试;
-- 3. fulfillment_issues 保存当前结构化异常,并保留已解决历史;
-- 4. 现有 order_items / fulfillment_tasks / work_orders 继续作为真源,
-- 通过触发器双写影子表,读路径暂不切换。
-- 原视图把 route_status 错写成“内部 SKU 是否有配置”,导致已经明确指定渠道的
-- 订单项仍被标记为 missing_channel。保留原视图为 raw 层,外层按“已有渠道即已路由”
-- 修正路由口径,原视图名和字段保持不变。
ALTER VIEW v_fulfillment_item_state RENAME TO v_fulfillment_item_state_raw;
CREATE OR REPLACE VIEW v_fulfillment_item_state AS
SELECT
raw.order_item_id,
raw.order_id,
raw.local_order_id,
raw.provider,
raw.platform,
raw.shop_id,
raw.shop_name,
raw.platform_order_id,
raw.pay_status,
raw.order_status,
raw.fulfillment_status,
raw.internal_sku,
raw.intended_channel,
raw.stored_channel,
raw.configured_channel,
CASE
WHEN COALESCE(raw.route_status, '') = 'missing_internal_sku' THEN 'missing_internal_sku'
WHEN raw.intended_channel IS NOT NULL THEN 'configured'
ELSE 'missing_channel'
END AS route_status,
raw.carrier_status,
raw.current_attempt_type,
raw.current_attempt_id,
raw.current_attempt_status,
raw.current_attempt_result_code,
raw.latest_task_id,
raw.latest_task_executor_key,
raw.latest_task_status,
raw.latest_task_result_code,
raw.latest_work_order_id,
raw.latest_work_order_status,
CASE
WHEN raw.route_status = 'missing_channel'
AND raw.intended_channel IS NOT NULL
THEN ''
ELSE raw.issue_code
END AS issue_code,
CASE
WHEN raw.route_status = 'missing_channel'
AND raw.intended_channel IS NOT NULL
THEN ''
ELSE raw.issue_category
END AS issue_category,
CASE
WHEN raw.route_status = 'missing_channel'
AND raw.intended_channel IS NOT NULL
THEN FALSE
ELSE raw.retryable
END AS retryable,
CASE
WHEN raw.route_status = 'missing_channel'
AND raw.intended_channel IS NOT NULL
THEN FALSE
ELSE raw.auto_retryable
END AS auto_retryable,
CASE
WHEN raw.route_status = 'missing_channel'
AND raw.intended_channel IS NOT NULL
THEN ''
ELSE raw.owner_role
END AS owner_role,
raw.fulfillment_locked,
raw.lock_reason,
raw.fulfillment_pending_reason,
raw.fulfillment_pending_detail,
raw.fulfillment_source,
raw.sku_code,
raw.sku_name,
raw.quantity,
raw.revenue_amount_fen,
raw.created_at,
raw.updated_at,
raw.age_minutes
FROM v_fulfillment_item_state_raw raw;
COMMENT ON VIEW v_fulfillment_item_state IS
'履约统一读模型:每订单项一行;明确渠道即视为已路由,渠道配置缺失只作为异常明细';
CREATE TABLE IF NOT EXISTS fulfillments (
id BIGSERIAL PRIMARY KEY,
order_item_id BIGINT NOT NULL UNIQUE REFERENCES order_items(id) ON DELETE CASCADE,
order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
internal_sku TEXT NOT NULL DEFAULT '',
route_status TEXT NOT NULL DEFAULT 'unrouted'
CHECK (route_status IN ('unrouted', 'configured')),
channel TEXT
CHECK (
channel IS NULL
OR channel IN ('work_order', 'affiliate_dash', 'third_party_voucher', 'manual', 'on_account')
),
carrier_status TEXT NOT NULL DEFAULT 'missing'
CHECK (carrier_status IN ('not_required', 'missing', 'creating', 'ready', 'failed', 'terminal')),
current_attempt_type TEXT NOT NULL DEFAULT ''
CHECK (current_attempt_type IN ('', 'task', 'work_order')),
current_attempt_source_id BIGINT,
current_attempt_status TEXT NOT NULL DEFAULT '',
lock_reason TEXT NOT NULL DEFAULT '',
issue_code TEXT NOT NULL DEFAULT '',
issue_category TEXT NOT NULL DEFAULT '',
retryable BOOLEAN NOT NULL DEFAULT FALSE,
owner_role TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL,
CHECK (
(current_attempt_type = '' AND current_attempt_source_id IS NULL)
OR (current_attempt_type <> '' AND current_attempt_source_id IS NOT NULL)
)
);
CREATE INDEX IF NOT EXISTS idx_fulfillments_order
ON fulfillments (order_id, updated_at DESC, id DESC);
CREATE INDEX IF NOT EXISTS idx_fulfillments_issue
ON fulfillments (issue_category, carrier_status, updated_at DESC)
WHERE issue_code <> '';
CREATE INDEX IF NOT EXISTS idx_fulfillments_channel
ON fulfillments (channel, carrier_status, updated_at DESC);
COMMENT ON TABLE fulfillments IS
'履约主记录:每订单项一行,拆分路由、渠道、载体、当前尝试和当前异常摘要';
CREATE TABLE IF NOT EXISTS fulfillment_attempts (
id BIGSERIAL PRIMARY KEY,
fulfillment_id BIGINT NOT NULL REFERENCES fulfillments(id) ON DELETE CASCADE,
unit_index INTEGER NOT NULL DEFAULT 1,
attempt_no INTEGER NOT NULL,
attempt_type TEXT NOT NULL CHECK (attempt_type IN ('task', 'work_order')),
source_id BIGINT NOT NULL,
source_attempt_no INTEGER NOT NULL DEFAULT 1,
executor_key TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT '',
result_code TEXT NOT NULL DEFAULT '',
result_message TEXT NOT NULL DEFAULT '',
started_at TIMESTAMPTZ NOT NULL,
finished_at TIMESTAMPTZ,
is_current BOOLEAN NOT NULL DEFAULT FALSE,
context_json JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL,
UNIQUE (attempt_type, source_id),
UNIQUE (fulfillment_id, unit_index, attempt_no),
CHECK (attempt_no > 0),
CHECK (unit_index > 0)
);
CREATE UNIQUE INDEX IF NOT EXISTS uq_fulfillment_attempts_current_unit
ON fulfillment_attempts (fulfillment_id, unit_index)
WHERE is_current = TRUE;
CREATE INDEX IF NOT EXISTS idx_fulfillment_attempts_history
ON fulfillment_attempts (fulfillment_id, unit_index, attempt_no DESC);
CREATE INDEX IF NOT EXISTS idx_fulfillment_attempts_status
ON fulfillment_attempts (attempt_type, status, updated_at DESC);
COMMENT ON TABLE fulfillment_attempts IS
'履约执行尝试:任务和接单工单的追加式历史,同一订单项单元仅一个当前尝试';
CREATE TABLE IF NOT EXISTS fulfillment_issues (
id BIGSERIAL PRIMARY KEY,
fulfillment_id BIGINT NOT NULL REFERENCES fulfillments(id) ON DELETE CASCADE,
issue_code TEXT NOT NULL,
issue_category TEXT NOT NULL DEFAULT '',
severity TEXT NOT NULL DEFAULT 'warning'
CHECK (severity IN ('info', 'warning', 'error', 'critical')),
source TEXT NOT NULL DEFAULT 'read_model',
retryable BOOLEAN NOT NULL DEFAULT FALSE,
auto_retryable BOOLEAN NOT NULL DEFAULT FALSE,
owner_role TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'open'
CHECK (status IN ('open', 'acknowledged', 'waiting', 'resolved')),
detail_json JSONB NOT NULL DEFAULT '{}'::jsonb,
first_seen_at TIMESTAMPTZ NOT NULL,
last_seen_at TIMESTAMPTZ NOT NULL,
resolved_at TIMESTAMPTZ,
UNIQUE (fulfillment_id, issue_code)
);
CREATE INDEX IF NOT EXISTS idx_fulfillment_issues_queue
ON fulfillment_issues (status, issue_category, last_seen_at DESC)
WHERE status <> 'resolved';
CREATE INDEX IF NOT EXISTS idx_fulfillment_issues_code
ON fulfillment_issues (issue_code, status, last_seen_at DESC);
COMMENT ON TABLE fulfillment_issues IS
'履约结构化异常:当前开放异常按 issue_code 唯一,解决后保留历史';
ALTER TABLE fulfillment_state_events
ADD COLUMN IF NOT EXISTS fulfillment_id BIGINT;
CREATE INDEX IF NOT EXISTS idx_fulfillment_state_events_fulfillment
ON fulfillment_state_events (fulfillment_id, id DESC)
WHERE fulfillment_id IS NOT NULL;
CREATE OR REPLACE FUNCTION sync_fulfillment_shadow(p_order_item_id BIGINT)
RETURNS VOID
LANGUAGE plpgsql
AS $$
DECLARE
item_record RECORD;
state_record RECORD;
fulfillment_id_value BIGINT;
BEGIN
SELECT
oi.id,
oi.order_id,
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS internal_sku,
oi.created_at
INTO item_record
FROM order_items oi
WHERE oi.id = p_order_item_id;
IF NOT FOUND THEN
RETURN;
END IF;
SELECT state.*
INTO state_record
FROM v_fulfillment_item_state state
WHERE state.order_item_id = item_record.id;
IF FOUND THEN
INSERT INTO fulfillments (
order_item_id,
order_id,
internal_sku,
route_status,
channel,
carrier_status,
current_attempt_type,
current_attempt_source_id,
current_attempt_status,
lock_reason,
issue_code,
issue_category,
retryable,
owner_role,
created_at,
updated_at
) VALUES (
item_record.id,
item_record.order_id,
COALESCE(state_record.internal_sku, ''),
CASE
WHEN state_record.route_status = 'configured' THEN 'configured'
ELSE 'unrouted'
END,
state_record.intended_channel,
state_record.carrier_status,
state_record.current_attempt_type,
NULLIF(state_record.current_attempt_id, 0),
state_record.current_attempt_status,
state_record.lock_reason,
state_record.issue_code,
state_record.issue_category,
state_record.retryable,
state_record.owner_role,
item_record.created_at,
NOW()
)
ON CONFLICT (order_item_id) DO UPDATE SET
order_id = EXCLUDED.order_id,
internal_sku = EXCLUDED.internal_sku,
route_status = EXCLUDED.route_status,
channel = EXCLUDED.channel,
carrier_status = EXCLUDED.carrier_status,
current_attempt_type = EXCLUDED.current_attempt_type,
current_attempt_source_id = EXCLUDED.current_attempt_source_id,
current_attempt_status = EXCLUDED.current_attempt_status,
lock_reason = EXCLUDED.lock_reason,
issue_code = EXCLUDED.issue_code,
issue_category = EXCLUDED.issue_category,
retryable = EXCLUDED.retryable,
owner_role = EXCLUDED.owner_role,
updated_at = NOW()
RETURNING id INTO fulfillment_id_value;
IF state_record.issue_code <> '' THEN
INSERT INTO fulfillment_issues (
fulfillment_id,
issue_code,
issue_category,
severity,
source,
retryable,
auto_retryable,
owner_role,
status,
detail_json,
first_seen_at,
last_seen_at,
resolved_at
) VALUES (
fulfillment_id_value,
state_record.issue_code,
state_record.issue_category,
CASE
WHEN state_record.issue_category IN ('after_sales', 'system') THEN 'error'
WHEN state_record.issue_category = 'carrier' THEN 'warning'
ELSE 'info'
END,
'read_model',
state_record.retryable,
state_record.auto_retryable,
state_record.owner_role,
'open',
COALESCE(state_record.fulfillment_pending_detail, '{}'::jsonb),
state_record.created_at,
NOW(),
NULL
)
ON CONFLICT (fulfillment_id, issue_code) DO UPDATE SET
issue_category = EXCLUDED.issue_category,
severity = EXCLUDED.severity,
retryable = EXCLUDED.retryable,
auto_retryable = EXCLUDED.auto_retryable,
owner_role = EXCLUDED.owner_role,
status = 'open',
detail_json = EXCLUDED.detail_json,
last_seen_at = NOW(),
resolved_at = NULL;
UPDATE fulfillment_issues
SET status = 'resolved',
resolved_at = NOW()
WHERE fulfillment_id = fulfillment_id_value
AND issue_code <> state_record.issue_code
AND status <> 'resolved';
ELSE
UPDATE fulfillment_issues
SET status = 'resolved',
resolved_at = NOW()
WHERE fulfillment_id = fulfillment_id_value
AND status <> 'resolved';
END IF;
ELSE
INSERT INTO fulfillments (
order_item_id,
order_id,
internal_sku,
route_status,
channel,
carrier_status,
current_attempt_type,
current_attempt_source_id,
current_attempt_status,
lock_reason,
issue_code,
issue_category,
retryable,
owner_role,
created_at,
updated_at
) VALUES (
item_record.id,
item_record.order_id,
COALESCE(item_record.internal_sku, ''),
CASE WHEN COALESCE(item_record.internal_sku, '') = '' THEN 'unrouted' ELSE 'configured' END,
NULL,
'terminal',
'',
NULL,
'',
'',
'',
'',
FALSE,
'',
item_record.created_at,
NOW()
)
ON CONFLICT (order_item_id) DO UPDATE SET
route_status = EXCLUDED.route_status,
channel = NULL,
carrier_status = 'terminal',
current_attempt_type = '',
current_attempt_source_id = NULL,
current_attempt_status = '',
lock_reason = '',
issue_code = '',
issue_category = '',
retryable = FALSE,
owner_role = '',
updated_at = NOW()
RETURNING id INTO fulfillment_id_value;
UPDATE fulfillment_issues
SET status = 'resolved',
resolved_at = NOW()
WHERE fulfillment_id = fulfillment_id_value
AND status <> 'resolved';
END IF;
END;
$$;
-- 先为当前活跃订单项建立履约主记录和结构化异常。
SELECT sync_fulfillment_shadow(state.order_item_id)
FROM v_fulfillment_item_state state;
WITH source_attempts AS (
SELECT
task.order_item_id,
task.unit_index,
task.created_at AS occurred_at,
'task'::text AS attempt_type,
task.id AS source_id,
task.attempt_no AS source_attempt_no,
task.executor_key,
task.task_status AS status,
task.result_code,
task.result_message,
task.created_at AS started_at,
CASE
WHEN task.task_status IN (
'closed', 'expired', 'failed', 'manual_review', 'retry_pending', 'cancelled'
) THEN task.updated_at
ELSE NULL
END AS finished_at,
task.is_current,
task.context_json,
task.created_at,
task.updated_at
FROM fulfillment_tasks task
JOIN fulfillments fulfillment ON fulfillment.order_item_id = task.order_item_id
UNION ALL
SELECT
work_order.order_item_id,
1,
work_order.created_at,
'work_order'::text,
work_order.id,
1,
'work_order'::text,
work_order.status,
''::text,
work_order.problem_note,
work_order.created_at,
CASE
WHEN work_order.status IN ('accepted', 'cancelled', 'closed') THEN work_order.updated_at
ELSE NULL
END,
work_order.status <> 'cancelled',
jsonb_build_object(
'workOrderNo', work_order.work_order_no,
'productName', work_order.product_name
),
work_order.created_at,
work_order.updated_at
FROM work_orders work_order
JOIN fulfillments fulfillment ON fulfillment.order_item_id = work_order.order_item_id
WHERE work_order.order_item_id IS NOT NULL
),
ranked AS (
SELECT
source_attempts.*,
ROW_NUMBER() OVER (
PARTITION BY order_item_id, unit_index
ORDER BY occurred_at, attempt_type, source_id
)::int AS attempt_no
FROM source_attempts
)
INSERT INTO fulfillment_attempts (
fulfillment_id,
unit_index,
attempt_no,
attempt_type,
source_id,
source_attempt_no,
executor_key,
status,
result_code,
result_message,
started_at,
finished_at,
is_current,
context_json,
created_at,
updated_at
)
SELECT
fulfillment.id,
ranked.unit_index,
ranked.attempt_no,
ranked.attempt_type,
ranked.source_id,
ranked.source_attempt_no,
ranked.executor_key,
ranked.status,
ranked.result_code,
ranked.result_message,
ranked.started_at,
ranked.finished_at,
CASE
WHEN ranked.attempt_type = fulfillment.current_attempt_type
AND ranked.source_id = fulfillment.current_attempt_source_id
THEN TRUE
ELSE FALSE
END,
ranked.context_json,
ranked.created_at,
ranked.updated_at
FROM ranked
JOIN fulfillments fulfillment ON fulfillment.order_item_id = ranked.order_item_id
ON CONFLICT (attempt_type, source_id) DO NOTHING;
UPDATE fulfillment_state_events event
SET fulfillment_id = fulfillment.id
FROM fulfillments fulfillment
WHERE fulfillment.order_item_id = event.order_item_id
AND event.fulfillment_id IS NULL;
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1
FROM pg_constraint
WHERE conname = 'fk_fulfillment_state_events_fulfillment'
) THEN
ALTER TABLE fulfillment_state_events
ADD CONSTRAINT fk_fulfillment_state_events_fulfillment
FOREIGN KEY (fulfillment_id) REFERENCES fulfillments(id) ON DELETE SET NULL;
END IF;
END $$;
CREATE OR REPLACE FUNCTION assign_fulfillment_event_shadow()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
IF NEW.fulfillment_id IS NULL THEN
SELECT fulfillment.id
INTO NEW.fulfillment_id
FROM fulfillments fulfillment
WHERE fulfillment.order_item_id = NEW.order_item_id;
END IF;
RETURN NEW;
END;
$$;
DROP TRIGGER IF EXISTS trg_fulfillment_state_events_shadow ON fulfillment_state_events;
CREATE TRIGGER trg_fulfillment_state_events_shadow
BEFORE INSERT ON fulfillment_state_events
FOR EACH ROW
EXECUTE FUNCTION assign_fulfillment_event_shadow();
CREATE OR REPLACE FUNCTION sync_fulfillment_shadow_from_order_item()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
PERFORM sync_fulfillment_shadow(NEW.id);
RETURN NEW;
END;
$$;
DROP TRIGGER IF EXISTS trg_order_items_fulfillment_shadow ON order_items;
CREATE TRIGGER trg_order_items_fulfillment_shadow
AFTER INSERT OR UPDATE OF
fulfillment_status,
fulfillment_channel,
fulfillment_source,
fulfillment_locked,
fulfillment_pending_reason,
fulfillment_pending_detail,
fulfillment_reason,
manual_sku_key,
sku_code,
sku_name
ON order_items
FOR EACH ROW
EXECUTE FUNCTION sync_fulfillment_shadow_from_order_item();
CREATE OR REPLACE FUNCTION sync_fulfillment_task_attempt()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
DECLARE
fulfillment_id_value BIGINT;
existing_attempt_id BIGINT;
next_attempt_no INTEGER;
BEGIN
IF TG_OP = 'DELETE' THEN
DELETE FROM fulfillment_attempts
WHERE attempt_type = 'task' AND source_id = OLD.id;
PERFORM sync_fulfillment_shadow(OLD.order_item_id);
RETURN OLD;
END IF;
PERFORM sync_fulfillment_shadow(NEW.order_item_id);
SELECT fulfillment.id
INTO fulfillment_id_value
FROM fulfillments fulfillment
WHERE fulfillment.order_item_id = NEW.order_item_id;
IF fulfillment_id_value IS NULL THEN
RETURN NEW;
END IF;
SELECT attempt.id
INTO existing_attempt_id
FROM fulfillment_attempts attempt
WHERE attempt.attempt_type = 'task'
AND attempt.source_id = NEW.id;
IF existing_attempt_id IS NULL THEN
SELECT COALESCE(MAX(attempt.attempt_no), 0) + 1
INTO next_attempt_no
FROM fulfillment_attempts attempt
WHERE attempt.fulfillment_id = fulfillment_id_value
AND attempt.unit_index = NEW.unit_index;
END IF;
UPDATE fulfillment_attempts
SET is_current = FALSE,
updated_at = NOW()
WHERE fulfillment_id = fulfillment_id_value
AND unit_index = NEW.unit_index
AND is_current = TRUE
AND NOT (attempt_type = 'task' AND source_id = NEW.id);
INSERT INTO fulfillment_attempts (
fulfillment_id,
unit_index,
attempt_no,
attempt_type,
source_id,
source_attempt_no,
executor_key,
status,
result_code,
result_message,
started_at,
finished_at,
is_current,
context_json,
created_at,
updated_at
) VALUES (
fulfillment_id_value,
NEW.unit_index,
COALESCE(next_attempt_no, 1),
'task',
NEW.id,
NEW.attempt_no,
NEW.executor_key,
NEW.task_status,
NEW.result_code,
NEW.result_message,
NEW.created_at,
CASE
WHEN NEW.task_status IN (
'closed', 'expired', 'failed', 'manual_review', 'retry_pending', 'cancelled'
) THEN NEW.updated_at
ELSE NULL
END,
NEW.is_current,
NEW.context_json,
NEW.created_at,
NEW.updated_at
)
ON CONFLICT (attempt_type, source_id) DO UPDATE SET
executor_key = EXCLUDED.executor_key,
status = EXCLUDED.status,
result_code = EXCLUDED.result_code,
result_message = EXCLUDED.result_message,
finished_at = EXCLUDED.finished_at,
is_current = EXCLUDED.is_current,
context_json = EXCLUDED.context_json,
updated_at = EXCLUDED.updated_at;
PERFORM sync_fulfillment_shadow(NEW.order_item_id);
RETURN NEW;
END;
$$;
DROP TRIGGER IF EXISTS trg_fulfillment_tasks_shadow ON fulfillment_tasks;
CREATE TRIGGER trg_fulfillment_tasks_shadow
AFTER INSERT OR UPDATE OR DELETE ON fulfillment_tasks
FOR EACH ROW
EXECUTE FUNCTION sync_fulfillment_task_attempt();
CREATE OR REPLACE FUNCTION sync_fulfillment_work_order_attempt()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
DECLARE
fulfillment_id_value BIGINT;
existing_attempt_id BIGINT;
next_attempt_no INTEGER;
BEGIN
IF TG_OP = 'DELETE' THEN
DELETE FROM fulfillment_attempts
WHERE attempt_type = 'work_order' AND source_id = OLD.id;
IF OLD.order_item_id IS NOT NULL THEN
PERFORM sync_fulfillment_shadow(OLD.order_item_id);
END IF;
RETURN OLD;
END IF;
IF NEW.order_item_id IS NULL THEN
RETURN NEW;
END IF;
PERFORM sync_fulfillment_shadow(NEW.order_item_id);
SELECT fulfillment.id
INTO fulfillment_id_value
FROM fulfillments fulfillment
WHERE fulfillment.order_item_id = NEW.order_item_id;
IF fulfillment_id_value IS NULL THEN
RETURN NEW;
END IF;
SELECT attempt.id
INTO existing_attempt_id
FROM fulfillment_attempts attempt
WHERE attempt.attempt_type = 'work_order'
AND attempt.source_id = NEW.id;
IF existing_attempt_id IS NULL THEN
SELECT COALESCE(MAX(attempt.attempt_no), 0) + 1
INTO next_attempt_no
FROM fulfillment_attempts attempt
WHERE attempt.fulfillment_id = fulfillment_id_value
AND attempt.unit_index = 1;
END IF;
UPDATE fulfillment_attempts
SET is_current = FALSE,
updated_at = NOW()
WHERE fulfillment_id = fulfillment_id_value
AND unit_index = 1
AND is_current = TRUE
AND NOT (attempt_type = 'work_order' AND source_id = NEW.id);
INSERT INTO fulfillment_attempts (
fulfillment_id,
unit_index,
attempt_no,
attempt_type,
source_id,
source_attempt_no,
executor_key,
status,
result_code,
result_message,
started_at,
finished_at,
is_current,
context_json,
created_at,
updated_at
) VALUES (
fulfillment_id_value,
1,
COALESCE(next_attempt_no, 1),
'work_order',
NEW.id,
1,
'work_order',
NEW.status,
'',
NEW.problem_note,
NEW.created_at,
CASE
WHEN NEW.status IN ('accepted', 'cancelled', 'closed') THEN NEW.updated_at
ELSE NULL
END,
NEW.status <> 'cancelled',
jsonb_build_object(
'workOrderNo', NEW.work_order_no,
'productName', NEW.product_name
),
NEW.created_at,
NEW.updated_at
)
ON CONFLICT (attempt_type, source_id) DO UPDATE SET
status = EXCLUDED.status,
result_message = EXCLUDED.result_message,
finished_at = EXCLUDED.finished_at,
is_current = EXCLUDED.is_current,
context_json = EXCLUDED.context_json,
updated_at = EXCLUDED.updated_at;
PERFORM sync_fulfillment_shadow(NEW.order_item_id);
RETURN NEW;
END;
$$;
DROP TRIGGER IF EXISTS trg_work_orders_fulfillment_shadow ON work_orders;
CREATE TRIGGER trg_work_orders_fulfillment_shadow
AFTER INSERT OR UPDATE OR DELETE ON work_orders
FOR EACH ROW
EXECUTE FUNCTION sync_fulfillment_work_order_attempt();
COMMENT ON COLUMN fulfillment_state_events.fulfillment_id IS
'正式履约影子记录;迁移 141 后新旧事件都自动关联';