feat(shipping-notice): 新增库存确认来源接口及相关逻辑

This commit is contained in:
hugo committed 2026-07-13 21:53:45 +08:00
1 parent a31735b689
commit 0a9bd6415d
69 files changed
+8442 -775

No files matched your search

@@ -0,0 +1,257 @@
"""Add shipping inventory source gate independent fields.
Purpose:
Move inventory source identity from step_payload_json to dedicated columns on
shipping_tasks, shipping_inventory_files, and shipping_task_inventory_links.
Dependencies:
Alembic revision e2f3a4b5c6d7.
Flow:
Order-parse gate writes task inventory fields; RPA/inventory/match stages
read the same columns for hard gate checks.
Revision ID: b4c5d6e7f8a9
Revises: e2f3a4b5c6d7
Create Date: 2026-07-13 10:00:00.000000
"""
from __future__ import annotations
import json
import sqlalchemy as sa
from alembic import op
revision = "b4c5d6e7f8a9"
down_revision = "e2f3a4b5c6d7"
branch_labels = None
depends_on = None
def upgrade():
"""Add inventory source gate columns and backfill legacy JSON where possible."""
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
batch_op.add_column(sa.Column("destination_code", sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column("destination_city", sa.String(length=128), nullable=True))
batch_op.add_column(sa.Column("destination_country", sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column("warehouse_hint", sa.String(length=128), nullable=True))
batch_op.add_column(sa.Column("inventory_source_code", sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column("inventory_source_type", sa.String(length=32), nullable=True))
batch_op.add_column(sa.Column("inventory_site_id", sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column("inventory_warehouse_id", sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column("inventory_source_status", sa.String(length=32), nullable=True))
batch_op.add_column(sa.Column("inventory_source_method", sa.String(length=32), nullable=True))
batch_op.add_column(sa.Column("inventory_source_confirmed_by", sa.Integer(), nullable=True))
batch_op.add_column(sa.Column("inventory_source_confirmed_at", sa.DateTime(), nullable=True))
batch_op.add_column(sa.Column("inventory_source_config_version", sa.String(length=32), nullable=True))
batch_op.add_column(sa.Column("inventory_routing_fingerprint", sa.String(length=64), nullable=True))
batch_op.create_index("ix_shipping_tasks_inventory_source_code", ["inventory_source_code"], unique=False)
batch_op.create_index("ix_shipping_tasks_inventory_site_id", ["inventory_site_id"], unique=False)
batch_op.create_index("ix_shipping_tasks_inventory_source_status", ["inventory_source_status"], unique=False)
batch_op.create_index(
"ix_shipping_tasks_inventory_routing_fingerprint",
["inventory_routing_fingerprint"],
unique=False,
)
batch_op.create_foreign_key(
"fk_shipping_tasks_inventory_source_confirmed_by_users",
"users",
["inventory_source_confirmed_by"],
["id"],
)
with op.batch_alter_table("shipping_inventory_files", schema=None) as batch_op:
batch_op.add_column(sa.Column("site_id", sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column("source_config_version", sa.String(length=32), nullable=True))
batch_op.add_column(sa.Column("identity_status", sa.String(length=32), nullable=True))
batch_op.create_index("ix_shipping_inventory_files_site_id", ["site_id"], unique=False)
batch_op.create_index("ix_shipping_inventory_files_identity_status", ["identity_status"], unique=False)
batch_op.create_index(
"ix_shipping_inventory_files_source_site_wh",
["source_code", "site_id", "warehouse_id"],
unique=False,
)
with op.batch_alter_table("shipping_task_inventory_links", schema=None) as batch_op:
batch_op.add_column(sa.Column("matched_source_code", sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column("matched_site_id", sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column("identity_check_status", sa.String(length=32), nullable=True))
batch_op.add_column(sa.Column("identity_checked_at", sa.DateTime(), nullable=True))
batch_op.create_index(
"ix_shipping_task_inventory_links_task_source",
["task_id", "matched_source_code", "matched_site_id"],
unique=False,
)
_backfill_legacy_inventory_source()
def _backfill_legacy_inventory_source() -> None:
"""Migrate rpa_inventory_source from step_payload_json; legacy rows require re-verification."""
bind = op.get_bind()
legacy_config_version = "legacy-unverified"
rows = bind.execute(
sa.text(
"SELECT id, step_payload_json, pending_human_reason FROM shipping_tasks "
"WHERE step_payload_json IS NOT NULL"
)
).fetchall()
for row in rows:
payload = row.step_payload_json
if not isinstance(payload, dict):
continue
source = payload.get("rpa_inventory_source")
if not isinstance(source, dict):
continue
source_code = str(source.get("source_code") or "").strip().upper()
if not source_code:
continue
site_id = str(source.get("site_id") or "").strip().upper() or None
warehouse_id = str(source.get("warehouse_id") or "").strip().upper() or None
source_type = str(source.get("source_type") or "").strip().lower() or None
resolution = payload.get("inventory_source_resolution")
status = "resolved"
method = "legacy_migrated"
routing_fingerprint = None
if isinstance(resolution, dict):
res_status = str(resolution.get("status") or "").strip()
routing_fingerprint = str(resolution.get("routing_fingerprint") or "").strip() or None
if res_status == "resolved":
status = "resolved"
method = "rule_exact"
elif res_status == "ambiguous":
status = "ambiguous"
elif res_status == "user_confirmed":
status = "user_confirmed"
method = "user_confirmed"
needs_review = False
if not site_id and warehouse_id:
# Historical bug: site_id was written into warehouse_id — cannot auto-fix.
status = "unresolved"
method = None
site_id = None
warehouse_id = None
source_code = None
source_type = None
needs_review = True
elif not site_id or not warehouse_id:
status = "unresolved"
method = None
source_code = None
source_type = None
site_id = None
warehouse_id = None
needs_review = True
elif not routing_fingerprint:
status = "unresolved"
method = None
needs_review = True
bind.execute(
sa.text(
"UPDATE shipping_tasks SET "
"inventory_source_code = :source_code, "
"inventory_source_type = :source_type, "
"inventory_site_id = :site_id, "
"inventory_warehouse_id = :warehouse_id, "
"inventory_source_status = :status, "
"inventory_source_method = :method, "
"inventory_source_config_version = :config_version, "
"inventory_routing_fingerprint = :routing_fingerprint "
"WHERE id = :task_id"
),
{
"source_code": source_code,
"source_type": source_type,
"site_id": site_id,
"warehouse_id": warehouse_id,
"status": status,
"method": method,
"config_version": legacy_config_version,
"routing_fingerprint": routing_fingerprint,
"task_id": row.id,
},
)
if needs_review or status in {"ambiguous", "unresolved"}:
bind.execute(
sa.text(
"UPDATE shipping_tasks SET "
"pending_human_reason = 'inventory_source_unresolved', "
"current_step = 'step2_parse_confirm', "
"process_status = 'pending_review' "
"WHERE id = :task_id"
),
{"task_id": row.id},
)
bind.execute(
sa.text(
"UPDATE shipping_tasks SET "
"pending_human_reason = 'inventory_source_unresolved', "
"current_step = 'step2_parse_confirm', "
"process_status = 'pending_review' "
"WHERE inventory_source_status IN ('ambiguous', 'unresolved', 'conflicted', 'invalid') "
"AND (pending_human_reason IS NULL OR pending_human_reason = '')"
)
)
bind.execute(
sa.text(
"UPDATE shipping_tasks SET "
"pending_human_reason = 'inventory_source_unresolved', "
"current_step = 'step2_parse_confirm', "
"process_status = 'pending_review' "
"WHERE inventory_source_config_version = 'legacy-unverified'"
)
)
file_rows = bind.execute(
sa.text("SELECT id, source_code, warehouse_id FROM shipping_inventory_files WHERE source_code IS NOT NULL")
).fetchall()
for row in file_rows:
bind.execute(
sa.text(
"UPDATE shipping_inventory_files SET identity_status = 'unknown' WHERE id = :file_id"
),
{"file_id": row.id},
)
def downgrade():
"""Remove inventory source gate columns."""
with op.batch_alter_table("shipping_task_inventory_links", schema=None) as batch_op:
batch_op.drop_index("ix_shipping_task_inventory_links_task_source")
batch_op.drop_column("identity_checked_at")
batch_op.drop_column("identity_check_status")
batch_op.drop_column("matched_site_id")
batch_op.drop_column("matched_source_code")
with op.batch_alter_table("shipping_inventory_files", schema=None) as batch_op:
batch_op.drop_index("ix_shipping_inventory_files_source_site_wh")
batch_op.drop_index("ix_shipping_inventory_files_identity_status")
batch_op.drop_index("ix_shipping_inventory_files_site_id")
batch_op.drop_column("identity_status")
batch_op.drop_column("source_config_version")
batch_op.drop_column("site_id")
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
batch_op.drop_constraint("fk_shipping_tasks_inventory_source_confirmed_by_users", type_="foreignkey")
batch_op.drop_index("ix_shipping_tasks_inventory_routing_fingerprint")
batch_op.drop_index("ix_shipping_tasks_inventory_source_status")
batch_op.drop_index("ix_shipping_tasks_inventory_site_id")
batch_op.drop_index("ix_shipping_tasks_inventory_source_code")
batch_op.drop_column("inventory_routing_fingerprint")
batch_op.drop_column("inventory_source_config_version")
batch_op.drop_column("inventory_source_confirmed_at")
batch_op.drop_column("inventory_source_confirmed_by")
batch_op.drop_column("inventory_source_method")
batch_op.drop_column("inventory_source_status")
batch_op.drop_column("inventory_warehouse_id")
batch_op.drop_column("inventory_site_id")
batch_op.drop_column("inventory_source_type")
batch_op.drop_column("inventory_source_code")
batch_op.drop_column("warehouse_hint")
batch_op.drop_column("destination_country")
batch_op.drop_column("destination_city")
batch_op.drop_column("destination_code")
@@ -0,0 +1,276 @@
"""
backend/migrations/versions/d6e7f8a9b0c1_add_rpa_callback_idempotency_fields.py
用途:RPA 回调幂等字段、快照去重与关联迁移、库存源/身份 CHECK 约束。
依赖:Alembic revision b4c5d6e7f8a9。
逻辑:回填 consumed_run_no → 去重并迁移链接 → 加 CHECK 与 ready 态部分唯一索引。
Revision ID: d6e7f8a9b0c1
Revises: b4c5d6e7f8a9
Create Date: 2026-07-13 17:20:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "d6e7f8a9b0c1"
down_revision = "b4c5d6e7f8a9"
branch_labels = None
depends_on = None
_RPA_IDENTITY_READY_WHERE = (
"snapshot_status = 'ready' "
"AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL "
"AND site_id IS NOT NULL "
"AND warehouse_id IS NOT NULL"
)
def _json_consumed_run_no_expr(dialect_name: str) -> str:
"""按方言生成从 step_payload_json 提取 consumed run_no 的 SQL 表达式。"""
if dialect_name == "postgresql":
return "step_payload_json->>'inventory_rpa_consumed_run_no'"
return "json_extract(step_payload_json, '$.inventory_rpa_consumed_run_no')"
def _backfill_consumed_run_no(bind) -> None:
"""将历史 step_payload_json 中的消费轮次回填到独立列。"""
expr = _json_consumed_run_no_expr(bind.dialect.name)
bind.execute(
sa.text(
f"""
UPDATE shipping_tasks
SET inventory_rpa_consumed_run_no = {expr}
WHERE inventory_rpa_consumed_run_no IS NULL
AND step_payload_json IS NOT NULL
AND {expr} IS NOT NULL
AND TRIM({expr}) != ''
"""
)
)
def _dedupe_duplicate_rpa_snapshots(bind) -> int:
"""
去重相同 RPA 四字段身份的快照(全状态),保留 ready 优先、id 最大的一条。
核心逻辑:迁移关联引用后再过期淘汰记录,避免任务仍指向被淘汰快照。
"""
groups = bind.execute(
sa.text(
"""
SELECT rpa_run_no, source_code, site_id, warehouse_id, COUNT(*) AS cnt
FROM shipping_inventory_files
WHERE rpa_run_no IS NOT NULL AND TRIM(rpa_run_no) != ''
AND source_code IS NOT NULL AND TRIM(source_code) != ''
AND site_id IS NOT NULL AND TRIM(site_id) != ''
AND warehouse_id IS NOT NULL AND TRIM(warehouse_id) != ''
GROUP BY rpa_run_no, source_code, site_id, warehouse_id
HAVING COUNT(*) > 1
"""
)
).fetchall()
active_true = "TRUE" if bind.dialect.name == "postgresql" else "1"
inactive_false = "FALSE" if bind.dialect.name == "postgresql" else "0"
superseded = 0
for group in groups:
rows = bind.execute(
sa.text(
"""
SELECT id
FROM shipping_inventory_files
WHERE rpa_run_no = :run_no
AND source_code = :source_code
AND site_id = :site_id
AND warehouse_id = :warehouse_id
ORDER BY
CASE snapshot_status WHEN 'ready' THEN 0 ELSE 1 END,
id DESC
"""
),
{
"run_no": group.rpa_run_no,
"source_code": group.source_code,
"site_id": group.site_id,
"warehouse_id": group.warehouse_id,
},
).fetchall()
if len(rows) < 2:
continue
keeper_id = rows[0].id
for row in rows[1:]:
superseded_id = row.id
bind.execute(
sa.text(
f"""
UPDATE shipping_task_inventory_links
SET inventory_file_id = :keeper_id
WHERE inventory_file_id = :superseded_id
AND NOT EXISTS (
SELECT 1 FROM shipping_task_inventory_links existing
WHERE existing.task_id = shipping_task_inventory_links.task_id
AND existing.inventory_file_id = :keeper_id
AND existing.is_active = {active_true}
)
"""
),
{"keeper_id": keeper_id, "superseded_id": superseded_id},
)
bind.execute(
sa.text(
f"""
UPDATE shipping_task_inventory_links
SET is_active = {inactive_false}
WHERE inventory_file_id = :superseded_id
"""
),
{"superseded_id": superseded_id},
)
bind.execute(
sa.text(
"""
UPDATE shipping_tasks
SET inventory_snapshot_id = :keeper_id
WHERE inventory_snapshot_id = :superseded_id
"""
),
{"keeper_id": keeper_id, "superseded_id": superseded_id},
)
bind.execute(
sa.text(
"""
UPDATE shipping_inventory_files
SET snapshot_status = 'expired', updated_at = CURRENT_TIMESTAMP
WHERE id = :id
"""
),
{"id": superseded_id},
)
superseded += 1
return superseded
def _sanitize_invalid_stable_inventory_sources(bind) -> None:
"""将缺少完整身份字段的伪稳定任务降级为 unresolved,并清空过期身份残留。"""
bind.execute(
sa.text(
"""
UPDATE shipping_tasks
SET inventory_source_status = 'unresolved',
inventory_source_code = NULL,
inventory_source_method = NULL,
inventory_source_type = NULL,
inventory_site_id = NULL,
inventory_warehouse_id = NULL,
inventory_source_config_version = NULL,
inventory_routing_fingerprint = NULL,
inventory_source_confirmed_by = NULL,
inventory_source_confirmed_at = NULL
WHERE inventory_source_status IN ('resolved', 'user_confirmed')
AND (
inventory_source_code IS NULL OR TRIM(inventory_source_code) = ''
OR inventory_site_id IS NULL OR TRIM(inventory_site_id) = ''
OR inventory_warehouse_id IS NULL OR TRIM(inventory_warehouse_id) = ''
OR inventory_source_config_version IS NULL OR TRIM(inventory_source_config_version) = ''
OR inventory_routing_fingerprint IS NULL OR TRIM(inventory_routing_fingerprint) = ''
)
"""
)
)
def _sanitize_invalid_identity_status(bind) -> None:
"""将非法 identity_status 归一为 unknown。"""
bind.execute(
sa.text(
"""
UPDATE shipping_inventory_files
SET identity_status = 'unknown'
WHERE identity_status IS NOT NULL
AND identity_status NOT IN ('pending', 'verified', 'mismatch', 'unknown')
"""
)
)
def _create_rpa_identity_ready_unique_index() -> None:
"""仅对 ready 快照施加 RPA 身份唯一约束,允许历史 expired 记录共存。"""
op.execute(
sa.text(
f"""
CREATE UNIQUE INDEX uq_shipping_inventory_files_rpa_identity_ready
ON shipping_inventory_files (rpa_run_no, source_code, site_id, warehouse_id)
WHERE {_RPA_IDENTITY_READY_WHERE}
"""
)
)
def upgrade():
"""回填消费轮次、去重快照、清洗数据并添加约束。"""
bind = op.get_bind()
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
batch_op.add_column(sa.Column("inventory_rpa_consumed_run_no", sa.String(length=128), nullable=True))
batch_op.create_index(
"ix_shipping_tasks_inventory_rpa_consumed_run_no",
["inventory_rpa_consumed_run_no"],
unique=False,
)
_backfill_consumed_run_no(bind)
_dedupe_duplicate_rpa_snapshots(bind)
_sanitize_invalid_stable_inventory_sources(bind)
_sanitize_invalid_identity_status(bind)
op.create_check_constraint(
"ck_shipping_tasks_inventory_source_status",
"shipping_tasks",
"inventory_source_status IS NULL OR inventory_source_status IN "
"('resolved', 'user_confirmed', 'ambiguous', 'unresolved', 'invalid', 'conflicted')",
)
op.create_check_constraint(
"ck_shipping_tasks_inventory_source_method",
"shipping_tasks",
"inventory_source_method IS NULL OR inventory_source_method IN "
"('rule_exact', 'rule_combined', 'user_confirmed', 'legacy_migrated', 'manual')",
)
op.create_check_constraint(
"ck_shipping_tasks_stable_inventory_identity",
"shipping_tasks",
"NOT (inventory_source_status IN ('resolved', 'user_confirmed') AND ("
"inventory_source_code IS NULL OR TRIM(inventory_source_code) = '' OR "
"inventory_site_id IS NULL OR TRIM(inventory_site_id) = '' OR "
"inventory_warehouse_id IS NULL OR TRIM(inventory_warehouse_id) = '' OR "
"inventory_source_config_version IS NULL OR TRIM(inventory_source_config_version) = '' OR "
"inventory_routing_fingerprint IS NULL OR TRIM(inventory_routing_fingerprint) = ''"
"))",
)
op.create_check_constraint(
"ck_shipping_inventory_files_identity_status",
"shipping_inventory_files",
"identity_status IS NULL OR identity_status IN ('pending', 'verified', 'mismatch', 'unknown')",
)
op.create_check_constraint(
"ck_shipping_inventory_files_snapshot_status",
"shipping_inventory_files",
"snapshot_status IS NULL OR snapshot_status IN ('ready', 'failed', 'expired')",
)
_create_rpa_identity_ready_unique_index()
def downgrade():
"""移除约束与 consumed run_no 列。"""
op.execute(sa.text("DROP INDEX IF EXISTS uq_shipping_inventory_files_rpa_identity_ready"))
op.drop_constraint("ck_shipping_inventory_files_snapshot_status", "shipping_inventory_files", type_="check")
op.drop_constraint("ck_shipping_inventory_files_identity_status", "shipping_inventory_files", type_="check")
op.drop_constraint("ck_shipping_tasks_stable_inventory_identity", "shipping_tasks", type_="check")
op.drop_constraint("ck_shipping_tasks_inventory_source_method", "shipping_tasks", type_="check")
op.drop_constraint("ck_shipping_tasks_inventory_source_status", "shipping_tasks", type_="check")
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
batch_op.drop_index("ix_shipping_tasks_inventory_rpa_consumed_run_no")
batch_op.drop_column("inventory_rpa_consumed_run_no")