feat(shipping-notice): 添加货代履约策略管理功能,支持策略创建、发布及版本控制,增强订单冻结和预约管理逻辑

This commit is contained in:
hugo committed 2026-07-23 12:06:34 +08:00
1 parent abd8fc1e16
commit d62f5107b2
82 files changed
+4914 -514

No files matched your search

@@ -0,0 +1,34 @@
"""make shipping reservation globally unique
Revision ID: 025b6c7d8e9f
Revises: 024a5b6c7d8e
Create Date: 2026-07-23 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = '025b6c7d8e9f'
down_revision = '024a5b6c7d8e'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""将预约号改为单列全局唯一,并保存首次注册时的标准 PO。"""
with op.batch_alter_table('shipping_reservations') as batch:
batch.add_column(sa.Column('po_number_normalized', sa.String(length=255), nullable=True))
batch.drop_constraint('uq_shipping_reservations_reservation_part', type_='unique')
batch.create_unique_constraint('uq_shipping_reservations_reservation_id', ['reservation_id'])
op.execute("UPDATE shipping_reservations SET po_number_normalized = '' WHERE po_number_normalized IS NULL")
with op.batch_alter_table('shipping_reservations') as batch:
batch.alter_column('po_number_normalized', existing_type=sa.String(length=255), nullable=False)
def downgrade() -> None:
"""恢复旧的 Reservation 与料号联合唯一约束。"""
with op.batch_alter_table('shipping_reservations') as batch:
batch.drop_constraint('uq_shipping_reservations_reservation_id', type_='unique')
batch.create_unique_constraint('uq_shipping_reservations_reservation_part', ['reservation_id', 'part_number'])
batch.drop_column('po_number_normalized')
@@ -0,0 +1,48 @@
"""add shipping fulfillment policies
Revision ID: 026c7d8e9f0a
Revises: 025b6c7d8e9f
Create Date: 2026-07-23 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = '026c7d8e9f0a'
down_revision = '025b6c7d8e9f'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""建立货代专用策略版本表;不影响已冻结的历史 Snapshot。"""
op.create_table(
'shipping_fulfillment_policies',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('schema_id', sa.Integer(), sa.ForeignKey('shipping_order_schemas.id'), nullable=False),
sa.Column('policy_code', sa.String(length=64), nullable=False),
sa.Column('version', sa.Integer(), nullable=False),
sa.Column('status', sa.String(length=16), nullable=False, server_default='draft'),
sa.Column('definition_json', sa.JSON(), nullable=False),
sa.Column('checksum', sa.String(length=64)),
sa.Column('lock_version', sa.Integer(), nullable=False, server_default='1'),
sa.Column('change_note', sa.Text()),
sa.Column('source_policy_id', sa.Integer(), sa.ForeignKey('shipping_fulfillment_policies.id')),
sa.Column('created_by_id', sa.Integer(), sa.ForeignKey('users.id')),
sa.Column('published_by_id', sa.Integer(), sa.ForeignKey('users.id')),
sa.Column('published_at', sa.DateTime()), sa.Column('retired_at', sa.DateTime()),
sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('schema_id', 'policy_code', 'version', name='uq_shipping_fulfillment_policies_version'),
sa.CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_fulfillment_policies_status'),
)
op.create_index(
'uq_shipping_fulfillment_policy_one_published', 'shipping_fulfillment_policies', ['schema_id'], unique=True,
postgresql_where=sa.text("status = 'published'"), sqlite_where=sa.text("status = 'published'"),
)
def downgrade() -> None:
"""移除尚未被 Snapshot 外键引用的策略表。"""
op.drop_index('uq_shipping_fulfillment_policy_one_published', table_name='shipping_fulfillment_policies')
op.drop_table('shipping_fulfillment_policies')
@@ -0,0 +1,172 @@
"""expand shipping standard field catalog
Revision ID: 027d8e9f0a1b
Revises: 026c7d8e9f0a
Create Date: 2026-07-23 00:00:00.000000
用途:以 57 项标准字段目录重建 shipping_order_fields,并清理依赖旧 field_id 的未投产数据。
依赖:shipping_order_schemas / shipping_order_fields 及相关履约、库存配置表。
逻辑:先按外键安全顺序清空受影响事实表,再重插标准字段;含解析绑定审计表须先于 parsing_profiles 删除。
"""
from __future__ import annotations
import uuid
from alembic import op
import sqlalchemy as sa
revision = '027d8e9f0a1b'
down_revision = '026c7d8e9f0a'
branch_labels = None
depends_on = None
STANDARD_FIELDS = (
('customer_po_number', 'header', 'string'), ('order_date', 'header', 'date'),
('source_order_number', 'header', 'string'), ('contract_number', 'header', 'string'),
('order_type', 'header', 'string'), ('sales_channel', 'header', 'string'),
('customer_code', 'header', 'string'), ('customer_name', 'header', 'string'),
('bill_to_customer', 'header', 'string'), ('bill_to_address', 'header', 'string'),
('ship_to_customer', 'header', 'string'), ('ship_to_address', 'header', 'string'),
('end_customer', 'header', 'string'), ('customer_contact', 'header', 'string'),
('ship_from_organization', 'header', 'string'), ('destination', 'header', 'string'),
('currency', 'header', 'string'), ('incoterm', 'header', 'string'),
('payment_term', 'header', 'string'), ('mark_number', 'header', 'string'),
('direct_ship_required', 'header', 'boolean'), ('urgent_order', 'header', 'boolean'),
('order_remark', 'header', 'string'), ('line_no', 'line', 'string'),
('reservation_id', 'line', 'string'), ('part_number', 'line', 'string'),
('product_revision', 'line', 'string'), ('customer_part_number', 'line', 'string'),
('customer_po_line_no', 'line', 'string'), ('product_feature', 'line', 'string'),
('qty', 'line', 'decimal'), ('uom', 'line', 'string'), ('reference_qty', 'line', 'decimal'),
('reference_uom', 'line', 'string'), ('pricing_qty', 'line', 'decimal'),
('pricing_uom', 'line', 'string'), ('required_date', 'line', 'date'),
('requested_receipt_date', 'line', 'date'), ('unit_price', 'line', 'decimal'),
('line_amount_before_tax', 'line', 'decimal'), ('line_tax_amount', 'line', 'decimal'),
('line_amount_with_tax', 'line', 'decimal'), ('tax_category', 'line', 'string'),
('tax_rate', 'line', 'decimal'), ('ship_from_site', 'line', 'string'),
('line_ship_to_address', 'line', 'string'), ('requested_warehouse_code', 'line', 'string'),
('storage_location_code', 'line', 'string'), ('lot_number', 'line', 'string'),
('inventory_source_hint', 'line', 'string'), ('partial_delivery_allowed', 'line', 'boolean'),
('bonded_flag', 'line', 'boolean'), ('package_type', 'line', 'string'),
('project_code', 'line', 'string'), ('wbs_code', 'line', 'string'),
('activity_code', 'line', 'string'), ('line_remark', 'line', 'string'),
)
def upgrade() -> None:
"""清理未投产旧配置/订单事实后,以 57 项目录重新建立字段身份。"""
bind = op.get_bind()
tables = set(sa.inspect(bind).get_table_names())
_reset_affected_shipping_order_data(bind, tables)
if 'shipping_order_snapshots' in tables:
columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_order_snapshots')}
with op.batch_alter_table('shipping_order_snapshots') as batch:
if 'po_number' in columns:
batch.alter_column('po_number', new_column_name='customer_po_number')
if 'shipping_order_snapshot_lines' in tables:
columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_order_snapshot_lines')}
if 'aws_part_number' in columns:
with op.batch_alter_table('shipping_order_snapshot_lines') as batch:
batch.drop_column('aws_part_number')
if not {'shipping_order_schemas', 'shipping_order_fields'} <= tables:
return
schema = bind.execute(sa.text("SELECT id FROM shipping_order_schemas WHERE schema_code = 'SHIPPING_ORDER'")).mappings().first()
if not schema:
return
schema_id = schema['id']
# 业务未投产,旧 field_id 不可安全重解释为新语义,因此一律重新建立。
bind.execute(sa.text("DELETE FROM shipping_order_fields WHERE schema_id = :schema_id"), {'schema_id': schema_id})
for sequence, (field_code, scope, value_type) in enumerate(STANDARD_FIELDS, start=1):
bind.execute(sa.text("""
INSERT INTO shipping_order_fields
(id, schema_id, field_code, scope, value_type, field_category, collection_mode,
display_sequence, status, published_once, created_at, updated_at)
VALUES
(:id, :schema_id, :field_code, :scope, :value_type, :field_category,
'llm_extraction', :sequence, 'active', false, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
"""), {
'id': str(uuid.uuid4()), 'schema_id': schema_id, 'field_code': field_code,
'scope': scope, 'value_type': value_type,
'field_category': 'order_header' if scope == 'header' else 'order_line',
'sequence': sequence,
})
def _reset_affected_shipping_order_data(bind: sa.Connection, tables: set[str]) -> None:
"""删除依赖旧字段身份的未投产配置和履约数据,并解除任务引用。
核心逻辑:先解绑任务/库存源外键,再按依赖末端→前端顺序 DELETE;
parsing_binding_audits 必须早于 parsing_profiles,避免 FK 阻断。
"""
if 'shipping_tasks' in tables:
columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_tasks')}
resets = []
if 'current_order_extraction_id' in columns:
resets.append('current_order_extraction_id = NULL')
if 'order_snapshot_id' in columns:
resets.append('order_snapshot_id = NULL')
if 'source_candidate_id' in columns:
resets.append('source_candidate_id = NULL')
if resets:
bind.execute(sa.text(f"UPDATE shipping_tasks SET {', '.join(resets)}"))
if 'agent_runtime_bindings' in tables:
columns = {item['name'] for item in sa.inspect(bind).get_columns('agent_runtime_bindings')}
if 'quality_batch_id' in columns:
bind.execute(sa.text('UPDATE agent_runtime_bindings SET quality_batch_id = NULL'))
if 'shipping_inventory_sources' in tables:
columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_inventory_sources')}
resets = [name for name in ('parsing_profile_id', 'previous_parsing_profile_id', 'excel_template_id') if name in columns]
if resets:
assignments = [f'{name} = NULL' for name in resets]
if 'enabled' in columns:
assignments.append('enabled = false')
bind.execute(sa.text(f"UPDATE shipping_inventory_sources SET {', '.join(assignments)}"))
# 由最末端向 Schema/Field 反向清理,确保不同部署阶段缺表时也可安全升级。
affected_tables = (
'shipping_notice_candidates', 'shipping_excel_templates',
'shipping_upload_attempts', 'shipping_export_artifact_lines',
'shipping_inventory_verification_lines', 'shipping_reservations',
'shipping_inventory_verifications', 'shipping_export_artifacts',
'shipping_order_review_events', 'shipping_order_snapshot_lines', 'shipping_order_snapshots',
'shipping_order_customer_matches', 'shipping_order_field_values',
'shipping_order_field_decisions', 'shipping_order_field_observations',
'shipping_order_lines', 'shipping_order_extractions',
'shipping_order_extraction_quality_labels', 'shipping_order_extraction_progress_events',
'shipping_order_extraction_diagnostic_audits', 'shipping_order_extraction_units',
'shipping_order_extraction_plans', 'shipping_order_extraction_run_intakes',
'shipping_order_extraction_runs', 'shipping_order_extraction_quality_batches',
'shipping_customer_shadow_matches', 'shipping_customer_shadow_resolutions',
'shipping_document_profile_test_runs', 'shipping_document_profile_test_samples',
'shipping_document_profile_test_suites', 'shipping_order_document_profiles',
'shipping_inventory_routing_rule_versions', 'shipping_inventory_routing_rule_conditions',
'shipping_inventory_routing_rules',
# [STEP] 先清绑定审计,再删 parsing_profiles,避免 previous/current 外键挡住删除。
'shipping_inventory_source_parsing_binding_audits',
'shipping_inventory_parsing_profiles',
'shipping_identity_evidences', 'shipping_identity_rule_audit_events',
'shipping_identity_rule_sets', 'shipping_identity_definitions',
'shipping_fulfillment_policies', 'shipping_order_schema_audit_events',
'shipping_order_schema_versions',
)
for table in affected_tables:
if table in tables:
bind.execute(sa.text(f'DELETE FROM {table}'))
def downgrade() -> None:
"""仅恢复已重命名/移除的物理兼容列;字段目录按发布记录仍不可无损回退。"""
bind = op.get_bind()
tables = set(sa.inspect(bind).get_table_names())
if 'shipping_order_snapshot_lines' in tables:
columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_order_snapshot_lines')}
if 'aws_part_number' not in columns:
with op.batch_alter_table('shipping_order_snapshot_lines') as batch:
batch.add_column(sa.Column('aws_part_number', sa.String(length=255), nullable=True))
if 'shipping_order_snapshots' in tables:
columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_order_snapshots')}
if 'customer_po_number' in columns:
with op.batch_alter_table('shipping_order_snapshots') as batch:
batch.alter_column('customer_po_number', new_column_name='po_number')
@@ -135,7 +135,7 @@ def upgrade() -> None:
)
op.create_index('ix_shipping_inventory_external_mappings_inventory_source_id', 'shipping_inventory_external_mappings', ['inventory_source_id'])
op.create_index(
'uq_shipping_inventory_external_mappings_source_default_enabled',
'uq_shipping_inv_ext_map_src_default_enabled',
'shipping_inventory_external_mappings',
['inventory_source_id'],
unique=True,
@@ -143,7 +143,7 @@ def upgrade() -> None:
sqlite_where=sa.text('freight_warehouse_id IS NULL AND enabled = 1'),
)
op.create_index(
'uq_shipping_inventory_external_mappings_source_warehouse_enabled',
'uq_shipping_inv_ext_map_src_wh_enabled',
'shipping_inventory_external_mappings',
['inventory_source_id', 'freight_warehouse_id'],
unique=True,
@@ -51,7 +51,6 @@ def _published_purposes(bind) -> dict[str, str]:
def upgrade() -> None:
"""仅迁移草稿规则;已发布规则若仍使用固定事实则阻断,禁止混合运行路径。"""
bind = op.get_bind()
purposes = _published_purposes(bind)
rules = sa.table(
'shipping_inventory_routing_rules',
sa.column('id', sa.Integer()), sa.column('status', sa.String()),
@@ -66,9 +65,13 @@ def upgrade() -> None:
.join(rules, rules.c.id == conditions.c.rule_id)
.where(conditions.c.system_fact_key.in_(tuple(_FACT_TO_PURPOSE)))
).mappings().all()
# 新库不存在旧固定事实条件,无需强制要求尚未配置的 published Schema。
if not legacy:
return
published = [row for row in legacy if row['status'] == 'published']
if published:
raise RuntimeError('Published routing rules still use fixed system facts; retire and replace them before migration')
purposes = _published_purposes(bind)
for row in legacy:
if row['status'] != 'draft':
continue
@@ -91,12 +91,18 @@ def _backfill_legacy_inventory_source() -> None:
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()
# `step_payload_json` was introduced by a sibling historical migration, not
# this revision's ancestor chain. Fresh databases therefore have no legacy
# JSON to backfill, while upgraded legacy databases can still preserve it.
task_columns = {item["name"] for item in sa.inspect(bind).get_columns("shipping_tasks")}
rows = []
if "step_payload_json" in task_columns:
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):
@@ -175,36 +181,15 @@ def _backfill_legacy_inventory_source() -> None:
},
)
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},
)
_mark_unresolved(bind, task_columns, "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'"
)
_mark_unresolved(
bind,
task_columns,
"inventory_source_status IN ('ambiguous', 'unresolved', 'conflicted', 'invalid') "
"AND (pending_human_reason IS NULL OR pending_human_reason = '')",
)
_mark_unresolved(bind, task_columns, "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")
@@ -218,6 +203,21 @@ def _backfill_legacy_inventory_source() -> None:
)
def _mark_unresolved(
bind: sa.Connection,
task_columns: set[str],
where_clause: str,
params: dict[str, object] | None = None,
) -> None:
"""回填旧状态时只写当前历史分支实际拥有的任务列。"""
assignments = ["pending_human_reason = 'inventory_source_unresolved'"]
if "current_step" in task_columns:
assignments.append("current_step = 'step2_parse_confirm'")
if "process_status" in task_columns:
assignments.append("process_status = 'pending_review'")
bind.execute(sa.text(f"UPDATE shipping_tasks SET {', '.join(assignments)} WHERE {where_clause}"), params or {})
def downgrade():
"""Remove inventory source gate columns."""
with op.batch_alter_table("shipping_task_inventory_links", schema=None) as batch_op:
@@ -12,6 +12,7 @@ Create Date: 2026-07-17 10:28:00.000000
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
@@ -23,6 +24,10 @@ depends_on = None
def upgrade() -> None:
"""将 shipping_inventory_erp_mappings 重命名为 shipping_inventory_external_mappings。"""
tables = set(sa.inspect(op.get_bind()).get_table_names())
# 空库链已由 2b3c 直接创建 external 表;只有历史库保留 erp 表时才需要重命名。
if 'shipping_inventory_erp_mappings' not in tables:
return
# [STEP 1] 表名
op.rename_table('shipping_inventory_erp_mappings', 'shipping_inventory_external_mappings')
@@ -60,11 +65,11 @@ def upgrade() -> None:
)
op.execute(
'ALTER INDEX IF EXISTS uq_shipping_inventory_erp_mappings_source_default_enabled '
'RENAME TO uq_shipping_inventory_external_mappings_source_default_enabled'
'RENAME TO uq_shipping_inv_ext_map_src_default_enabled'
)
op.execute(
'ALTER INDEX IF EXISTS uq_shipping_inventory_erp_mappings_source_warehouse_enabled '
'RENAME TO uq_shipping_inventory_external_mappings_source_warehouse_enabled'
'RENAME TO uq_shipping_inv_ext_map_src_wh_enabled'
)
op.execute(
'ALTER INDEX IF EXISTS shipping_inventory_erp_mappings_pkey '
@@ -74,16 +79,19 @@ def upgrade() -> None:
def downgrade() -> None:
"""回滚为 erp_* 表与列名。"""
tables = set(sa.inspect(op.get_bind()).get_table_names())
if 'shipping_inventory_external_mappings' not in tables:
return
op.execute(
'ALTER INDEX IF EXISTS shipping_inventory_external_mappings_pkey '
'RENAME TO shipping_inventory_erp_mappings_pkey'
)
op.execute(
'ALTER INDEX IF EXISTS uq_shipping_inventory_external_mappings_source_warehouse_enabled '
'ALTER INDEX IF EXISTS uq_shipping_inv_ext_map_src_wh_enabled '
'RENAME TO uq_shipping_inventory_erp_mappings_source_warehouse_enabled'
)
op.execute(
'ALTER INDEX IF EXISTS uq_shipping_inventory_external_mappings_source_default_enabled '
'ALTER INDEX IF EXISTS uq_shipping_inv_ext_map_src_default_enabled '
'RENAME TO uq_shipping_inventory_erp_mappings_source_default_enabled'
)
op.execute(
@@ -38,6 +38,9 @@ def _json_consumed_run_no_expr(dialect_name: str) -> str:
def _backfill_consumed_run_no(bind) -> None:
"""将历史 step_payload_json 中的消费轮次回填到独立列。"""
task_columns = {item["name"] for item in sa.inspect(bind).get_columns("shipping_tasks")}
if "step_payload_json" not in task_columns:
return
expr = _json_consumed_run_no_expr(bind.dialect.name)
bind.execute(
sa.text(