feat(shipping-notice): 落地字段资产治理与唯一 Schema,自动建单随版本冻结
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
b7307fc573
commit
3a1dbf7ce5
144 files changed
+15167
-4480
No files matched your search
@@ -24,6 +24,7 @@ import app.api.admin.shipping_customers # noqa: F401
|
||||
import app.api.admin.shipping_identity_rules # noqa: F401
|
||||
import app.api.admin.shipping_inventory # noqa: F401
|
||||
import app.api.admin.shipping_order_schema # noqa: F401
|
||||
import app.api.admin.shipping_field_assets # noqa: F401
|
||||
import app.api.admin.shipping_order_document_profiles # noqa: F401
|
||||
import app.api.admin.shipping_document_layouts # noqa: F401
|
||||
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"""
|
||||
backend/app/api/admin/shipping_field_assets.py
|
||||
|
||||
用途:货代字段资产治理管理 API(列表/详情/扩展 CRUD、弃用恢复、影响分析)。
|
||||
依赖:admin blueprint、require_admin、field_asset_service、field_impact_analysis。
|
||||
逻辑:路由只读取参数与管理员身份;资产校验、审计与事务由 field_asset_service 完成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
from app.services.shipping_notice import field_impact_analysis
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
"""读取 require_admin 写入请求上下文的管理员 ID。"""
|
||||
return getattr(getattr(g, 'current_user', None), 'id', None)
|
||||
|
||||
|
||||
def _ok(data, *, status: int = 200):
|
||||
"""按平台统一 envelope 返回管理 API 成功结果。"""
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-field-assets', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_field_assets():
|
||||
"""分页列出全局字段资产,支持编码搜索与 kind/status/scope 筛选。"""
|
||||
return _ok(field_asset_service.list_assets(
|
||||
q=request.args.get('q'),
|
||||
asset_kind=request.args.get('asset_kind'),
|
||||
status=request.args.get('status'),
|
||||
scope=request.args.get('scope'),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-field-assets/<field_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_field_asset(field_id: str):
|
||||
"""读取单个字段资产详情。"""
|
||||
return _ok(field_asset_service.get_asset(field_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-field-assets', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_field_asset():
|
||||
"""创建扩展字段资产;标准编码与 mail/context 编码由服务层拒绝。"""
|
||||
return _ok(field_asset_service.create_extension(
|
||||
request.get_json(silent=True) or {},
|
||||
actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-field-assets/<field_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_field_asset(field_id: str):
|
||||
"""更新扩展字段显示属性;系统标准字段只读。"""
|
||||
return _ok(field_asset_service.update_extension(
|
||||
field_id,
|
||||
request.get_json(silent=True) or {},
|
||||
actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-field-assets/<field_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_shipping_field_asset(field_id: str):
|
||||
"""弃用扩展字段;请求体须含 reason;有阻断下游时须 confirm_impact=true。"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return _ok(field_asset_service.retire_extension(
|
||||
field_id,
|
||||
reason=str(payload.get('reason') or ''),
|
||||
actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
confirm_impact=bool(payload.get('confirm_impact')),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-field-assets/<field_id>/restore', methods=['POST'])
|
||||
@require_admin
|
||||
def restore_shipping_field_asset(field_id: str):
|
||||
"""恢复已弃用的扩展字段。"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return _ok(field_asset_service.restore_extension(
|
||||
field_id,
|
||||
reason=str(payload.get('reason') or 'restored via admin API'),
|
||||
actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-field-assets/<field_id>/impact', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_field_asset_impact(field_id: str):
|
||||
"""只读分析字段资产在下游配置与历史运行中的引用影响。"""
|
||||
return _ok(field_impact_analysis.analyze_field_impact(field_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-field-assets/<field_id>/audits', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_field_asset_audits(field_id: str):
|
||||
"""读取单字段审计时间线(含采用/取消采用与扩展生命周期事件)。"""
|
||||
limit = request.args.get('limit', 50, type=int)
|
||||
return _ok(field_asset_service.list_asset_audits(field_id, limit=limit or 50))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-field-assets/<field_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_field_asset(field_id: str):
|
||||
"""物理删除已禁止;应使用 retire 或取消 Schema 采用。"""
|
||||
del field_id
|
||||
field_asset_service.forbid_physical_delete()
|
||||
return _ok({})
|
||||
@@ -135,7 +135,7 @@ def list_order_document_profile_samples():
|
||||
raise service.ValidationError(
|
||||
'limit is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
) from exc
|
||||
return _ok(service.list_sample_documents(limit=limit))
|
||||
return _ok(service.list_sample_documents(actor_id=_actor_id(), limit=limit))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-samples', methods=['POST'])
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/api/admin/shipping_order_schema.py
|
||||
|
||||
用途:提供唯一货代订单 Schema、字段目录和版本发布的管理 API。
|
||||
依赖:admin blueprint、require_admin、order_schema.service。
|
||||
逻辑:路由只读取参数和管理员身份;字段校验、不可变性与事务由领域服务完成。
|
||||
用途:提供唯一发货订单 Schema、字段目录和版本发布的管理 API。
|
||||
依赖:admin blueprint、require_admin、order_schema.service、fulfillment_policy_registry。
|
||||
逻辑:路由读取管理员身份;字段校验、不可变性与事务由领域服务完成。
|
||||
固定操作默认 Schema STANDARD_SHIPPING_NOTICE;不接受 family_code,不下线表结构。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,8 +14,11 @@ from flask import g, request
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.models.shipping_order_schema import ShippingOrderField
|
||||
from app.services.shipping_notice.order_schema import service
|
||||
from app.services.shipping_notice import fulfillment_policy_registry
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
from app.services.shipping_notice.standard_field_registry import DEFAULT_V1_ADOPTION_CODES
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
@@ -30,26 +34,33 @@ def _ok(data, *, status: int = 200):
|
||||
@admin_bp.route('/shipping-order-schema', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_order_schema():
|
||||
"""读取订单 Schema 管理状态和受控字段能力目录。"""
|
||||
"""读取唯一发货订单 Schema 管理状态和受控字段能力目录。"""
|
||||
return _ok(service.get_state())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/auto-creation-policy', methods=['GET', 'PUT'])
|
||||
@require_admin
|
||||
def shipping_order_auto_creation_policy():
|
||||
"""读取或更新订单解析自动建单总开关;字段阈值由 Schema 草稿维护。"""
|
||||
"""
|
||||
GET:读取已发布生效的自动建单策略。
|
||||
PUT:已废弃;须写入 Schema 草稿并随版本发布生效。
|
||||
"""
|
||||
if request.method == 'GET':
|
||||
return _ok(service.get_auto_creation_policy())
|
||||
return _ok(service.save_auto_creation_policy(request.get_json(silent=True) or {}, actor_id=_actor_id()))
|
||||
return _ok(service.save_auto_creation_policy(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-fulfillment-policies', methods=['GET', 'POST'])
|
||||
@require_admin
|
||||
def shipping_fulfillment_policies():
|
||||
"""读取策略能力目录或创建新的货代履约策略草稿。"""
|
||||
"""读取履约策略能力目录或创建新的货代履约策略草稿。"""
|
||||
if request.method == 'GET':
|
||||
return _ok(fulfillment_policy_registry.get_state())
|
||||
return _ok(fulfillment_policy_registry.create_draft(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
return _ok(fulfillment_policy_registry.create_draft(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-fulfillment-policies/<int:policy_id>/publish', methods=['POST'])
|
||||
@@ -65,8 +76,10 @@ def publish_shipping_fulfillment_policy(policy_id: int):
|
||||
@admin_bp.route('/shipping-order-schema', methods=['POST'])
|
||||
@require_admin
|
||||
def initialize_shipping_order_schema():
|
||||
"""初始化全局唯一订单 Schema。"""
|
||||
return _ok(service.initialize_schema(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
"""初始化唯一发货订单 Schema。"""
|
||||
return _ok(service.initialize_schema(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/fields', methods=['POST'])
|
||||
@@ -118,52 +131,52 @@ def delete_shipping_order_field(field_id: str):
|
||||
@admin_bp.route('/shipping-order-schema/versions', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_order_schema_version():
|
||||
"""创建下一订单 Schema 草稿,可复制已有版本。"""
|
||||
"""创建下一草稿,可从当前发布版复制。"""
|
||||
return _ok(service.create_draft(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
|
||||
request.get_json(silent=True) or {},
|
||||
actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/versions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_order_schema_versions():
|
||||
"""分页读取订单 Schema 全部版本概要,供历史抽屉按需加载。"""
|
||||
"""分页列出 Schema 版本;可按 version 数字精确过滤。"""
|
||||
try:
|
||||
page = int(request.args.get('page', '1'))
|
||||
page_size = int(request.args.get('page_size', '20'))
|
||||
version_number = request.args.get('version_number')
|
||||
parsed_version_number = int(version_number) if version_number is not None else None
|
||||
version = request.args.get('version')
|
||||
parsed_version = int(version) if version is not None else None
|
||||
except ValueError as exc:
|
||||
raise service.ValidationError('page must be an integer') from exc
|
||||
return _ok(service.list_versions(
|
||||
page=page, page_size=page_size, version_number=parsed_version_number,
|
||||
))
|
||||
return _ok(service.list_versions(page=page, page_size=page_size, version_number=parsed_version))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_order_schema_version(version_id: int):
|
||||
"""读取一个版本的完整只读快照,供历史查看和后续版本比较使用。"""
|
||||
"""读取指定版本完整快照。"""
|
||||
return _ok(service.get_version_detail(version_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>/diff', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_order_schema_version_diff(version_id: int):
|
||||
"""返回两个版本之间由服务端计算的字段级语义差异。"""
|
||||
def diff_shipping_order_schema_version(version_id: int):
|
||||
"""比较两个 Schema 版本定义差异。"""
|
||||
try:
|
||||
against_version_id = int(request.args['against_version_id'])
|
||||
except (KeyError, ValueError) as exc:
|
||||
raise service.ValidationError(
|
||||
'against_version_id is required', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
|
||||
) from exc
|
||||
return _ok(service.get_version_diff(version_id, against_version_id=against_version_id))
|
||||
against_version_id = int(request.args.get('against_version_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise service.ValidationError('against_version_id must be an integer') from exc
|
||||
return _ok(service.get_version_diff(
|
||||
version_id, against_version_id=against_version_id,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/audit-events', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_order_schema_audit_events():
|
||||
"""分页读取订单 Schema 的只读配置审计时间线。"""
|
||||
"""分页读取唯一 Schema 的只读配置审计时间线。"""
|
||||
try:
|
||||
page = int(request.args.get('page', '1'))
|
||||
page_size = int(request.args.get('page_size', '20'))
|
||||
@@ -171,7 +184,11 @@ def list_shipping_order_schema_audit_events():
|
||||
parsed_version_id = int(version_id) if version_id is not None else None
|
||||
except ValueError as exc:
|
||||
raise service.ValidationError('page must be an integer') from exc
|
||||
return _ok(service.list_audit_events(page=page, page_size=page_size, version_id=parsed_version_id))
|
||||
return _ok(service.list_audit_events(
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
version_id=parsed_version_id,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>/usage', methods=['GET'])
|
||||
@@ -205,7 +222,9 @@ def get_shipping_order_schema_extraction_audit(extraction_id: int):
|
||||
def update_shipping_order_schema_version(version_id: int):
|
||||
"""整体替换草稿字段配置。"""
|
||||
return _ok(service.save_draft(
|
||||
version_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
version_id,
|
||||
request.get_json(silent=True) or {},
|
||||
actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
@@ -213,11 +232,11 @@ def update_shipping_order_schema_version(version_id: int):
|
||||
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_order_schema_version(version_id: int):
|
||||
"""删除错误草稿,已发布和退役版本由服务层保护。"""
|
||||
"""删除错误草稿;发布版本由服务端拒绝。"""
|
||||
service.delete_draft(
|
||||
version_id, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
return '', 204
|
||||
return _ok(None)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>/publish', methods=['POST'])
|
||||
@@ -235,5 +254,22 @@ def publish_shipping_order_schema_version(version_id: int):
|
||||
@admin_bp.route('/shipping-order-schema/published-contract', methods=['GET'])
|
||||
@require_admin
|
||||
def get_published_shipping_order_contract():
|
||||
"""读取当前发布的精简字段契约,供配置验证和 Dify 文档维护使用。"""
|
||||
"""读取当前已发布精简字段契约,供配置验证和 Dify 文档维护使用。"""
|
||||
return _ok(service.get_published_contract())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/suggested-adoption', methods=['GET'])
|
||||
@require_admin
|
||||
def get_suggested_field_adoption():
|
||||
"""返回首发建议采用的标准 field_code 及对应 active 资产 ID,供 Schema 草稿勾选辅助。"""
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
codes = list(DEFAULT_V1_ADOPTION_CODES)
|
||||
rows = ShippingOrderField.query.filter(
|
||||
ShippingOrderField.field_code.in_(codes),
|
||||
ShippingOrderField.status == 'active',
|
||||
).all()
|
||||
by_code = {row.field_code: row.id for row in rows}
|
||||
return _ok({
|
||||
'codes': codes,
|
||||
'field_ids': [by_code[code] for code in codes if code in by_code],
|
||||
})
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/api/workspace/shipping_notice.py
|
||||
|
||||
用途:HXOPS 工作台与聊天前端使用的发货通知用户态 API。
|
||||
用途:HXOPS 工作台发货通知用户态 API(任务处理工作台为履约写操作入口;Chat 仅通知/上传)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload / ui_state。
|
||||
逻辑:薄路由层鉴权与参数校验;register_blueprints 经 workspace 包注册。
|
||||
逻辑:薄路由层鉴权与参数校验;写接口保留乐观锁、幂等键与统一 AppError;
|
||||
人工上传强制证据资产;Chat Turn 履约写路径已废弃,请改走本 Blueprint。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -26,11 +27,13 @@ from app.services.shipping_notice.constants import (
|
||||
from app.services.shipping_notice.tool_common import switch_batch_focus
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
count_my_todos,
|
||||
get_batch_for_user,
|
||||
get_conversation_batch_workspace,
|
||||
get_focus_task_for_batch,
|
||||
get_task_for_user,
|
||||
list_batches_for_user,
|
||||
list_my_todos,
|
||||
list_tasks_page_for_user,
|
||||
list_tasks_for_batch,
|
||||
resolve_task_export_download,
|
||||
@@ -100,6 +103,44 @@ def workspace_shipping_tasks():
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/my-todos', methods=['GET'])
|
||||
def workspace_shipping_my_todos():
|
||||
"""
|
||||
分页列出当前用户「我的待办」(pending / processing / done)。
|
||||
|
||||
核心逻辑:委托 query_service.list_my_todos;管理员可读全局但 can_handle 仅创建者。
|
||||
"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.query_service import list_my_todos
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
try:
|
||||
page = int(request.args.get('page') or 1)
|
||||
page_size = int(request.args.get('page_size') or 20)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('page and page_size must be integers') from exc
|
||||
return _ok(list_my_todos(
|
||||
user.id,
|
||||
bucket=str(request.args.get('bucket') or 'pending'),
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
is_admin=is_admin,
|
||||
todo_category=str(request.args.get('todo_category') or '').strip() or None,
|
||||
customer=str(request.args.get('customer') or '').strip() or None,
|
||||
task_no=str(request.args.get('task_no') or '').strip() or None,
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/my-todos/count', methods=['GET'])
|
||||
def workspace_shipping_my_todos_count():
|
||||
"""返回「我的待办」各 bucket 计数,供导航徽标使用。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.query_service import count_my_todos
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
return _ok(count_my_todos(user.id, is_admin=is_admin))
|
||||
|
||||
|
||||
def _batch_task_nos(data: dict) -> list[str]:
|
||||
"""校验批量任务号,统一限制 100 条并去重,避免前端循环绕过服务端门禁。"""
|
||||
raw_task_nos = data.get('task_nos')
|
||||
@@ -524,11 +565,13 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
checkpoint / action_buttons / steps,减少前端二次推导与竞态刷新。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok({
|
||||
**serialize_task_detail(task),
|
||||
**serialize_task_detail(task, viewer_user_id=user.id, is_admin=is_admin),
|
||||
'ui_state': build_task_ui_state(task),
|
||||
})
|
||||
|
||||
@@ -902,13 +945,12 @@ def workspace_mark_manual_uploaded(task_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
|
||||
def workspace_retry_shipping_upload(task_no: str):
|
||||
"""用户态重试上传货代系统,直接触发既有 RPA 上传链路。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'retry_upload'}))
|
||||
"""首期禁用货代 RPA 重试上传;引导用户改走人工凭据登记。"""
|
||||
_require_user()
|
||||
raise ValidationError(
|
||||
'首期不支持货代 RPA 上传重试。请下载 Excel,在货代系统人工上传后提交截图/PDF 凭据。',
|
||||
code='SHIPPING.FREIGHT_RPA_UPLOAD_DISABLED',
|
||||
)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST'])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
@@ -1043,20 +1085,22 @@ def workspace_list_shipping_order_extraction_documents(run_no: str):
|
||||
def workspace_get_shipping_order_review_run(run_no: str):
|
||||
"""读取当前用户 Run 的复核 Case 汇总;不返回机器原文或内部执行快照。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_run
|
||||
from app.services.shipping_notice.order_review_service import get_user_review_run
|
||||
from app.services.shipping_notice.order_review_service import get_review_run_visible_to_user
|
||||
|
||||
return _ok(serialize_review_run(get_user_review_run(user_id=user.id, run_no=run_no)))
|
||||
return _ok(serialize_review_run(get_review_run_visible_to_user(run_no, user.id, is_admin=is_admin)))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>', methods=['GET'])
|
||||
def workspace_get_shipping_order_review_case(case_no: str):
|
||||
"""读取当前用户的一份 PDF 复核详情;Case 编号不能跨 owner 越权访问。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
from app.services.shipping_notice.order_review_service import get_user_review_case
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
|
||||
return _ok(serialize_review_case(get_user_review_case(user_id=user.id, case_no=case_no)))
|
||||
return _ok(serialize_review_case(get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin)))
|
||||
|
||||
|
||||
def _review_draft_payload() -> dict:
|
||||
@@ -1145,9 +1189,12 @@ def workspace_validate_shipping_order_review_draft(case_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/confirm', methods=['POST'])
|
||||
def workspace_confirm_shipping_order_review_case(case_no: str):
|
||||
"""确认一份 PDF 草稿并独立建单;请求版本和幂等键不可省略。"""
|
||||
"""确认一份 PDF 草稿并独立建单;提交后复用 auto_progress 自动推进。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_confirmation_service import confirm_review_case
|
||||
from app.services.shipping_notice.order_review_confirmation_service import (
|
||||
confirm_review_case,
|
||||
trigger_auto_progress_after_review_confirm,
|
||||
)
|
||||
|
||||
payload = _review_draft_payload()
|
||||
result = confirm_review_case(
|
||||
@@ -1158,6 +1205,20 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
|
||||
warning_acknowledgements=payload.get('warning_acknowledgements'),
|
||||
)
|
||||
db.session.commit()
|
||||
# [STEP] 事务提交后再走与 STP 直通相同的 auto_progress,避免未提交任务被推进。
|
||||
progress = trigger_auto_progress_after_review_confirm(
|
||||
task_no=result.get('task_no'),
|
||||
idempotent_replay=bool(result.get('idempotent_replay')),
|
||||
)
|
||||
if progress is not None:
|
||||
result = dict(result)
|
||||
result.pop('trigger_auto_progress', None)
|
||||
result['auto_progress'] = {
|
||||
'status': progress.get('status'),
|
||||
'message': progress.get('message'),
|
||||
'checkpoint': progress.get('checkpoint'),
|
||||
}
|
||||
result['auto_progress_started'] = True
|
||||
return _ok(result)
|
||||
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
mark_order_extraction_persistence_started,
|
||||
order_extraction_layout_prerequisite_issues,
|
||||
materialize_order_extraction_run_inputs,
|
||||
progress_ready_extraction_unit,
|
||||
schedule_order_extraction_layouts,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
@@ -123,6 +124,8 @@ def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) ->
|
||||
'matched_table_count': int(decision.get('matched_table_count') or 0),
|
||||
'parsed_table_count': int(decision.get('parsed_table_count') or 0),
|
||||
'match_status': str(decision.get('match_status') or 'no_match'),
|
||||
'route_decision': str(decision.get('route_decision') or ''),
|
||||
'reason_codes': [str(code) for code in decision.get('reason_codes') or decision.get('fallback_reason_codes') or []],
|
||||
},
|
||||
)
|
||||
|
||||
@@ -595,6 +598,16 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
unit_orders_by_id[int(unit.id)] = [item for item in saved_orders if isinstance(item, dict)]
|
||||
persisted_orders.extend(unit_orders_by_id[int(unit.id)])
|
||||
wave_orders.extend(unit_orders_by_id[int(unit.id)])
|
||||
# 重试路径:已 candidate_ready 的 Unit 仍须独立触发下游(幂等)。
|
||||
try:
|
||||
progress_ready_extraction_unit(
|
||||
run=run, unit=unit, orders=unit_orders_by_id[int(unit.id)],
|
||||
)
|
||||
except Exception:
|
||||
from flask import current_app
|
||||
current_app.logger.exception(
|
||||
'retry unit progress failed run=%s unit=%s', run.run_no, unit.id,
|
||||
)
|
||||
continue
|
||||
if unit.status == 'review_required':
|
||||
continue
|
||||
@@ -735,6 +748,32 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
},
|
||||
job_id=job.id,
|
||||
)
|
||||
# [STEP] 每 PDF 独立下游:立刻物化 Candidate / STP 建单,不阻塞同批其它 Unit。
|
||||
try:
|
||||
unit_persist = progress_ready_extraction_unit(
|
||||
run=run, unit=unit, orders=merged_unit_orders,
|
||||
)
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
unit=unit,
|
||||
event_code='unit_persisted',
|
||||
summary={
|
||||
'created_count': int(unit_persist.get('created_count') or 0),
|
||||
'pending_count': int(unit_persist.get('pending_count') or 0),
|
||||
'idempotent_replay': bool(unit_persist.get('idempotent_replay')),
|
||||
},
|
||||
job_id=job.id,
|
||||
)
|
||||
except Exception as unit_exc:
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
unit=unit,
|
||||
event_code='unit_persist_failed',
|
||||
reason_code=getattr(unit_exc, 'code', None) or 'unit_persist_failed',
|
||||
summary={'error': str(unit_exc)[:300]},
|
||||
job_id=job.id,
|
||||
)
|
||||
raise
|
||||
orders = persisted_orders + merged_orders
|
||||
execution = {
|
||||
'mode': 'deterministic',
|
||||
@@ -748,7 +787,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
run.extraction_completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
# [STEP 2] Candidate 写入与解析执行分离;落库失败可重试,已完成 Unit 不重复解析。
|
||||
# [STEP 2] Run 收口:已按 Unit 独立落库;此处再跑一遍全量 submit 幂等对齐未消费 Unit / Review Case。
|
||||
mark_order_extraction_persistence_started(run)
|
||||
result = submit_order_extraction_run_result(run=run, orders=orders)
|
||||
requires_review = runtime_budget_stopped or _result_requires_review(units=units, result=result)
|
||||
|
||||
@@ -40,6 +40,7 @@ from app.models.shipping_fulfillment import (
|
||||
)
|
||||
from app.models.shipping_fulfillment_policy import ShippingFulfillmentPolicy
|
||||
from app.models.shipping_order_schema import (
|
||||
ShippingFieldAsset,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSchemaAuditEvent,
|
||||
ShippingOrderField,
|
||||
@@ -49,6 +50,7 @@ from app.models.shipping_order_schema import (
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingSchemaFamily,
|
||||
)
|
||||
from app.models.shipping_order_customer_match import ShippingOrderCustomerMatch
|
||||
from app.models.shipping_order_snapshot import (
|
||||
@@ -170,9 +172,11 @@ __all__ = [
|
||||
'ShippingContextProvider',
|
||||
'ShippingContextProviderOption',
|
||||
'ShippingOrderSchema',
|
||||
'ShippingSchemaFamily',
|
||||
'ShippingOrderSchemaVersion',
|
||||
'ShippingOrderSchemaAuditEvent',
|
||||
'ShippingOrderField',
|
||||
'ShippingFieldAsset',
|
||||
'ShippingOrderExtraction',
|
||||
'ShippingOrderLine',
|
||||
'ShippingOrderFieldObservation',
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/models/shipping_order_schema.py
|
||||
|
||||
用途:定义货代订单唯一 Schema、不可变版本、配置审计及动态订单解析结果。
|
||||
依赖:models.base.Base、shipping_tasks、shipping_notice_intakes、shipping_context_providers、users。
|
||||
逻辑:草稿和发布版本统一保存完整 JSON 定义;写操作追加审计事件;解析链锁定发布版本并保存裁决结果。
|
||||
用途:定义货代字段资产、Schema 族/不可变版本、配置审计及动态订单解析结果。
|
||||
依赖:models.base.Base、shipping_tasks、shipping_notice_intakes、users。
|
||||
逻辑:字段资产全局存活(标准只读、扩展可弃用);Schema 族版本仅采用资产并冻结 definition_json;
|
||||
写操作追加审计;解析链锁定发布版本。表名保留历史命名以降低迁移耦合。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -44,18 +45,14 @@ def _default_field_category(context: Any) -> str:
|
||||
|
||||
|
||||
class ShippingOrderSchema(Base):
|
||||
"""全局唯一货代订单 Schema;当前业务只允许一个逻辑 Schema。"""
|
||||
"""Schema 族容器;本轮默认族编码 STANDARD_SHIPPING_NOTICE,模型允许多族。"""
|
||||
|
||||
__tablename__ = 'shipping_order_schemas'
|
||||
__table_args__ = (
|
||||
CheckConstraint("schema_code = 'SHIPPING_ORDER'", name='ck_shipping_order_schemas_single_code'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schema_code: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
|
||||
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
# 自动建单是订单解析的运行策略,不属于不可变字段模板版本。
|
||||
auto_creation_policy_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
@@ -63,27 +60,27 @@ class ShippingOrderSchema(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
fields: Mapped[list['ShippingOrderField']] = relationship(
|
||||
back_populates='schema', cascade='all, delete-orphan', order_by='ShippingOrderField.display_sequence'
|
||||
)
|
||||
versions: Mapped[list['ShippingOrderSchemaVersion']] = relationship(
|
||||
back_populates='schema', cascade='all, delete-orphan', order_by='ShippingOrderSchemaVersion.version'
|
||||
)
|
||||
|
||||
|
||||
ShippingSchemaFamily = ShippingOrderSchema
|
||||
|
||||
|
||||
class ShippingOrderField(Base):
|
||||
"""订单字段稳定身份;下游使用 field_id,版本快照冻结当时的名称和规则。"""
|
||||
"""全局字段资产(系统标准或扩展)。标准不可弃用/删除;扩展仅 active⇄retired。"""
|
||||
|
||||
__tablename__ = 'shipping_order_fields'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('schema_id', 'field_code', name='uq_shipping_order_fields_schema_code'),
|
||||
UniqueConstraint('field_code', name='uq_shipping_order_fields_field_code'),
|
||||
CheckConstraint("scope IN ('header', 'line')", name='ck_shipping_order_fields_scope'),
|
||||
CheckConstraint(
|
||||
"field_category IN ('general_context', 'order_header', 'order_line')",
|
||||
"field_category IN ('order_header', 'order_line')",
|
||||
name='ck_shipping_order_fields_category',
|
||||
),
|
||||
CheckConstraint(
|
||||
"collection_mode IN ('deterministic_context', 'llm_extraction')",
|
||||
"collection_mode IN ('llm_extraction')",
|
||||
name='ck_shipping_order_fields_collection_mode',
|
||||
),
|
||||
CheckConstraint(
|
||||
@@ -91,24 +88,44 @@ class ShippingOrderField(Base):
|
||||
name='ck_shipping_order_fields_value_type',
|
||||
),
|
||||
CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_order_fields_status'),
|
||||
Index('ix_shipping_order_fields_schema_scope', 'schema_id', 'scope'),
|
||||
CheckConstraint(
|
||||
"asset_kind IN ('system_standard', 'extension')",
|
||||
name='ck_shipping_order_fields_asset_kind',
|
||||
),
|
||||
CheckConstraint(
|
||||
"storage_mode IN ('typed_column', 'json_only')",
|
||||
name='ck_shipping_order_fields_storage_mode',
|
||||
),
|
||||
Index('ix_shipping_order_fields_scope_status', 'scope', 'status'),
|
||||
Index('ix_shipping_order_fields_asset_kind', 'asset_kind'),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_uuid)
|
||||
schema_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=False)
|
||||
field_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
scope: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
value_type: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
field_category: Mapped[str] = mapped_column(String(32), nullable=False, default=_default_field_category)
|
||||
collection_mode: Mapped[str] = mapped_column(String(32), nullable=False, default='llm_extraction')
|
||||
asset_kind: Mapped[str] = mapped_column(String(32), nullable=False, default='extension', server_default='extension')
|
||||
storage_mode: Mapped[str] = mapped_column(String(32), nullable=False, default='json_only', server_default='json_only')
|
||||
storage_column: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
semantic_description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
display_name_default: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
fulfillment_role: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
display_sequence: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
|
||||
published_once: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
|
||||
retired_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
retired_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
restored_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
restored_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
schema: Mapped['ShippingOrderSchema'] = relationship(back_populates='fields')
|
||||
|
||||
ShippingFieldAsset = ShippingOrderField
|
||||
|
||||
|
||||
class ShippingOrderSchemaVersion(Base):
|
||||
@@ -152,13 +169,17 @@ class ShippingOrderSchemaVersion(Base):
|
||||
|
||||
|
||||
class ShippingOrderSchemaAuditEvent(Base):
|
||||
"""订单 Schema 配置的追加式审计事件;保存操作前后快照且不提供修改入口。"""
|
||||
"""字段资产与 Schema 配置的追加式审计事件;不提供修改入口。"""
|
||||
|
||||
__tablename__ = 'shipping_order_schema_audit_events'
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"event_type IN ('draft_created', 'draft_saved', 'published', 'draft_deleted', 'cloned', "
|
||||
"'field_saved', 'field_retired', 'field_deleted')",
|
||||
"event_type IN ("
|
||||
"'draft_created', 'draft_saved', 'published', 'draft_deleted', 'cloned', "
|
||||
"'field_saved', 'field_retired', 'field_restored', "
|
||||
"'extension_created', 'extension_updated', 'extension_retired', 'extension_restored', "
|
||||
"'family_created', 'field_adopted', 'field_unadopted', 'publish_blocked'"
|
||||
")",
|
||||
name='ck_shipping_order_schema_audit_event_type',
|
||||
),
|
||||
Index('ix_shipping_order_schema_audit_version_created', 'version_id', 'created_at'),
|
||||
@@ -166,7 +187,8 @@ class ShippingOrderSchemaAuditEvent(Base):
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schema_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=False)
|
||||
schema_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=True)
|
||||
field_id: Mapped[Optional[str]] = mapped_column(String(36), nullable=True)
|
||||
version_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_schema_versions.id', ondelete='SET NULL'), nullable=True
|
||||
)
|
||||
@@ -179,6 +201,7 @@ class ShippingOrderSchemaAuditEvent(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
|
||||
class ShippingOrderExtraction(Base):
|
||||
"""一次订单解析审计;锁定 Schema 和输入快照,承载 LLM 原始结果及最终状态。"""
|
||||
|
||||
@@ -250,7 +273,7 @@ class ShippingOrderFieldObservation(Base):
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
|
||||
line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True)
|
||||
field_id: Mapped[str] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=False)
|
||||
field_id: Mapped[str] = mapped_column(String(36), nullable=False) # 软引用:历史 Run 可保留孤儿 field_id
|
||||
source_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_documents.id'), nullable=True)
|
||||
source_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
extractor: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
@@ -288,7 +311,7 @@ class ShippingOrderFieldDecision(Base):
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
|
||||
line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True)
|
||||
field_id: Mapped[str] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=False)
|
||||
field_id: Mapped[str] = mapped_column(String(36), nullable=False) # 软引用:历史 Run 可保留孤儿 field_id
|
||||
decision_status: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
selected_observation_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_field_observations.id'), nullable=True
|
||||
@@ -321,7 +344,7 @@ class ShippingOrderFieldValue(Base):
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
|
||||
line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True)
|
||||
field_id: Mapped[str] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=False)
|
||||
field_id: Mapped[str] = mapped_column(String(36), nullable=False) # 软引用:历史 Run 可保留孤儿 field_id
|
||||
value_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
value_decimal: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
|
||||
value_integer: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/candidate_service.py
|
||||
|
||||
用途:提供订单候选的用户态查询、选择与重复决策能力。
|
||||
用途:提供订单候选的用户态查询、选择与重复决策能力;含 STP 严格建单门禁。
|
||||
依赖:ShippingNoticeCandidate/Document/Intake、duplicate_detection、business_fingerprint。
|
||||
逻辑:workspace API 调用本模块;所有写操作锁定 Candidate,并在字段变化后重算双指纹和重复状态。
|
||||
逻辑:workspace API 调用本模块;所有写操作锁定 Candidate,并在字段变化后重算双指纹和重复状态;
|
||||
仅严格门禁通过的 Candidate 可物化 Task(缺字段/低置信/缺证据/重复冲突 → 拒绝)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,10 +21,55 @@ from app.services.shipping_notice.duplicate_detection import apply_duplicate_res
|
||||
from app.services.shipping_notice.intake_service import can_force_create_shipping_duplicate
|
||||
|
||||
_ACTIONS = frozenset({'open_existing', 'create_revision', 'force_create'})
|
||||
_STP_DUPLICATE_OK = frozenset({'none', 'unchecked'})
|
||||
|
||||
|
||||
def evaluate_candidate_stp_gate(candidate: ShippingNoticeCandidate) -> tuple[bool, list[str]]:
|
||||
"""
|
||||
评估 Candidate 是否通过 STP 严格建单门禁(不抛异常)。
|
||||
|
||||
核心逻辑:仅对 automatic 接受态施加严格门禁(缺字段、阻断冲突、低置信、缺证据、
|
||||
未解决重复)。人工复核确认(acceptance_mode=manual)不走 STP 直通门禁。
|
||||
|
||||
Args:
|
||||
candidate: 待评估订单候选。
|
||||
|
||||
Returns:
|
||||
(是否通过, 失败原因码列表)。
|
||||
"""
|
||||
if str(candidate.acceptance_mode or '') != 'automatic':
|
||||
return True, []
|
||||
reasons: list[str] = []
|
||||
if str(candidate.validation_status or '') != 'ready':
|
||||
reasons.append('incomplete_fields')
|
||||
if candidate.conflicts_json:
|
||||
reasons.append('blocking_conflict')
|
||||
missing = list(candidate.missing_fields_json or [])
|
||||
if missing:
|
||||
reasons.append('incomplete_fields')
|
||||
evidence = candidate.evidence_json
|
||||
if evidence is None or (isinstance(evidence, list) and len(evidence) == 0):
|
||||
reasons.append('missing_evidence')
|
||||
try:
|
||||
confidence = float(candidate.confidence) if candidate.confidence is not None else None
|
||||
except (TypeError, ValueError):
|
||||
confidence = None
|
||||
if confidence is not None and confidence < 0.85:
|
||||
reasons.append('low_confidence')
|
||||
dup_status = str(candidate.duplicate_status or 'unchecked')
|
||||
if dup_status not in _STP_DUPLICATE_OK:
|
||||
if str(candidate.duplicate_resolution or '') != 'open_existing':
|
||||
reasons.append('duplicate_conflict')
|
||||
return not reasons, sorted(set(reasons))
|
||||
|
||||
|
||||
def ensure_candidate_fulfillment_ready(candidate: ShippingNoticeCandidate) -> None:
|
||||
"""统一履约门禁:只有已接受、当前且无阻断问题的 Candidate 才能建单。"""
|
||||
"""
|
||||
统一履约门禁:已接受、当前、无阻断;automatic 候选额外通过 STP 严格门禁。
|
||||
|
||||
Raises:
|
||||
ConflictError: 接受态、选中态、版本、消费态或 STP 严格门禁失败。
|
||||
"""
|
||||
if str(candidate.candidate_status or '') != 'accepted':
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_ACCEPTANCE_REQUIRED',
|
||||
@@ -40,6 +86,14 @@ def ensure_candidate_fulfillment_ready(candidate: ShippingNoticeCandidate) -> No
|
||||
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
||||
message='订单候选仍有字段冲突或未完成审核',
|
||||
)
|
||||
# [STEP] STP 严格门禁仅约束自动直通;人工确认建单已由复核草稿校验背书。
|
||||
passed, reason_codes = evaluate_candidate_stp_gate(candidate)
|
||||
if not passed:
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_STP_GATE_FAILED',
|
||||
message='订单候选未通过直通建单严格门禁',
|
||||
details={'reason_codes': reason_codes},
|
||||
)
|
||||
|
||||
|
||||
def _candidate_for_user(candidate_no: str, user_id: int, *, lock: bool = False) -> tuple[ShippingNoticeCandidate, ShippingNoticeIntake, ShippingNoticeDocument]:
|
||||
|
||||
@@ -16,7 +16,6 @@ from app.services.chat.action_schema import TurnEvent
|
||||
from app.services.chat.turn_context import TurnContext
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.decision_workflow import submit_decision
|
||||
from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref, get_task_for_user
|
||||
from app.services.shipping_notice.shipping_turn_context import resolve_shipping_task_no
|
||||
from app.services.shipping_notice.shipping_turn_helpers import (
|
||||
@@ -48,6 +47,24 @@ def _require_task(ctx: TurnContext):
|
||||
return task
|
||||
|
||||
|
||||
_CHAT_FULFILLMENT_WRITE_DISABLED_MSG = (
|
||||
"该操作已迁移至工作台「我的待办」任务处理页,请从侧栏进入任务处理后再操作。"
|
||||
)
|
||||
_CHAT_FULFILLMENT_WRITE_DISABLED_CODE = "SHIPPING.CHAT_FULFILLMENT_WRITE_DISABLED"
|
||||
|
||||
|
||||
def _reject_chat_fulfillment_write() -> None:
|
||||
"""
|
||||
拒绝 Chat Turn 履约写路径,引导用户改走任务工作台。
|
||||
|
||||
核心逻辑:STP 验收要求货代上传、Excel 生成、库存匹配等写操作仅在工作台执行。
|
||||
"""
|
||||
raise ValidationError(
|
||||
_CHAT_FULFILLMENT_WRITE_DISABLED_MSG,
|
||||
code=_CHAT_FULFILLMENT_WRITE_DISABLED_CODE,
|
||||
)
|
||||
|
||||
|
||||
def _format_decision_message(decision: str, result: dict[str, Any], task_no: str) -> str:
|
||||
"""对齐前端 shippingDecisionFormat.ts 的助手摘要格式。"""
|
||||
lines = [_tool_result_message(result) or "操作已完成。"]
|
||||
@@ -248,16 +265,10 @@ class ShippingGenerateExcelAction:
|
||||
action_type = "shipping.generate_excel"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
yield TurnEvent(event="step.started", data={"step_id": "generate_excel", "label": "生成发货 Excel..."})
|
||||
result = shipping_tools.generate_excel({"task_id": task.task_no, "event_source": "chat_turn"})
|
||||
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
|
||||
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "generate_excel failed")
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield _shipping_ui_state_event(refreshed)
|
||||
content = "\n".join(filter(None, [_tool_result_message(result), f"任务编号:{task.task_no}"]))
|
||||
yield TurnEvent(event="message.completed", data={"content": content, "message_type": "text"})
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "generate_excel"})
|
||||
_require_task(ctx)
|
||||
_reject_chat_fulfillment_write()
|
||||
return
|
||||
yield # pragma: no cover — satisfies Generator type; unreachable after reject
|
||||
|
||||
|
||||
class ShippingFreezeOrderAction:
|
||||
@@ -300,48 +311,20 @@ class ShippingRetryUploadAction:
|
||||
action_type = "shipping.retry_upload"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
yield TurnEvent(event="step.started", data={"step_id": "retry_upload", "label": "重试上传货代..."})
|
||||
result = shipping_tools.upload_to_freight({
|
||||
"task_id": task.task_no,
|
||||
"mode": "retry_upload",
|
||||
"event_source": "chat_turn",
|
||||
})
|
||||
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
|
||||
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "retry_upload failed")
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield _shipping_ui_state_event(refreshed)
|
||||
content = _tool_result_message(result) or "已触发重试上传。"
|
||||
yield TurnEvent(event="message.completed", data={"content": content, "message_type": "text"})
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "retry_upload"})
|
||||
_require_task(ctx)
|
||||
_reject_chat_fulfillment_write()
|
||||
return
|
||||
yield # pragma: no cover — satisfies Generator type; unreachable after reject
|
||||
|
||||
|
||||
class ShippingMatchInventoryAction:
|
||||
action_type = "shipping.match_inventory"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
yield TurnEvent(event="step.started", data={"step_id": "match_inventory", "label": "匹配库存..."})
|
||||
result = shipping_tools.match_inventory({
|
||||
"task_id": task.task_no,
|
||||
AUTO_CHAIN_FALLBACK: True,
|
||||
"event_source": "chat_turn",
|
||||
})
|
||||
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
|
||||
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "match_inventory failed")
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield _shipping_ui_state_event(refreshed)
|
||||
payload = _match_result_payload(task.task_no, result)
|
||||
content = _tool_result_message(result) or "库存匹配已完成。"
|
||||
yield TurnEvent(
|
||||
event="message.completed",
|
||||
data={
|
||||
"content": content,
|
||||
"message_type": "shipping-match-result",
|
||||
"payload": payload,
|
||||
},
|
||||
)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "match_inventory"})
|
||||
_require_task(ctx)
|
||||
_reject_chat_fulfillment_write()
|
||||
return
|
||||
yield # pragma: no cover — satisfies Generator type; unreachable after reject
|
||||
|
||||
|
||||
class ShippingConfirmInventorySourceAction:
|
||||
@@ -384,30 +367,9 @@ class ShippingMarkManualUploadedAction:
|
||||
evidence_asset_no = str(payload.get("evidence_asset_no") or "").strip()
|
||||
if not evidence_asset_no:
|
||||
raise ValidationError("evidence_asset_no is required", code="SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED")
|
||||
yield TurnEvent(event="step.started", data={"step_id": "mark_manual_uploaded", "label": "确认手工上传..."})
|
||||
result = shipping_tools.upload_to_freight({
|
||||
"task_id": task.task_no,
|
||||
"mode": "manual_confirm",
|
||||
"event_source": "chat_turn",
|
||||
"operator_id": int(ctx.user_id),
|
||||
"evidence_asset_no": evidence_asset_no,
|
||||
"artifact_id": payload.get("artifact_id"),
|
||||
"freight_ref_no": str(payload.get("freight_ref_no") or "").strip(),
|
||||
})
|
||||
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
|
||||
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "mark_manual_uploaded failed")
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield _shipping_ui_state_event(refreshed)
|
||||
content = _tool_result_message(result) or f"好的,任务 {task.task_no} 已确认完成,无需再处理。"
|
||||
yield TurnEvent(
|
||||
event="message.completed",
|
||||
data={
|
||||
"content": content,
|
||||
"message_type": "text",
|
||||
"payload": {"shipping_actions_used": True},
|
||||
},
|
||||
)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "mark_manual_uploaded"})
|
||||
_reject_chat_fulfillment_write()
|
||||
return
|
||||
yield # pragma: no cover — satisfies Generator type; unreachable after reject
|
||||
|
||||
|
||||
_HANDLERS = (
|
||||
|
||||
@@ -17,7 +17,7 @@ from flask import current_app
|
||||
from sqlalchemy import and_, func, or_, update
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import ShippingDocumentLayoutVersion, ShippingNoticeDocument
|
||||
from app.models import ShippingDocumentLayoutVersion, ShippingNoticeDocument, ShippingNoticeIntake
|
||||
|
||||
|
||||
LAYOUT_PARSER_NAME = 'mineru'
|
||||
@@ -156,6 +156,27 @@ def schedule_layout_version(
|
||||
source_hash = str(document.content_hash or '').strip().lower()
|
||||
if len(source_hash) != 64:
|
||||
return None
|
||||
# Identical files from the same owner reuse a completed layout rather than waiting for MinerU again.
|
||||
owner_id = db.session.query(ShippingNoticeIntake.user_id).filter(
|
||||
ShippingNoticeIntake.id == document.intake_id,
|
||||
).scalar()
|
||||
if not force:
|
||||
reusable_from_owner = (
|
||||
ShippingDocumentLayoutVersion.query
|
||||
.join(ShippingNoticeDocument, ShippingNoticeDocument.id == ShippingDocumentLayoutVersion.document_id)
|
||||
.join(ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeDocument.intake_id)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == owner_id,
|
||||
ShippingNoticeDocument.content_hash == source_hash,
|
||||
ShippingDocumentLayoutVersion.parser_key == current_layout_parser_key(),
|
||||
ShippingDocumentLayoutVersion.status.in_(tuple(CURRENT_LAYOUT_STATUSES)),
|
||||
)
|
||||
.order_by(ShippingDocumentLayoutVersion.finished_at.desc(), ShippingDocumentLayoutVersion.id.desc())
|
||||
.first()
|
||||
)
|
||||
if reusable_from_owner is not None:
|
||||
document.current_layout_version_id = reusable_from_owner.id
|
||||
return reusable_from_owner
|
||||
active = ShippingDocumentLayoutVersion.query.filter(
|
||||
ShippingDocumentLayoutVersion.document_id == int(document.id),
|
||||
ShippingDocumentLayoutVersion.status.in_({'queued', 'running'}),
|
||||
|
||||
@@ -0,0 +1,625 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/field_asset_service.py
|
||||
|
||||
用途:货代字段资产治理——列表/详情、扩展创建与弃用恢复、标准只读校验、审计写入。
|
||||
依赖:ShippingOrderField、standard_field_registry、ShippingOrderSchemaAuditEvent、db。
|
||||
逻辑:由 admin 字段资产 API 与 Schema 采用校验调用;禁止物理删除与标准字段弃用;
|
||||
禁止将 mail/context 类编码登记为订单字段资产。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models.shipping_order_schema import ShippingOrderField, ShippingOrderSchemaAuditEvent
|
||||
from app.services.shipping_notice.standard_field_registry import (
|
||||
STANDARD_FIELD_SPECS,
|
||||
assert_registry_consistent,
|
||||
get_standard_field,
|
||||
is_standard_field_code,
|
||||
standard_field_codes,
|
||||
)
|
||||
|
||||
FIELD_CODE_RE = re.compile(r'^[a-z][a-z0-9_]*$')
|
||||
FIELD_TYPES = frozenset({'string', 'decimal', 'integer', 'date', 'boolean', 'enum'})
|
||||
FORBIDDEN_CONTEXT_CODES = frozenset({
|
||||
'sender_email', 'sender_domain', 'from_email', 'from_domain',
|
||||
'mail_from', 'mail_domain',
|
||||
})
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
"""将可空时间转换为 API ISO 字符串。"""
|
||||
return value.isoformat() if value else None
|
||||
|
||||
|
||||
def _append_audit(
|
||||
*,
|
||||
event_type: str,
|
||||
actor_id: int | None,
|
||||
request_id: str | None,
|
||||
field_id: str | None,
|
||||
schema_id: int | None = None,
|
||||
before: dict[str, Any] | None = None,
|
||||
after: dict[str, Any] | None = None,
|
||||
summary: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""写入追加式字段资产审计事件。"""
|
||||
db.session.add(ShippingOrderSchemaAuditEvent(
|
||||
schema_id=schema_id,
|
||||
field_id=field_id,
|
||||
event_type=event_type,
|
||||
actor_id=actor_id,
|
||||
before_snapshot_json=before,
|
||||
after_snapshot_json=after,
|
||||
change_summary_json=summary or {},
|
||||
request_id=request_id,
|
||||
))
|
||||
|
||||
|
||||
def asset_payload(field: ShippingOrderField, *, adoption_index: dict[str, list[dict[str, Any]]] | None = None) -> dict[str, Any]:
|
||||
"""序列化字段资产身份与治理元数据,不含版本级识别规则。"""
|
||||
storage = _storage_descriptor(field)
|
||||
adoptions = list((adoption_index or {}).get(field.id) or [])
|
||||
return {
|
||||
'id': field.id,
|
||||
'field_code': field.field_code,
|
||||
'scope': field.scope,
|
||||
'value_type': field.value_type,
|
||||
'field_category': field.field_category,
|
||||
'collection_mode': field.collection_mode,
|
||||
'asset_kind': field.asset_kind,
|
||||
'storage_mode': field.storage_mode,
|
||||
'storage_column': field.storage_column,
|
||||
'storage_table': storage['storage_table'],
|
||||
'storage_path': storage['storage_path'],
|
||||
'storage_kind': storage['storage_kind'],
|
||||
'semantic_description': field.semantic_description,
|
||||
'display_name_default': field.display_name_default,
|
||||
'fulfillment_role': field.fulfillment_role,
|
||||
'display_sequence': int(field.display_sequence or 0),
|
||||
'status': field.status,
|
||||
'published_once': bool(field.published_once),
|
||||
'retired_reason': field.retired_reason,
|
||||
'retired_at': _iso(field.retired_at),
|
||||
'restored_at': _iso(field.restored_at),
|
||||
'created_at': _iso(field.created_at),
|
||||
'updated_at': _iso(field.updated_at),
|
||||
'adoption_summary': {
|
||||
'total': len(adoptions),
|
||||
'published': sum(1 for item in adoptions if item.get('status') == 'published'),
|
||||
'draft': sum(1 for item in adoptions if item.get('status') == 'draft'),
|
||||
'retired': sum(1 for item in adoptions if item.get('status') == 'retired'),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _build_adoption_index() -> dict[str, list[dict[str, Any]]]:
|
||||
"""一次扫描 Schema 版本,生成 field_id → 采用摘要索引,供列表页展示。"""
|
||||
from app.models.shipping_order_schema import ShippingOrderSchemaVersion
|
||||
|
||||
index: dict[str, list[dict[str, Any]]] = {}
|
||||
for version in ShippingOrderSchemaVersion.query.filter(
|
||||
ShippingOrderSchemaVersion.status.in_(['draft', 'published', 'retired']),
|
||||
).all():
|
||||
family = version.schema
|
||||
for item in (version.definition_json or {}).get('fields') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
field_id = str(item.get('field_id') or '')
|
||||
if not field_id:
|
||||
continue
|
||||
index.setdefault(field_id, []).append({
|
||||
'schema_version_id': version.id,
|
||||
'version': version.version,
|
||||
'status': version.status,
|
||||
'schema_id': version.schema_id,
|
||||
'schema_code': family.schema_code if family is not None else None,
|
||||
})
|
||||
return index
|
||||
|
||||
|
||||
def _storage_descriptor(field: ShippingOrderField) -> dict[str, str]:
|
||||
"""
|
||||
生成管理员可读的存储落点说明。
|
||||
|
||||
核心逻辑:typed_column → Snapshot 固定列;标准 json_only → Snapshot JSON(系统预置);
|
||||
扩展 → Snapshot JSON(扩展)。与「全部标准都是物理列」不同:仅投影子集为 typed。
|
||||
"""
|
||||
if field.storage_mode == 'typed_column' and field.storage_column:
|
||||
table = (
|
||||
'shipping_order_snapshots'
|
||||
if field.scope == 'header'
|
||||
else 'shipping_order_snapshot_lines'
|
||||
)
|
||||
return {
|
||||
'storage_kind': 'typed_column',
|
||||
'storage_table': table,
|
||||
'storage_path': f'{table}.{field.storage_column}',
|
||||
}
|
||||
json_column = 'header_values_json' if field.scope == 'header' else 'field_values_json'
|
||||
table = (
|
||||
'shipping_order_snapshots'
|
||||
if field.scope == 'header'
|
||||
else 'shipping_order_snapshot_lines'
|
||||
)
|
||||
kind = 'standard_json' if field.asset_kind == 'system_standard' else 'extension_json'
|
||||
return {
|
||||
'storage_kind': kind,
|
||||
'storage_table': table,
|
||||
'storage_path': f'{table}.{json_column}[{field.field_code}]',
|
||||
}
|
||||
|
||||
|
||||
def ensure_standard_assets_seeded(*, actor_id: int | None = None) -> int:
|
||||
"""
|
||||
确保 57 项标准资产已落库;缺失则补齐;已存在则强制校验锁定属性与注册表一致。
|
||||
|
||||
Returns:
|
||||
本次新插入的标准字段数量。
|
||||
|
||||
Raises:
|
||||
ConflictError: 库中标准字段的 scope/type/storage/履约角色与注册表不一致。
|
||||
"""
|
||||
assert_registry_consistent()
|
||||
existing = {
|
||||
row.field_code: row
|
||||
for row in ShippingOrderField.query.filter_by(asset_kind='system_standard').all()
|
||||
}
|
||||
inserted = 0
|
||||
for sequence, spec in enumerate(STANDARD_FIELD_SPECS.values(), start=1):
|
||||
row = existing.get(spec.field_code)
|
||||
if row is not None:
|
||||
# [STEP] 注册表是唯一事实:已存在行必须与锁定属性一致,禁止静默沿用脏数据。
|
||||
mismatches: list[str] = []
|
||||
if row.scope != spec.scope:
|
||||
mismatches.append(f'scope={row.scope!r}!={spec.scope!r}')
|
||||
if row.value_type != spec.value_type:
|
||||
mismatches.append(f'value_type={row.value_type!r}!={spec.value_type!r}')
|
||||
if row.storage_mode != spec.storage_mode:
|
||||
mismatches.append(f'storage_mode={row.storage_mode!r}!={spec.storage_mode!r}')
|
||||
if (row.storage_column or None) != (spec.storage_column or None):
|
||||
mismatches.append(f'storage_column={row.storage_column!r}!={spec.storage_column!r}')
|
||||
if (row.fulfillment_role or None) != (spec.fulfillment_role or None):
|
||||
mismatches.append(f'fulfillment_role={row.fulfillment_role!r}!={spec.fulfillment_role!r}')
|
||||
if row.status != 'active':
|
||||
mismatches.append(f'status={row.status!r}!=active')
|
||||
if mismatches:
|
||||
raise ConflictError(
|
||||
f'Standard field {spec.field_code} diverges from registry',
|
||||
code='SHIPPING.FIELD_ASSET_STANDARD_DRIFT',
|
||||
details={'field_code': spec.field_code, 'mismatches': mismatches},
|
||||
)
|
||||
# 显示名/语义允许由运维同步刷新为注册表文案(非身份属性)。
|
||||
row.display_name_default = spec.display_name
|
||||
row.semantic_description = spec.semantic_description
|
||||
row.display_sequence = sequence
|
||||
continue
|
||||
db.session.add(ShippingOrderField(
|
||||
field_code=spec.field_code,
|
||||
scope=spec.scope,
|
||||
value_type=spec.value_type,
|
||||
field_category='order_header' if spec.scope == 'header' else 'order_line',
|
||||
collection_mode='llm_extraction',
|
||||
asset_kind='system_standard',
|
||||
storage_mode=spec.storage_mode,
|
||||
storage_column=spec.storage_column,
|
||||
semantic_description=spec.semantic_description,
|
||||
display_name_default=spec.display_name,
|
||||
fulfillment_role=spec.fulfillment_role,
|
||||
display_sequence=sequence,
|
||||
status='active',
|
||||
created_by_id=actor_id,
|
||||
))
|
||||
inserted += 1
|
||||
if inserted:
|
||||
db.session.flush()
|
||||
return inserted
|
||||
|
||||
|
||||
def list_assets(
|
||||
*,
|
||||
q: str | None = None,
|
||||
asset_kind: str | None = None,
|
||||
status: str | None = None,
|
||||
scope: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""列出字段资产,支持搜索与筛选。"""
|
||||
ensure_standard_assets_seeded()
|
||||
query = ShippingOrderField.query
|
||||
if asset_kind in {'system_standard', 'extension'}:
|
||||
query = query.filter_by(asset_kind=asset_kind)
|
||||
if status in {'active', 'retired'}:
|
||||
query = query.filter_by(status=status)
|
||||
if scope in {'header', 'line'}:
|
||||
query = query.filter_by(scope=scope)
|
||||
needle = str(q or '').strip().lower()
|
||||
if needle:
|
||||
like = f'%{needle}%'
|
||||
query = query.filter(or_(
|
||||
func.lower(ShippingOrderField.field_code).like(like),
|
||||
func.lower(func.coalesce(ShippingOrderField.display_name_default, '')).like(like),
|
||||
func.lower(func.coalesce(ShippingOrderField.semantic_description, '')).like(like),
|
||||
))
|
||||
rows = query.order_by(
|
||||
ShippingOrderField.asset_kind.desc(),
|
||||
ShippingOrderField.display_sequence,
|
||||
ShippingOrderField.field_code,
|
||||
).all()
|
||||
adoption_index = _build_adoption_index()
|
||||
return {
|
||||
'items': [asset_payload(item, adoption_index=adoption_index) for item in rows],
|
||||
'standard_count': sum(1 for item in rows if item.asset_kind == 'system_standard'),
|
||||
'extension_count': sum(1 for item in rows if item.asset_kind == 'extension'),
|
||||
'locked_standard_codes': sorted(standard_field_codes()),
|
||||
}
|
||||
|
||||
|
||||
def get_asset(field_id: str) -> dict[str, Any]:
|
||||
"""读取单个字段资产详情,并附带跨 Schema 族的采用摘要(published/draft/retired)。"""
|
||||
from app.models.shipping_order_schema import ShippingOrderSchemaVersion
|
||||
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None:
|
||||
raise NotFoundError('Field asset not found', code='SHIPPING.FIELD_ASSET_NOT_FOUND')
|
||||
payload = asset_payload(field)
|
||||
adoptions: list[dict[str, Any]] = []
|
||||
for version in ShippingOrderSchemaVersion.query.filter(
|
||||
ShippingOrderSchemaVersion.status.in_(['draft', 'published', 'retired']),
|
||||
).order_by(ShippingOrderSchemaVersion.version.desc()).all():
|
||||
fields = (version.definition_json or {}).get('fields') or []
|
||||
if any(str(item.get('field_id') or '') == field_id for item in fields if isinstance(item, dict)):
|
||||
family = version.schema
|
||||
adoptions.append({
|
||||
'schema_version_id': version.id,
|
||||
'version': version.version,
|
||||
'status': version.status,
|
||||
'schema_id': version.schema_id,
|
||||
'schema_code': family.schema_code if family is not None else None,
|
||||
'schema_display_name': family.display_name if family is not None else None,
|
||||
})
|
||||
payload['adoptions'] = adoptions
|
||||
return payload
|
||||
|
||||
|
||||
def create_extension(
|
||||
data: dict[str, Any], *, actor_id: int | None, request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
新建扩展字段资产。
|
||||
|
||||
Raises:
|
||||
ValidationError: 编码非法、撞标准码、伪造 typed 映射或上下文编码。
|
||||
ConflictError: field_code 冲突。
|
||||
"""
|
||||
code = str(data.get('field_code') or '').strip().lower()
|
||||
scope = str(data.get('scope') or '').strip().lower()
|
||||
value_type = str(data.get('value_type') or '').strip().lower()
|
||||
display_name = str(data.get('display_name') or data.get('display_name_default') or '').strip()
|
||||
semantic = str(data.get('semantic_description') or '').strip() or None
|
||||
if not FIELD_CODE_RE.fullmatch(code):
|
||||
raise ValidationError('field_code must use lower snake_case', code='SHIPPING.FIELD_ASSET_INVALID')
|
||||
if code in FORBIDDEN_CONTEXT_CODES or code.startswith('mail_') or code.startswith('sender_'):
|
||||
raise ValidationError(
|
||||
'Context/mail identifiers cannot be registered as order field assets',
|
||||
code='SHIPPING.FIELD_ASSET_CONTEXT_FORBIDDEN',
|
||||
)
|
||||
if is_standard_field_code(code):
|
||||
raise ValidationError(
|
||||
'Cannot create extension that collides with a system standard field_code',
|
||||
code='SHIPPING.FIELD_ASSET_STANDARD_CODE',
|
||||
)
|
||||
if scope not in {'header', 'line'} or value_type not in FIELD_TYPES:
|
||||
raise ValidationError('scope or value_type is invalid', code='SHIPPING.FIELD_ASSET_INVALID')
|
||||
if not display_name:
|
||||
raise ValidationError('display_name is required', code='SHIPPING.FIELD_ASSET_INVALID')
|
||||
if data.get('storage_mode') == 'typed_column' or data.get('storage_column'):
|
||||
raise ValidationError(
|
||||
'Extension fields cannot map to typed snapshot columns',
|
||||
code='SHIPPING.FIELD_ASSET_TYPED_FORBIDDEN',
|
||||
)
|
||||
next_sequence = (db.session.query(func.max(ShippingOrderField.display_sequence)).scalar() or 0) + 1
|
||||
field = ShippingOrderField(
|
||||
field_code=code,
|
||||
scope=scope,
|
||||
value_type=value_type,
|
||||
field_category='order_header' if scope == 'header' else 'order_line',
|
||||
collection_mode='llm_extraction',
|
||||
asset_kind='extension',
|
||||
storage_mode='json_only',
|
||||
storage_column=None,
|
||||
semantic_description=semantic,
|
||||
display_name_default=display_name,
|
||||
display_sequence=next_sequence,
|
||||
status='active',
|
||||
created_by_id=actor_id,
|
||||
)
|
||||
db.session.add(field)
|
||||
try:
|
||||
db.session.flush()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('field_code already exists', code='SHIPPING.FIELD_ASSET_CONFLICT') from exc
|
||||
payload = asset_payload(field)
|
||||
_append_audit(
|
||||
event_type='extension_created',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
field_id=field.id,
|
||||
after=payload,
|
||||
summary={'field_code': code, 'scope': scope, 'value_type': value_type},
|
||||
)
|
||||
db.session.commit()
|
||||
return payload
|
||||
|
||||
|
||||
def update_extension(
|
||||
field_id: str,
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
actor_id: int | None,
|
||||
request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
更新扩展字段的显示属性;不可改 scope/type/code。
|
||||
|
||||
核心逻辑:要求 expected_updated_at 与当前 updated_at 一致,避免并发覆盖。
|
||||
"""
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None:
|
||||
raise NotFoundError('Field asset not found', code='SHIPPING.FIELD_ASSET_NOT_FOUND')
|
||||
if field.asset_kind != 'extension':
|
||||
raise ConflictError('System standard fields are read-only', code='SHIPPING.FIELD_ASSET_STANDARD_READONLY')
|
||||
expected = data.get('expected_updated_at')
|
||||
if expected is None or not str(expected).strip():
|
||||
raise ValidationError(
|
||||
'expected_updated_at is required',
|
||||
code='SHIPPING.FIELD_ASSET_LOCK_REQUIRED',
|
||||
details={'field': 'expected_updated_at'},
|
||||
)
|
||||
current = _iso(field.updated_at)
|
||||
if str(expected).strip() != current:
|
||||
raise ConflictError(
|
||||
'Field asset was changed by another user',
|
||||
code='SHIPPING.FIELD_ASSET_VERSION_CONFLICT',
|
||||
details={'expected_updated_at': expected, 'current_updated_at': current},
|
||||
)
|
||||
before = asset_payload(field)
|
||||
if 'display_name' in data or 'display_name_default' in data:
|
||||
name = str(data.get('display_name') or data.get('display_name_default') or '').strip()
|
||||
if not name:
|
||||
raise ValidationError('display_name is required', code='SHIPPING.FIELD_ASSET_INVALID')
|
||||
field.display_name_default = name
|
||||
if 'semantic_description' in data:
|
||||
field.semantic_description = str(data.get('semantic_description') or '').strip() or None
|
||||
for locked in ('field_code', 'scope', 'value_type', 'storage_mode', 'storage_column', 'asset_kind'):
|
||||
if locked in data and str(data.get(locked)) not in {None, '', getattr(field, locked)}:
|
||||
raise ConflictError(
|
||||
f'{locked} is immutable after creation',
|
||||
code='SHIPPING.FIELD_ASSET_IMMUTABLE',
|
||||
)
|
||||
field.updated_at = datetime.utcnow()
|
||||
after = asset_payload(field)
|
||||
_append_audit(
|
||||
event_type='extension_updated',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
field_id=field.id,
|
||||
before=before,
|
||||
after=after,
|
||||
summary={'field_code': field.field_code},
|
||||
)
|
||||
db.session.commit()
|
||||
return after
|
||||
|
||||
|
||||
def retire_extension(
|
||||
field_id: str,
|
||||
*,
|
||||
reason: str,
|
||||
actor_id: int | None,
|
||||
request_id: str | None = None,
|
||||
confirm_impact: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
弃用扩展字段;标准字段拒绝。
|
||||
|
||||
核心逻辑:先跑影响分析;存在阻断下游时必须 confirm_impact=True 才允许弃用,
|
||||
并将影响摘要写入审计,满足弃用前可追溯。
|
||||
"""
|
||||
from app.services.shipping_notice.field_impact_analysis import analyze_field_impact
|
||||
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None:
|
||||
raise NotFoundError('Field asset not found', code='SHIPPING.FIELD_ASSET_NOT_FOUND')
|
||||
if field.asset_kind != 'extension':
|
||||
raise ConflictError(
|
||||
'System standard fields cannot be retired; unadopt in Schema instead',
|
||||
code='SHIPPING.FIELD_ASSET_STANDARD_NO_RETIRE',
|
||||
)
|
||||
note = str(reason or '').strip()
|
||||
if not note:
|
||||
raise ValidationError('retire reason is required', code='SHIPPING.FIELD_ASSET_RETIRE_REASON_REQUIRED')
|
||||
if field.status == 'retired':
|
||||
return asset_payload(field)
|
||||
|
||||
impact = analyze_field_impact(field_id)
|
||||
if impact['blocking_items'] and not confirm_impact:
|
||||
raise ConflictError(
|
||||
'Extension field is still referenced by downstream configuration; confirm impact to retire',
|
||||
code='SHIPPING.FIELD_ASSET_RETIRE_IMPACT_CONFIRM_REQUIRED',
|
||||
details=impact,
|
||||
)
|
||||
|
||||
before = asset_payload(field)
|
||||
field.status = 'retired'
|
||||
field.retired_reason = note
|
||||
field.retired_by_id = actor_id
|
||||
field.retired_at = datetime.utcnow()
|
||||
after = asset_payload(field)
|
||||
_append_audit(
|
||||
event_type='extension_retired',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
field_id=field.id,
|
||||
before=before,
|
||||
after=after,
|
||||
summary={
|
||||
'field_code': field.field_code,
|
||||
'reason': note,
|
||||
'confirm_impact': bool(confirm_impact),
|
||||
'blocking_count': impact['blocking_count'],
|
||||
'blocking_kinds': impact['blocking_kinds'],
|
||||
'blocking_items': impact['blocking_items'],
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return after
|
||||
|
||||
|
||||
def restore_extension(
|
||||
field_id: str,
|
||||
*,
|
||||
reason: str,
|
||||
actor_id: int | None,
|
||||
request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""恢复已弃用扩展字段。"""
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None:
|
||||
raise NotFoundError('Field asset not found', code='SHIPPING.FIELD_ASSET_NOT_FOUND')
|
||||
if field.asset_kind != 'extension':
|
||||
raise ConflictError('System standard fields cannot be restored via retire flow', code='SHIPPING.FIELD_ASSET_STANDARD_READONLY')
|
||||
note = str(reason or '').strip()
|
||||
if not note:
|
||||
raise ValidationError('restore reason is required', code='SHIPPING.FIELD_ASSET_RESTORE_REASON_REQUIRED')
|
||||
if field.status == 'active':
|
||||
return asset_payload(field)
|
||||
before = asset_payload(field)
|
||||
field.status = 'active'
|
||||
field.restored_by_id = actor_id
|
||||
field.restored_at = datetime.utcnow()
|
||||
field.retired_reason = None
|
||||
after = asset_payload(field)
|
||||
_append_audit(
|
||||
event_type='extension_restored',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
field_id=field.id,
|
||||
before=before,
|
||||
after=after,
|
||||
summary={'field_code': field.field_code, 'reason': note},
|
||||
)
|
||||
db.session.commit()
|
||||
return after
|
||||
|
||||
|
||||
def require_adoptable_asset(field_id: str) -> ShippingOrderField:
|
||||
"""
|
||||
Schema 草稿采用前校验:资产存在且 active;标准与扩展均可,retired 拒绝。
|
||||
|
||||
Raises:
|
||||
NotFoundError / ConflictError
|
||||
"""
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None:
|
||||
raise NotFoundError('Field asset not found', code='SHIPPING.FIELD_ASSET_NOT_FOUND')
|
||||
if field.status != 'active':
|
||||
raise ConflictError(
|
||||
'Retired field assets cannot be adopted into a new draft',
|
||||
code='SHIPPING.FIELD_ASSET_NOT_ADOPTABLE',
|
||||
)
|
||||
return field
|
||||
|
||||
|
||||
def reorder_assets(
|
||||
data: dict[str, Any], *, actor_id: int | None, request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""保存全局字段资产目录顺序。"""
|
||||
ordered_ids = data.get('field_ids')
|
||||
if not isinstance(ordered_ids, list) or not ordered_ids or len(set(map(str, ordered_ids))) != len(ordered_ids):
|
||||
raise ValidationError('field_ids must be a unique non-empty list', code='SHIPPING.FIELD_ASSET_ORDER_INVALID')
|
||||
fields = ShippingOrderField.query.filter_by(status='active').all()
|
||||
by_id = {field.id: field for field in fields}
|
||||
normalized_ids = [str(field_id) for field_id in ordered_ids]
|
||||
if set(normalized_ids) != set(by_id):
|
||||
raise ValidationError('field_ids must contain all active assets', code='SHIPPING.FIELD_ASSET_ORDER_INVALID')
|
||||
before = [{'field_id': field.id, 'display_sequence': field.display_sequence} for field in fields]
|
||||
for sequence, field_id in enumerate(normalized_ids, start=1):
|
||||
by_id[field_id].display_sequence = sequence
|
||||
_append_audit(
|
||||
event_type='extension_updated',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
field_id=None,
|
||||
before={'fields': before},
|
||||
after={'fields': [
|
||||
{'field_id': field_id, 'display_sequence': index}
|
||||
for index, field_id in enumerate(normalized_ids, start=1)
|
||||
]},
|
||||
summary={'action': 'reorder'},
|
||||
)
|
||||
db.session.commit()
|
||||
return {'items': [asset_payload(by_id[field_id]) for field_id in normalized_ids]}
|
||||
|
||||
|
||||
def forbid_physical_delete() -> None:
|
||||
"""
|
||||
拒绝物理删除字段资产;扩展字段应走 retire,标准字段应取消 Schema 采用。
|
||||
|
||||
Raises:
|
||||
ConflictError: 始终抛出,供 legacy delete API 与 admin DELETE 路由使用。
|
||||
"""
|
||||
raise ConflictError(
|
||||
'Field assets cannot be physically deleted; retire extensions instead',
|
||||
code='SHIPPING.FIELD_ASSET_DELETE_FORBIDDEN',
|
||||
)
|
||||
|
||||
|
||||
def list_asset_audits(field_id: str, *, limit: int = 50) -> dict[str, Any]:
|
||||
"""
|
||||
读取单字段相关审计事件(含 Schema 采用相关事件中带 field_id 的记录)。
|
||||
|
||||
核心逻辑:补充操作人展示名,便于管理端审计时间线追溯。
|
||||
"""
|
||||
from app.models import User
|
||||
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None:
|
||||
raise NotFoundError('Field asset not found', code='SHIPPING.FIELD_ASSET_NOT_FOUND')
|
||||
rows = (
|
||||
ShippingOrderSchemaAuditEvent.query
|
||||
.filter_by(field_id=field_id)
|
||||
.order_by(ShippingOrderSchemaAuditEvent.created_at.desc())
|
||||
.limit(max(1, min(int(limit or 50), 200)))
|
||||
.all()
|
||||
)
|
||||
actor_ids = {row.actor_id for row in rows if row.actor_id}
|
||||
actors = {
|
||||
user.id: (user.real_name or user.username)
|
||||
for user in User.query.filter(User.id.in_(actor_ids)).all()
|
||||
} if actor_ids else {}
|
||||
return {
|
||||
'field_id': field_id,
|
||||
'items': [
|
||||
{
|
||||
'id': row.id,
|
||||
'event_type': row.event_type,
|
||||
'actor_id': row.actor_id,
|
||||
'actor_display_name': actors.get(row.actor_id) if row.actor_id else None,
|
||||
'request_id': row.request_id,
|
||||
'before': row.before_snapshot_json,
|
||||
'after': row.after_snapshot_json,
|
||||
'change_summary': row.change_summary_json or {},
|
||||
'created_at': row.created_at.isoformat() if row.created_at else None,
|
||||
}
|
||||
for row in rows
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/field_impact_analysis.py
|
||||
|
||||
用途:汇总字段资产在下游配置与历史运行中的引用,供弃用提示与 Schema 发布门禁使用。
|
||||
依赖:库存路由/解析档案、文档模板、Excel 模板、履约策略、身份规则、提取观测表。
|
||||
逻辑:由 field_asset_service / order_schema.publish 调用;返回对象级阻断明细
|
||||
(id/名称/版本/状态/引用位置/处理入口),published/draft 配置引用为阻断,
|
||||
已完成 Run 仅作历史只读提示,不阻断发布。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingFulfillmentPolicy,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryRoutingRule,
|
||||
ShippingInventoryRoutingRuleCondition,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderField,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldObservation,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.models.shipping_identity_rule import (
|
||||
ShippingIdentityDefinition,
|
||||
ShippingIdentityRuleSet,
|
||||
)
|
||||
|
||||
|
||||
def _ref(
|
||||
*,
|
||||
kind: str,
|
||||
object_id: str | int,
|
||||
display_name: str,
|
||||
status: str,
|
||||
version: int | str | None = None,
|
||||
reference_path: str,
|
||||
admin_path: str | None = None,
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""组装统一的下游引用对象载荷。"""
|
||||
payload: dict[str, Any] = {
|
||||
'kind': kind,
|
||||
'object_id': object_id,
|
||||
'display_name': display_name,
|
||||
'status': status,
|
||||
'version': version,
|
||||
'reference_path': reference_path,
|
||||
'admin_path': admin_path,
|
||||
}
|
||||
if extra:
|
||||
payload.update(extra)
|
||||
return payload
|
||||
|
||||
|
||||
def _profile_reference_paths(profile: ShippingOrderDocumentProfile, field_id: str) -> list[str]:
|
||||
"""返回文档模板内引用该字段的位置描述列表。"""
|
||||
definition = profile.definition_json or {}
|
||||
paths: list[str] = []
|
||||
for index, rule in enumerate(definition.get('column_rules', []) or []):
|
||||
if not isinstance(rule, dict):
|
||||
continue
|
||||
for target in rule.get('target_fields', []) or []:
|
||||
if isinstance(target, dict) and str(target.get('field_id') or '') == field_id:
|
||||
paths.append(f'column_rules[{index}].target_fields')
|
||||
for table_index, table_region in enumerate(definition.get('table_regions', []) or []):
|
||||
if not isinstance(table_region, dict):
|
||||
continue
|
||||
for layout_kind in ('header_layouts', 'line_layouts'):
|
||||
for layout_index, layout in enumerate(table_region.get(layout_kind) or []):
|
||||
if not isinstance(layout, dict):
|
||||
continue
|
||||
for region_index, field_region in enumerate(layout.get('field_regions', []) or []):
|
||||
if isinstance(field_region, dict) and str(field_region.get('field_id') or '') == field_id:
|
||||
paths.append(
|
||||
f'table_regions[{table_index}].{layout_kind}[{layout_index}]'
|
||||
f'.field_regions[{region_index}]'
|
||||
)
|
||||
return paths
|
||||
|
||||
|
||||
def list_field_runtime_references(field_id: str) -> list[dict[str, Any]]:
|
||||
"""
|
||||
返回仍会阻断配置变更的下游对象明细(draft/published 配置)。
|
||||
|
||||
不含已结束 Extraction/Run;那些只出现在 analyze_field_impact 的 historical 段。
|
||||
"""
|
||||
references: list[dict[str, Any]] = []
|
||||
|
||||
# [STEP 1] 库存路由条件
|
||||
routing_rows = (
|
||||
db.session.query(ShippingInventoryRoutingRuleCondition, ShippingInventoryRoutingRule)
|
||||
.join(ShippingInventoryRoutingRule)
|
||||
.filter(
|
||||
ShippingInventoryRoutingRuleCondition.order_field_id == field_id,
|
||||
ShippingInventoryRoutingRule.status.in_(['draft', 'published']),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for condition, rule in routing_rows:
|
||||
references.append(_ref(
|
||||
kind='inventory_routing_rule',
|
||||
object_id=rule.id,
|
||||
display_name=rule.rule_name or rule.rule_code or f'Rule #{rule.id}',
|
||||
status=rule.status,
|
||||
version=rule.version,
|
||||
reference_path=f'conditions[id={condition.id}].order_field_id',
|
||||
admin_path='/admin/shipping-inventory?section=routing',
|
||||
extra={'rule_code': rule.rule_code},
|
||||
))
|
||||
|
||||
# [STEP 2] 库存解析档案 match_keys
|
||||
for profile in ShippingInventoryParsingProfile.query.filter(
|
||||
ShippingInventoryParsingProfile.status.in_(['draft', 'published']),
|
||||
).all():
|
||||
for index, item in enumerate((profile.definition_json or {}).get('match_keys', []) or []):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if str(item.get('order_field_id') or '') != field_id:
|
||||
continue
|
||||
references.append(_ref(
|
||||
kind='inventory_parsing_profile',
|
||||
object_id=profile.id,
|
||||
display_name=profile.display_name or profile.profile_code,
|
||||
status=profile.status,
|
||||
version=getattr(profile, 'version', None),
|
||||
reference_path=f'definition.match_keys[{index}].order_field_id',
|
||||
admin_path='/admin/shipping-inventory?section=parsing',
|
||||
extra={'profile_code': profile.profile_code},
|
||||
))
|
||||
|
||||
# [STEP 3] 订单文档模板
|
||||
for profile in ShippingOrderDocumentProfile.query.filter(
|
||||
ShippingOrderDocumentProfile.status.in_(['draft', 'published']),
|
||||
).all():
|
||||
paths = _profile_reference_paths(profile, field_id)
|
||||
if not paths:
|
||||
continue
|
||||
code = getattr(profile, 'profile_code', None) or str(profile.id)
|
||||
references.append(_ref(
|
||||
kind='order_document_profile',
|
||||
object_id=profile.id,
|
||||
display_name=getattr(profile, 'display_name', None) or code,
|
||||
status=profile.status,
|
||||
version=getattr(profile, 'version', None),
|
||||
reference_path='; '.join(paths),
|
||||
admin_path=f'/admin/shipping-order-document-profiles/{code}/versions/{getattr(profile, "version", 1)}',
|
||||
extra={'profile_code': code},
|
||||
))
|
||||
|
||||
# [STEP 4] Excel 导出模板 mappings
|
||||
for template in ShippingExcelTemplate.query.filter(
|
||||
ShippingExcelTemplate.status.in_(['draft', 'published']),
|
||||
).all():
|
||||
hit_paths: list[str] = []
|
||||
for index, item in enumerate((template.definition_json or {}).get('mappings', []) or []):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if item.get('source_kind') == 'order_field' and str(item.get('source_key') or '') == field_id:
|
||||
hit_paths.append(f'definition.mappings[{index}].source_key')
|
||||
if not hit_paths:
|
||||
continue
|
||||
references.append(_ref(
|
||||
kind='excel_template',
|
||||
object_id=template.id,
|
||||
display_name=template.display_name or template.template_code,
|
||||
status=template.status,
|
||||
version=template.version,
|
||||
reference_path='; '.join(hit_paths),
|
||||
admin_path='/admin/shipping-inventory?section=excel',
|
||||
extra={'template_code': template.template_code},
|
||||
))
|
||||
|
||||
# [STEP 5] 履约策略 field_bindings
|
||||
for policy in ShippingFulfillmentPolicy.query.filter(
|
||||
ShippingFulfillmentPolicy.status.in_(['draft', 'published']),
|
||||
).all():
|
||||
hit_paths: list[str] = []
|
||||
for index, item in enumerate((policy.definition_json or {}).get('field_bindings', []) or []):
|
||||
if isinstance(item, dict) and str(item.get('field_id') or '') == field_id:
|
||||
role = item.get('role') or item.get('purpose') or index
|
||||
hit_paths.append(f'definition.field_bindings[{index}]({role})')
|
||||
if not hit_paths:
|
||||
continue
|
||||
references.append(_ref(
|
||||
kind='fulfillment_policy',
|
||||
object_id=policy.id,
|
||||
display_name=getattr(policy, 'display_name', None) or f'Policy #{policy.id}',
|
||||
status=policy.status,
|
||||
version=getattr(policy, 'version', None),
|
||||
reference_path='; '.join(hit_paths),
|
||||
admin_path='/admin/shipping-inventory?section=fulfillment',
|
||||
))
|
||||
|
||||
# [STEP 6] 客户识别定义 / 规则集
|
||||
for definition in ShippingIdentityDefinition.query.filter_by(
|
||||
context_field_id=field_id, status='active',
|
||||
).all():
|
||||
references.append(_ref(
|
||||
kind='identity_definition',
|
||||
object_id=definition.id,
|
||||
display_name=definition.display_name or definition.definition_code,
|
||||
status=definition.status,
|
||||
version=None,
|
||||
reference_path='context_field_id',
|
||||
admin_path='/admin/shipping-identity-rules',
|
||||
extra={'definition_code': definition.definition_code},
|
||||
))
|
||||
for rule_set in ShippingIdentityRuleSet.query.filter(
|
||||
ShippingIdentityRuleSet.status.in_(['draft', 'published']),
|
||||
).all():
|
||||
for index, item in enumerate((rule_set.definition_json or {}).get('definitions', []) or []):
|
||||
if isinstance(item, dict) and str(item.get('context_field_id') or '') == field_id:
|
||||
references.append(_ref(
|
||||
kind='identity_rule_set',
|
||||
object_id=rule_set.id,
|
||||
display_name=f'Identity RuleSet v{rule_set.version}',
|
||||
status=rule_set.status,
|
||||
version=rule_set.version,
|
||||
reference_path=f'definition.definitions[{index}].context_field_id',
|
||||
admin_path='/admin/shipping-identity-rules',
|
||||
))
|
||||
|
||||
return references
|
||||
|
||||
|
||||
def list_field_runtime_reference_kinds(field_id: str) -> list[str]:
|
||||
"""
|
||||
返回仍会阻断配置变更的下游 kind 列表(兼容旧调用方)。
|
||||
|
||||
不含已结束 Extraction/Run;那些只出现在 analyze_field_impact 的 historical 段。
|
||||
"""
|
||||
kinds: list[str] = []
|
||||
for item in list_field_runtime_references(field_id):
|
||||
kind = str(item.get('kind') or '')
|
||||
if kind and kind not in kinds:
|
||||
kinds.append(kind)
|
||||
return kinds
|
||||
|
||||
|
||||
def _historical_run_hint(field_id: str) -> dict[str, Any]:
|
||||
"""统计历史观测/裁决/值引用;仅提示,不阻断。"""
|
||||
observation_count = db.session.query(ShippingOrderFieldObservation.id).filter_by(field_id=field_id).count()
|
||||
decision_count = db.session.query(ShippingOrderFieldDecision.id).filter_by(field_id=field_id).count()
|
||||
value_count = db.session.query(ShippingOrderFieldValue.id).filter_by(field_id=field_id).count()
|
||||
schema_version_count = 0
|
||||
schema_versions: list[dict[str, Any]] = []
|
||||
for version in ShippingOrderSchemaVersion.query.filter(
|
||||
ShippingOrderSchemaVersion.status.in_(['published', 'retired']),
|
||||
).all():
|
||||
fields = (version.definition_json or {}).get('fields') or []
|
||||
if any(str(item.get('field_id') or '') == field_id for item in fields if isinstance(item, dict)):
|
||||
schema_version_count += 1
|
||||
family = version.schema
|
||||
schema_versions.append({
|
||||
'schema_version_id': version.id,
|
||||
'version': version.version,
|
||||
'status': version.status,
|
||||
'schema_code': family.schema_code if family is not None else None,
|
||||
'schema_display_name': family.display_name if family is not None else None,
|
||||
})
|
||||
return {
|
||||
'observation_count': observation_count,
|
||||
'decision_count': decision_count,
|
||||
'value_count': value_count,
|
||||
'immutable_schema_version_count': schema_version_count,
|
||||
'immutable_schema_versions': schema_versions,
|
||||
'blocks_publish': False,
|
||||
}
|
||||
|
||||
|
||||
def analyze_field_impact(field_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
单字段影响分析:阻断类下游对象明细 + 历史只读提示。
|
||||
|
||||
Returns:
|
||||
field_id、blocking_items、blocking_kinds、historical、can_unadopt / can_retire_extension。
|
||||
"""
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
blocking_items = list_field_runtime_references(field_id)
|
||||
blocking_kinds: list[str] = []
|
||||
for item in blocking_items:
|
||||
kind = str(item.get('kind') or '')
|
||||
if kind and kind not in blocking_kinds:
|
||||
blocking_kinds.append(kind)
|
||||
historical = _historical_run_hint(field_id)
|
||||
return {
|
||||
'field_id': field_id,
|
||||
'field_code': field.field_code if field is not None else None,
|
||||
'blocking_items': blocking_items,
|
||||
'blocking_kinds': blocking_kinds,
|
||||
'blocking_count': len(blocking_items),
|
||||
'historical': historical,
|
||||
'can_unadopt': not blocking_items,
|
||||
'can_retire_extension': (
|
||||
field is not None
|
||||
and field.asset_kind == 'extension'
|
||||
and not blocking_items
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def analyze_unadopt_impact(*, previous_field_ids: set[str], next_field_ids: set[str]) -> dict[str, Any]:
|
||||
"""
|
||||
Schema 发布前:对「上一 published 已启用、本草稿取消采用」的字段做门禁汇总。
|
||||
|
||||
Returns:
|
||||
blocked 字段 map(含 kinds + items)、warnings、历史只读提示。
|
||||
blocked 结构:{ field_id: { kinds: [...], items: [...] } },并附 blocked_field_ids 便于前端。
|
||||
"""
|
||||
omitted = previous_field_ids - next_field_ids
|
||||
blocked: dict[str, dict[str, Any]] = {}
|
||||
warnings: list[dict[str, Any]] = []
|
||||
for field_id in sorted(omitted):
|
||||
impact = analyze_field_impact(field_id)
|
||||
if impact['blocking_items']:
|
||||
blocked[field_id] = {
|
||||
'field_id': field_id,
|
||||
'field_code': impact['field_code'],
|
||||
'kinds': list(impact['blocking_kinds']),
|
||||
'items': list(impact['blocking_items']),
|
||||
}
|
||||
elif impact['historical']['observation_count'] or impact['historical']['immutable_schema_version_count']:
|
||||
warnings.append({
|
||||
'field_id': field_id,
|
||||
'field_code': impact['field_code'],
|
||||
'historical': impact['historical'],
|
||||
'severity': 'info',
|
||||
})
|
||||
return {
|
||||
'omitted_field_ids': sorted(omitted),
|
||||
'blocked': blocked,
|
||||
'blocked_field_ids': sorted(blocked.keys()),
|
||||
'warnings': warnings,
|
||||
'can_publish': not blocked,
|
||||
}
|
||||
@@ -2,8 +2,10 @@
|
||||
services/shipping_notice/fulfillment_policy_registry.py
|
||||
|
||||
用途:管理货代字段能力绑定与版本化滚动履约策略。
|
||||
依赖:订单 Schema、履约策略模型与统一 AppError。
|
||||
逻辑:策略使用稳定 field_id 绑定货代能力;冻结只消费当前 published 策略,历史 Snapshot 保存完整策略事实。
|
||||
依赖:唯一发货订单 Schema、字段资产、履约策略模型与统一 AppError。
|
||||
逻辑:策略使用稳定 field_id 绑定货代能力;核心能力仅允许系统标准行字段;
|
||||
发布策略前必须存在已发布 Schema,且绑定字段已被采用;
|
||||
冻结只消费当前 published 策略,历史 Snapshot 保存完整策略事实。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,9 +18,16 @@ from typing import Any
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingFulfillmentPolicy, ShippingOrderField, ShippingOrderSchema, ShippingOrderSchemaVersion
|
||||
from app.services.shipping_notice.standard_field_registry import (
|
||||
DEFAULT_SCHEMA_FAMILY_CODE,
|
||||
FULFILLMENT_CORE_FIELD_CODES,
|
||||
)
|
||||
|
||||
|
||||
SHIP_AVAILABLE_ROLLING_V1 = 'SHIP_AVAILABLE_ROLLING_V1'
|
||||
_CORE_CAPABILITIES = frozenset({
|
||||
'fulfillment.reservation_identity', 'fulfillment.part_number', 'fulfillment.quantity',
|
||||
})
|
||||
_CAPABILITIES = {
|
||||
'fulfillment.reservation_identity': {'scope': 'line', 'value_type': 'string', 'required': True},
|
||||
'fulfillment.part_number': {'scope': 'line', 'value_type': 'string', 'required': True},
|
||||
@@ -42,7 +51,15 @@ def capability_catalog() -> list[dict[str, Any]]:
|
||||
|
||||
|
||||
def _schema() -> ShippingOrderSchema:
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
"""
|
||||
读取唯一发货订单 Schema(STANDARD_SHIPPING_NOTICE),兼容历史 SHIPPING_ORDER。
|
||||
|
||||
Raises:
|
||||
NotFoundError: Schema 尚未初始化。
|
||||
"""
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code=DEFAULT_SCHEMA_FAMILY_CODE).one_or_none()
|
||||
if schema is None:
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
if schema is None:
|
||||
raise NotFoundError('Shipping order schema is not initialized', code='SHIPPING.ORDER_SCHEMA_NOT_FOUND')
|
||||
return schema
|
||||
@@ -53,8 +70,8 @@ def _checksum(definition: dict[str, Any]) -> str:
|
||||
return hashlib.sha256(json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
|
||||
|
||||
|
||||
def _field_bindings(raw: Any, *, schema_id: int) -> list[dict[str, Any]]:
|
||||
"""校验能力与稳定 field_id 的一对一绑定,拒绝 scope/type 漂移。"""
|
||||
def _field_bindings(raw: Any, **_ignored: Any) -> list[dict[str, Any]]:
|
||||
"""校验能力与稳定 field_id 的一对一绑定;核心能力仅允许系统标准行字段。"""
|
||||
if not isinstance(raw, list):
|
||||
raise ValidationError('field_bindings must be a list', code='SHIPPING.FULFILLMENT_POLICY_INVALID')
|
||||
seen_capabilities: set[str] = set()
|
||||
@@ -68,11 +85,25 @@ def _field_bindings(raw: Any, *, schema_id: int) -> list[dict[str, Any]]:
|
||||
spec = _CAPABILITIES.get(capability)
|
||||
field = db.session.get(ShippingOrderField, field_id) if field_id else None
|
||||
if (
|
||||
spec is None or field is None or field.schema_id != schema_id or field.status != 'active'
|
||||
spec is None or field is None or field.status != 'active'
|
||||
or field.scope != spec['scope'] or field.value_type != spec['value_type']
|
||||
or capability in seen_capabilities or field_id in seen_fields
|
||||
):
|
||||
raise ValidationError('field capability binding is invalid', code='SHIPPING.FULFILLMENT_POLICY_INVALID')
|
||||
expected_code = _CANONICAL_FIELD_CODES.get(capability)
|
||||
if capability in _CORE_CAPABILITIES:
|
||||
if field.asset_kind != 'system_standard' or field.field_code not in FULFILLMENT_CORE_FIELD_CODES:
|
||||
raise ValidationError(
|
||||
'Core fulfillment capabilities require system standard line fields',
|
||||
code='SHIPPING.FULFILLMENT_FIELD_INVALID',
|
||||
details={'capability_code': capability, 'field_code': field.field_code},
|
||||
)
|
||||
if expected_code and field.field_code != expected_code:
|
||||
raise ValidationError(
|
||||
'Core fulfillment capability must bind the canonical standard field',
|
||||
code='SHIPPING.FULFILLMENT_FIELD_INVALID',
|
||||
details={'capability_code': capability, 'expected': expected_code},
|
||||
)
|
||||
seen_capabilities.add(capability)
|
||||
seen_fields.add(field_id)
|
||||
bindings.append({
|
||||
@@ -91,7 +122,7 @@ def _field_bindings(raw: Any, *, schema_id: int) -> list[dict[str, Any]]:
|
||||
return sorted(bindings, key=lambda item: item['capability_code'])
|
||||
|
||||
|
||||
def _definition(raw: dict[str, Any], *, schema_id: int) -> dict[str, Any]:
|
||||
def _definition(raw: dict[str, Any], **_ignored: Any) -> dict[str, Any]:
|
||||
"""生成可发布的受控策略定义,策略仅支持滚动发货语义。"""
|
||||
policy_code = str(raw.get('policy_code') or SHIP_AVAILABLE_ROLLING_V1).strip()
|
||||
if policy_code != SHIP_AVAILABLE_ROLLING_V1:
|
||||
@@ -101,10 +132,27 @@ def _definition(raw: dict[str, Any], *, schema_id: int) -> dict[str, Any]:
|
||||
'fulfillment_mode': 'ship_available_rolling',
|
||||
'requires_confirmed_customer': True,
|
||||
'allows_partial_reservation': False,
|
||||
'field_bindings': _field_bindings(raw.get('field_bindings'), schema_id=schema_id),
|
||||
'field_bindings': _field_bindings(raw.get('field_bindings')),
|
||||
}
|
||||
|
||||
|
||||
def list_field_references(field_id: str) -> list[dict[str, Any]]:
|
||||
"""列出仍绑定该字段的履约策略版本,供影响分析使用。"""
|
||||
items: list[dict[str, Any]] = []
|
||||
for policy in ShippingFulfillmentPolicy.query.filter(
|
||||
ShippingFulfillmentPolicy.status.in_(['draft', 'published']),
|
||||
).all():
|
||||
bindings = (policy.definition_json or {}).get('field_bindings') or []
|
||||
if any(str(item.get('field_id') or '') == field_id for item in bindings if isinstance(item, dict)):
|
||||
items.append({
|
||||
'kind': 'fulfillment_policy',
|
||||
'policy_id': policy.id,
|
||||
'version': policy.version,
|
||||
'status': policy.status,
|
||||
})
|
||||
return items
|
||||
|
||||
|
||||
def _payload(policy: ShippingFulfillmentPolicy) -> dict[str, Any]:
|
||||
"""序列化策略版本,前端只能拿到已验证定义与版本状态。"""
|
||||
return {
|
||||
@@ -116,13 +164,19 @@ def _payload(policy: ShippingFulfillmentPolicy) -> dict[str, Any]:
|
||||
|
||||
|
||||
def get_state() -> dict[str, Any]:
|
||||
"""读取货代履约策略管理状态及当前发布版本。"""
|
||||
"""读取唯一发货订单 Schema 的货代履约策略管理状态及当前发布版本。"""
|
||||
schema = _schema()
|
||||
policies = ShippingFulfillmentPolicy.query.filter_by(schema_id=schema.id).order_by(ShippingFulfillmentPolicy.version.desc()).all()
|
||||
return {'capabilities': capability_catalog(), 'policies': [_payload(item) for item in policies]}
|
||||
return {
|
||||
'schema_code': schema.schema_code,
|
||||
'capabilities': capability_catalog(),
|
||||
'policies': [_payload(item) for item in policies],
|
||||
}
|
||||
|
||||
|
||||
def create_draft(raw: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
def create_draft(
|
||||
raw: dict[str, Any], *, actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""创建下一策略草稿;未发布策略不得参与冻结。"""
|
||||
schema = _schema()
|
||||
latest = db.session.query(ShippingFulfillmentPolicy.version).filter_by(schema_id=schema.id).order_by(ShippingFulfillmentPolicy.version.desc()).first()
|
||||
@@ -136,34 +190,44 @@ def create_draft(raw: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]
|
||||
return _payload(policy)
|
||||
|
||||
|
||||
def publish(policy_id: int, *, actor_id: int | None, expected_lock_version: int | None) -> dict[str, Any]:
|
||||
"""发布策略并退役旧版本;策略字段必须存在于当前发布 Schema。"""
|
||||
def publish(
|
||||
policy_id: int, *, actor_id: int | None, expected_lock_version: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""发布策略并退役旧版本;策略字段必须存在于当前已发布 Schema。"""
|
||||
policy = db.session.get(ShippingFulfillmentPolicy, policy_id)
|
||||
if policy is None:
|
||||
raise NotFoundError('Fulfillment policy not found', code='SHIPPING.FULFILLMENT_POLICY_NOT_FOUND')
|
||||
schema = _schema()
|
||||
if policy.schema_id != schema.id:
|
||||
raise NotFoundError('Fulfillment policy not found', code='SHIPPING.FULFILLMENT_POLICY_NOT_FOUND')
|
||||
if policy.status != 'draft' or expected_lock_version != policy.lock_version:
|
||||
raise ConflictError('Fulfillment policy has changed', code='SHIPPING.FULFILLMENT_POLICY_CONFLICT')
|
||||
definition = _definition(dict(policy.definition_json or {}), schema_id=policy.schema_id)
|
||||
published_schema = ShippingOrderSchemaVersion.query.filter_by(
|
||||
schema_id=policy.schema_id, status='published',
|
||||
).one_or_none()
|
||||
if published_schema is not None:
|
||||
enabled_field_ids = {
|
||||
str(config.get('field_id'))
|
||||
for config in (published_schema.definition_json or {}).get('fields') or []
|
||||
if config.get('enabled', True)
|
||||
}
|
||||
missing_field_ids = sorted(
|
||||
str(binding['field_id'])
|
||||
for binding in definition['field_bindings']
|
||||
if str(binding['field_id']) not in enabled_field_ids
|
||||
if published_schema is None:
|
||||
raise ConflictError(
|
||||
'Fulfillment policy requires a published schema version',
|
||||
code='SHIPPING.FULFILLMENT_POLICY_SCHEMA_REQUIRED',
|
||||
details={'schema_id': policy.schema_id},
|
||||
)
|
||||
enabled_field_ids = {
|
||||
str(config.get('field_id'))
|
||||
for config in (published_schema.definition_json or {}).get('fields') or []
|
||||
if config.get('enabled', True)
|
||||
}
|
||||
missing_field_ids = sorted(
|
||||
str(binding['field_id'])
|
||||
for binding in definition['field_bindings']
|
||||
if str(binding['field_id']) not in enabled_field_ids
|
||||
)
|
||||
if missing_field_ids:
|
||||
raise ValidationError(
|
||||
'Fulfillment policy fields must be included in the published schema',
|
||||
code='SHIPPING.FULFILLMENT_POLICY_INVALID',
|
||||
details={'field_ids': missing_field_ids},
|
||||
)
|
||||
if missing_field_ids:
|
||||
raise ValidationError(
|
||||
'Fulfillment policy fields must be included in the published schema',
|
||||
code='SHIPPING.FULFILLMENT_POLICY_INVALID',
|
||||
details={'field_ids': missing_field_ids},
|
||||
)
|
||||
current = ShippingFulfillmentPolicy.query.filter_by(schema_id=policy.schema_id, status='published').one_or_none()
|
||||
now = datetime.utcnow()
|
||||
if current is not None:
|
||||
@@ -176,7 +240,7 @@ def publish(policy_id: int, *, actor_id: int | None, expected_lock_version: int
|
||||
|
||||
|
||||
def published_policy() -> ShippingFulfillmentPolicy:
|
||||
"""取得当前可执行策略;没有发布版本时 fail closed。"""
|
||||
"""取得唯一 Schema 当前可执行策略;没有发布版本时 fail closed。"""
|
||||
schema = _schema()
|
||||
policy = ShippingFulfillmentPolicy.query.filter_by(schema_id=schema.id, status='published').one_or_none()
|
||||
if policy is None:
|
||||
|
||||
@@ -4,7 +4,9 @@ services/shipping_notice/fulfillment_workflow.py
|
||||
用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传/RPA 与自动串联编排。
|
||||
依赖:customer_identity_gate、reservation_gate、match、export、rpa、query_service、inventory_workflow、inventory_mapping_workflow、动态订单字段、tool_common、tool_response。
|
||||
逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match;
|
||||
订单行按锁定 Schema 的业务用途从当前 Extraction FieldValue 读取。
|
||||
订单行按锁定 Schema 的业务用途从当前 Extraction FieldValue 读取;
|
||||
STP:auto_progress / try_auto_chain_after_match 止于 Excel 待人工上传;
|
||||
无论 AUTO_UPLOAD 开关为何值,自动链均不调用 upload_to_freight。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -154,6 +156,7 @@ def _auto_generate_excel_enabled() -> bool:
|
||||
|
||||
|
||||
def _auto_upload_enabled() -> bool:
|
||||
"""读取货代自动上传开关;STP 自动链已忽略该开关,仅保留配置探测/兼容读取。"""
|
||||
return _cfg_bool("SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED", False)
|
||||
|
||||
|
||||
@@ -221,10 +224,10 @@ def try_auto_chain_after_match(
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
匹配成功后自动串联 Excel 导出与货代上传(Hxops chat fallback 链)。
|
||||
匹配成功后自动串联 Excel 导出,并停在待人工上传(STP)。
|
||||
|
||||
核心逻辑:match_result 为 ok 后默认自动生成 Excel;若自动上传开关开启,
|
||||
继续触发 RPA 上传。失败、超时或缺少 RPA 配置时转人工接管。
|
||||
核心逻辑:match_result 为 ok 后默认自动生成 Excel;无论
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 为何值,首期硬禁止自动货代 RPA 上传。
|
||||
|
||||
Args:
|
||||
task: 当前 ShippingTask。
|
||||
@@ -241,9 +244,11 @@ def try_auto_chain_after_match(
|
||||
|
||||
result = match_result
|
||||
from app.services.shipping_notice.tool_common import merge_tool_payload
|
||||
from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state
|
||||
|
||||
tool_payload = merge_tool_payload(task, payload)
|
||||
|
||||
# [STEP 1] 低风险:匹配成功后自动生成 Excel。
|
||||
if _auto_generate_excel_enabled():
|
||||
db.session.refresh(task)
|
||||
if not task.export_file_path and match_completed(task):
|
||||
@@ -252,15 +257,23 @@ def try_auto_chain_after_match(
|
||||
return gen
|
||||
result = prepend_tool_message(gen, str(result.get("message") or ""))
|
||||
|
||||
if _auto_upload_enabled():
|
||||
db.session.refresh(task)
|
||||
if task.export_file_path and task.process_status != "uploaded":
|
||||
up = upload_to_freight({**tool_payload, "mode": "auto"})
|
||||
if up.get("status") == "failed":
|
||||
return up
|
||||
result = prepend_tool_message(up, str(result.get("message") or ""))
|
||||
if up.get("status") in {"running", "needs_human"}:
|
||||
return {**up, "message": result.get("message", up.get("message", ""))}
|
||||
# [STEP 2] STP 硬停:Excel 就绪后进入 wait_manual_upload;绝不调用 upload_to_freight。
|
||||
# 即便 _auto_upload_enabled() 为 True 也不得突破(首期无货代 RPA 自动上传)。
|
||||
db.session.refresh(task)
|
||||
ui = resolve_task_ui_state(task)
|
||||
if ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or (
|
||||
task.export_file_path and task.process_status != "uploaded"
|
||||
):
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message=str(result.get("message") or "发货 Excel 已生成,请在任务处理工作台完成人工上传凭据。"),
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
@@ -616,16 +629,16 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
将已生成的发货 Excel 上传至货代系统,或标记人工上传完成。
|
||||
【AI 触发时机】:Excel 已生成且用户确认上传/重试 RPA 时调用;mode=manual_confirm 用于手工上传收口。
|
||||
登记人工货代上传完成(首期唯一上传收口)。
|
||||
【AI 触发时机】:禁止调用;仅工作台 mark-manual-uploaded 以 mode=manual_confirm 调用。
|
||||
|
||||
核心逻辑:补齐 export → manual_confirm 直接 UPLOADED → auto/retry_upload 走 RPA 触发与超时重试。
|
||||
核心逻辑:首期硬拒绝 auto/retry_upload(不触发货代 RPA);manual_confirm 校验凭据后标记 UPLOADED。
|
||||
|
||||
Args:
|
||||
payload: 须含 task_id;mode 可选 auto / retry_upload / manual_confirm;manual_confirm 可传 freight_ref_no。
|
||||
payload: 须含 task_id;mode 必须为 manual_confirm;须传 evidence_asset_no。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: status 可为 ok / running / needs_human / failed。
|
||||
dict[str, Any]: status 可为 ok / failed。
|
||||
"""
|
||||
lang = resolve_lang(payload)
|
||||
task = resolve_task_from_payload(payload)
|
||||
@@ -666,14 +679,26 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return gen
|
||||
|
||||
# [STEP 2] 区分人工确认与 RPA 上传两种路径。
|
||||
# 首期 STP:仅允许 manual_confirm(外部货代上传后登记凭据);禁止 auto/retry_upload 触发 RPA。
|
||||
artifact_id = payload.get('artifact_id')
|
||||
try:
|
||||
artifact_id = int(artifact_id) if artifact_id is not None else None
|
||||
except (TypeError, ValueError):
|
||||
return tool_response(status='failed', task=task, message='artifact_id 无效', data=serialize_task_for_tool(task))
|
||||
|
||||
# manual_confirm 需要私有回执;auto/retry_upload 走 Artifact 尝试和回调。
|
||||
mode = str(payload.get("mode") or "auto").strip().lower()
|
||||
if mode != "manual_confirm":
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
message="首期不支持货代 RPA 自动上传。请下载 Excel,在货代系统人工上传后,于任务处理工作台提交截图/PDF 凭据。",
|
||||
data=serialize_task_for_tool(task),
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
stop_agent_turn=True,
|
||||
next_required_action="请在任务处理工作台使用「登记人工上传」。",
|
||||
)
|
||||
|
||||
# manual_confirm 需要私有回执;auto/retry_upload 已在上方拒绝。
|
||||
if mode == "manual_confirm":
|
||||
operator_id = payload.get('operator_id')
|
||||
try:
|
||||
@@ -971,9 +996,16 @@ def run_auto_progress_fulfillment_steps(
|
||||
payload: dict[str, Any],
|
||||
steps: list[str],
|
||||
) -> dict[str, Any] | None:
|
||||
"""auto_progress 中匹配→导出→上传编排;有早停响应时返回 dict,否则返回 None。"""
|
||||
"""
|
||||
auto_progress 中匹配→导出编排;有早停响应时返回 dict,否则返回 None。
|
||||
|
||||
核心逻辑:自动匹配与生成 Excel;Phase 0 STP 硬禁止自动货代上传(含 RPA),
|
||||
停在 wait_manual_upload。无论 SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 为何值,
|
||||
本函数永不调用 upload_to_freight;货代 RPA 上传不在自动链范围内。
|
||||
"""
|
||||
from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state
|
||||
|
||||
# [STEP 1] 若允许自动匹配且当前尚未完成匹配,则先进入 match_inventory。
|
||||
# 这是履约侧串联的起点,失败或需人审时必须立即早停返回。
|
||||
if _auto_match_enabled() and not match_completed(task):
|
||||
matched = match_inventory({"task_id": task.task_no, **(payload or {})})
|
||||
if matched.get("status") != "ok":
|
||||
@@ -981,19 +1013,28 @@ def run_auto_progress_fulfillment_steps(
|
||||
steps.append("库存匹配")
|
||||
|
||||
# [STEP 2] 匹配完成后按配置自动生成 Excel。
|
||||
# 只在尚未生成导出文件时触发,避免重复导出覆盖人工下载链路。
|
||||
if _auto_generate_excel_enabled() and match_completed(task) and not task.export_file_path:
|
||||
gen = generate_excel({"task_id": task.task_no})
|
||||
if gen.get("status") != "ok":
|
||||
return gen
|
||||
steps.append("生成发货 Excel")
|
||||
|
||||
# [STEP 3] 最后根据配置尝试自动上传货代。
|
||||
# 上传会返回 running/needs_human 等早停状态,因此这里直接把结果上抛给 auto_progress。
|
||||
if _auto_upload_enabled() and task.export_file_path and task.process_status != "uploaded":
|
||||
up = upload_to_freight({"task_id": task.task_no, "mode": "auto"})
|
||||
if up.get("status") == "running":
|
||||
steps.append("触发 RPA 上传")
|
||||
return up
|
||||
# [STEP 3] STP 停点:Excel 已生成则进入 wait_manual_upload。
|
||||
# AUTO_UPLOAD 分支已硬禁用,绝不 enqueue 货代 RPA。
|
||||
ui = resolve_task_ui_state(task)
|
||||
if ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or (
|
||||
task.export_file_path and task.process_status != "uploaded"
|
||||
):
|
||||
steps.append("等待人工上传货代")
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message="发货 Excel 已生成,请下载后在货代系统上传,并提交截图/PDF 凭据。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
)
|
||||
|
||||
return None
|
||||
@@ -772,10 +772,14 @@ def run_intake_parse(
|
||||
is_profile_sample = str(locked.purpose or '') == 'order_document_profile_sample'
|
||||
schema_definition: dict[str, Any] = {'fields': []}
|
||||
if not is_profile_sample:
|
||||
from app.models import ShippingOrderSchemaVersion
|
||||
from app.services.shipping_notice.order_schema.runtime import published_version
|
||||
|
||||
try:
|
||||
schema_version = published_version()
|
||||
schema_definition = dict(schema_version.definition_json or {})
|
||||
except ConflictError:
|
||||
schema_definition = {'fields': []}
|
||||
|
||||
schema_version = ShippingOrderSchemaVersion.query.filter_by(status='published').first()
|
||||
schema_definition = dict(schema_version.definition_json or {}) if schema_version is not None else {'fields': []}
|
||||
# [STEP 2] shipping_notice 上传阶段只落快览摘要;模板样本用途保留文档/布局持久化。
|
||||
if is_profile_sample:
|
||||
persist_info = persist_intake_documents(
|
||||
@@ -785,6 +789,14 @@ def run_intake_parse(
|
||||
uploaded_storage_keys=uploaded_storage_keys,
|
||||
schema_definition=schema_definition,
|
||||
)
|
||||
# 模板样本必须先具备可用布局才可进入向导;同内容文件会在此同步复用已有布局。
|
||||
from app.services.shipping_notice.document_layout.lifecycle import schedule_document_layouts
|
||||
|
||||
layout_versions = schedule_document_layouts(
|
||||
ShippingNoticeDocument.query.filter_by(intake_id=locked.id).all(),
|
||||
created_by_id=locked.user_id,
|
||||
)
|
||||
persist_info['layout_version_count'] = len(layout_versions)
|
||||
|
||||
tech_summary = intake_result_to_structured_summary(result)
|
||||
tech_summary['document_count'] = persist_info.get('document_count')
|
||||
|
||||
@@ -16,7 +16,12 @@ from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingNoticeDocument, ShippingOrderDocumentProfileEditLease, ShippingOrderDocumentProfileSample
|
||||
from app.models import (
|
||||
ShippingNoticeDocument,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileEditLease,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
|
||||
@@ -54,12 +59,17 @@ def _initial_definition(main_table_id: str) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _new_profile_code() -> str:
|
||||
"""生成新模板族的服务端系统编码,避免客户端命名参与解析、版本和审计主键。"""
|
||||
return f"ODP-{datetime.utcnow():%Y%m%d}-{secrets.token_hex(6).upper()}"
|
||||
|
||||
|
||||
def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
以单事务完成创建向导。
|
||||
|
||||
Args:
|
||||
data: 模板身份、已解析样本文档、主表格、Schema 和浏览器会话身份。
|
||||
data: 模板名称、已解析样本文档、主表格、Schema 和浏览器会话身份;系统编码由服务端生成。
|
||||
actor_id: 当前管理员主键。
|
||||
|
||||
Returns:
|
||||
@@ -83,10 +93,16 @@ def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
|
||||
if not any(str(item.get('table_id') or '') == table_id for item in tables):
|
||||
raise ValidationError('Selected main table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
|
||||
for _attempt in range(3):
|
||||
profile_code = _new_profile_code()
|
||||
if ShippingOrderDocumentProfile.query.filter_by(profile_code=profile_code).first() is None:
|
||||
break
|
||||
else:
|
||||
raise ConflictError('Could not allocate order document profile code', code='SHIPPING.ORDER_DOCUMENT_PROFILE_DRAFT_EXISTS')
|
||||
try:
|
||||
saved = profile_service.save_draft(
|
||||
{
|
||||
'profile_code': data.get('profile_code'),
|
||||
'profile_code': profile_code,
|
||||
'display_name': data.get('display_name'),
|
||||
'schema_version_id': schema_version_id,
|
||||
'definition': _initial_definition(table_id),
|
||||
@@ -104,7 +120,7 @@ def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
|
||||
profile_service._audit(
|
||||
profile_id=profile_id, document_id=document.id, event_type='wizard_created', actor_id=actor_id,
|
||||
operation_id=operation_id, browser_session_id=session_id, revision_no=revision_no,
|
||||
detail={'main_table_id': table_id, 'schema_version_id': schema_version_id},
|
||||
detail={'main_table_id': table_id, 'schema_version_id': schema_version_id, 'profile_code': profile_code},
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
token = secrets.token_urlsafe(32)
|
||||
|
||||
@@ -1481,17 +1481,22 @@ def _reconstructed_table_html(*, layout: dict[str, Any], raw_table: dict[str, An
|
||||
raise ValidationError('Coordinate reconstruction could not produce a table', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID') from exc
|
||||
|
||||
|
||||
def list_sample_documents(*, limit: int = 50) -> list[dict[str, Any]]:
|
||||
"""仅列出模板工作台专用样本;普通发货历史附件不得混入下拉框。"""
|
||||
def list_sample_documents(*, actor_id: int | None, limit: int = 50) -> list[dict[str, Any]]:
|
||||
"""仅列出当前管理员可标注的专用样本,并按内容哈希收敛重复上传。"""
|
||||
if actor_id is None:
|
||||
return []
|
||||
safe_limit = max(1, min(int(limit), 100))
|
||||
rows = ShippingNoticeDocument.query.join(
|
||||
ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeDocument.intake_id,
|
||||
).filter(
|
||||
ShippingNoticeDocument.document_type.in_({'attachment', 'email_body'}),
|
||||
ShippingNoticeIntake.purpose == 'order_document_profile_sample',
|
||||
ShippingNoticeIntake.user_id == int(actor_id),
|
||||
ShippingNoticeIntake.parse_status == 'parsed',
|
||||
ShippingNoticeDocument.current_layout_version_id.is_not(None),
|
||||
).order_by(ShippingNoticeDocument.created_at.desc()).limit(safe_limit * 4).all()
|
||||
result: list[dict[str, Any]] = []
|
||||
seen_content_hashes: set[str] = set()
|
||||
for document in rows:
|
||||
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
|
||||
|
||||
@@ -1499,6 +1504,10 @@ def list_sample_documents(*, limit: int = 50) -> list[dict[str, Any]]:
|
||||
tables = layout.get('tables') if isinstance(layout.get('tables'), list) else []
|
||||
if layout.get('status') != 'ready' or not tables:
|
||||
continue
|
||||
content_hash = str(document.content_hash or '').strip().lower()
|
||||
# 同一内容只显示最新可用文档,避免同名/同附件重复占据选择器。
|
||||
if content_hash and content_hash in seen_content_hashes:
|
||||
continue
|
||||
intake = db.session.get(ShippingNoticeIntake, document.intake_id)
|
||||
if intake is None:
|
||||
continue
|
||||
@@ -1524,6 +1533,8 @@ def list_sample_documents(*, limit: int = 50) -> list[dict[str, Any]]:
|
||||
'can_delete': delete_block_reason is None,
|
||||
'delete_block_reason': delete_block_reason,
|
||||
})
|
||||
if content_hash:
|
||||
seen_content_hashes.add(content_hash)
|
||||
if len(result) >= safe_limit:
|
||||
break
|
||||
return result
|
||||
|
||||
@@ -586,6 +586,30 @@ def persist_order_extraction_result(
|
||||
or candidate.duplicate_resolution == 'open_existing'
|
||||
)
|
||||
):
|
||||
# STP:automatic 候选须再过严格门禁才物化 Task;失败则降为 provisional 待复核。
|
||||
if candidate.candidate_status == 'accepted' and candidate.acceptance_mode == 'automatic':
|
||||
from app.services.shipping_notice.candidate_service import evaluate_candidate_stp_gate
|
||||
passed, stp_reasons = evaluate_candidate_stp_gate(candidate)
|
||||
if not passed:
|
||||
candidate.candidate_status = 'provisional'
|
||||
candidate.acceptance_mode = None
|
||||
candidate.accepted_at = None
|
||||
candidate.acceptance_reason = None
|
||||
candidate.acceptance_policy_version = None
|
||||
candidate.selected = False
|
||||
reasons.extend(stp_reasons)
|
||||
pending_item = {
|
||||
'candidate_no': candidate.candidate_no,
|
||||
'order_index': index,
|
||||
'source_intake_no': intake_no,
|
||||
'po_number': candidate.po_number,
|
||||
'reasons': sorted(set(reasons)),
|
||||
'missing_fields': list(candidate.missing_fields_json or []),
|
||||
'duplicate_status': candidate.duplicate_status,
|
||||
}
|
||||
pending.append(pending_item)
|
||||
pending_by_intake[int(intake.id)].append(pending_item)
|
||||
continue
|
||||
auto_candidates.append(candidate)
|
||||
else:
|
||||
if candidate.candidate_status != 'accepted' and candidate.validation_status == 'ready' and not auto_create_enabled:
|
||||
@@ -957,3 +981,159 @@ def submit_order_extraction_run_result(
|
||||
flag_modified(run, 'auto_freeze_policy_json')
|
||||
db.session.commit()
|
||||
return result
|
||||
|
||||
|
||||
def submit_order_extraction_unit_result(
|
||||
*,
|
||||
run: Any,
|
||||
unit: Any,
|
||||
orders: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
单个 PDF/Unit 完成后立即落 Candidate 并按 STP 门禁建 Task,不等待同 Run 其它 Unit。
|
||||
|
||||
核心逻辑:仅锁定本 Unit 的 Intake/Document,复用 persist_order_extraction_result;
|
||||
通过门禁的 automatic Candidate 建批后由编排器触发 auto_progress;最后幂等初始化 Review Case。
|
||||
|
||||
Args:
|
||||
run: 所属 ShippingOrderExtractionRun。
|
||||
unit: 已进入 candidate_ready 的 ShippingOrderExtractionUnit。
|
||||
orders: 该 Unit 合并邮件补充后的订单数组。
|
||||
|
||||
Returns:
|
||||
与 submit_order_extraction_run_result 同形的业务摘要(作用域为本 Unit)。
|
||||
"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
snapshot_intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else []
|
||||
unit_intake_id = int(unit.intake_id)
|
||||
unit_document_id = int(unit.document_id)
|
||||
scoped_snapshots = []
|
||||
for item in snapshot_intakes:
|
||||
if not isinstance(item, dict) or int(item.get('intake_id') or 0) != unit_intake_id:
|
||||
continue
|
||||
docs = [
|
||||
document for document in (item.get('documents') or [])
|
||||
if isinstance(document, dict) and int(document.get('document_id') or 0) == unit_document_id
|
||||
]
|
||||
scoped = dict(item)
|
||||
scoped['documents'] = docs
|
||||
scoped_snapshots.append(scoped)
|
||||
if not scoped_snapshots:
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='Unit Intake 不在 Run 快照中')
|
||||
|
||||
frozen_context_by_intake = {
|
||||
int(item['intake_id']): dict(item.get('deterministic_context') or {})
|
||||
for item in scoped_snapshots
|
||||
if str(item.get('intake_id') or '').isdigit()
|
||||
}
|
||||
frozen_layout_candidates_by_document = {
|
||||
int(document['document_id']): list(document.get('layout_schema_candidates') or [])
|
||||
for intake in scoped_snapshots
|
||||
for document in intake.get('documents') or []
|
||||
if isinstance(document, dict) and str(document.get('document_id') or '').isdigit()
|
||||
}
|
||||
frozen_evidence_text_by_document = {
|
||||
int(document['document_id']): (
|
||||
frozen_document_text_for_parser(document) or str(document.get('extracted_text') or '')
|
||||
)
|
||||
for intake in scoped_snapshots
|
||||
for document in intake.get('documents') or []
|
||||
if isinstance(document, dict) and str(document.get('document_id') or '').isdigit()
|
||||
}
|
||||
intake = db.session.get(ShippingNoticeIntake, unit_intake_id)
|
||||
document = db.session.get(ShippingNoticeDocument, unit_document_id)
|
||||
if intake is None or document is None or int(document.intake_id) != unit_intake_id:
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='Unit Intake/Document 不存在')
|
||||
if int(intake.user_id) != int(run.user_id):
|
||||
raise ForbiddenError(code='SHIPPING_NOTICE.FORBIDDEN', message='Unit Intake 不属于 Run 用户')
|
||||
|
||||
# 幂等:本 Unit 候选已消费建单则直接回放,避免重复建批。
|
||||
consumed = ShippingNoticeCandidate.query.filter(
|
||||
ShippingNoticeCandidate.order_extraction_run_id == int(run.id),
|
||||
ShippingNoticeCandidate.primary_document_id == unit_document_id,
|
||||
ShippingNoticeCandidate.consumed_task_id.isnot(None),
|
||||
).all()
|
||||
if consumed:
|
||||
task_nos = sorted({
|
||||
str(task.task_no)
|
||||
for task in ShippingTask.query.filter(
|
||||
ShippingTask.id.in_([int(row.consumed_task_id) for row in consumed])
|
||||
).all()
|
||||
})
|
||||
result = {
|
||||
'status': 'ok',
|
||||
'request_id': str(run.run_no),
|
||||
'batch_no': None,
|
||||
'created': [{'task_no': task_no} for task_no in task_nos],
|
||||
'opened_existing': [],
|
||||
'pending_orders': [],
|
||||
'non_shipping_orders': [],
|
||||
'created_count': len(task_nos),
|
||||
'opened_existing_count': 0,
|
||||
'pending_count': 0,
|
||||
'non_shipping_count': 0,
|
||||
'created_with_missing_fields_count': 0,
|
||||
'idempotent_replay': True,
|
||||
'unit_id': int(unit.id),
|
||||
}
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
ensure_run_review_cases(run=run)
|
||||
return result
|
||||
|
||||
session = db.session.query(ChatSession).filter_by(session_id=run.conversation_id).one()
|
||||
current_intakes = _load_intakes(
|
||||
session=session,
|
||||
intake_nos=[str(intake.intake_no)],
|
||||
lock=True,
|
||||
allow_consumed=False,
|
||||
)
|
||||
current_documents = [row for row in _load_documents(current_intakes, lock=True) if int(row.id) == unit_document_id]
|
||||
if len(current_intakes) != 1 or len(current_documents) != 1:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED', message='Unit 源数据已变化')
|
||||
|
||||
for intake_snapshot in scoped_snapshots:
|
||||
frozen_context = dict(intake_snapshot.get('deterministic_context') or {})
|
||||
if canonical_mail_context(current_intakes[0]) != frozen_context:
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED',
|
||||
message='Run 冻结后的邮件上下文已变化',
|
||||
)
|
||||
for frozen in intake_snapshot.get('documents') or []:
|
||||
if not isinstance(frozen, dict):
|
||||
continue
|
||||
doc = current_documents[0]
|
||||
if (
|
||||
str(doc.content_hash or '') != str(frozen.get('content_hash') or '')
|
||||
or str(doc.extracted_text or '') != str(frozen.get('extracted_text') or '')
|
||||
):
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED',
|
||||
message='Run 冻结后的附件内容已变化',
|
||||
)
|
||||
|
||||
result = persist_order_extraction_result(
|
||||
session=session,
|
||||
intakes=current_intakes,
|
||||
documents=current_documents,
|
||||
current_snapshot=str(run.input_snapshot_hash),
|
||||
request_id=f'{run.run_no}:unit:{int(unit.id)}',
|
||||
orders=orders,
|
||||
run_id=int(run.id),
|
||||
schema_version_id=int(run.schema_version_id),
|
||||
extraction_source='deterministic_order_parser',
|
||||
frozen_context_by_intake=frozen_context_by_intake,
|
||||
frozen_layout_candidates_by_document=frozen_layout_candidates_by_document,
|
||||
frozen_evidence_text_by_document=frozen_evidence_text_by_document,
|
||||
auto_create_enabled=bool(((run.auto_freeze_policy_json or {}).get('enabled', False))),
|
||||
)
|
||||
result['unit_id'] = int(unit.id)
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
ensure_run_review_cases(run=run)
|
||||
_store_run_submission_result(
|
||||
intakes=current_intakes,
|
||||
snapshot_hash=str(run.input_snapshot_hash),
|
||||
request_id=str(run.run_no),
|
||||
result=result,
|
||||
)
|
||||
db.session.commit()
|
||||
return result
|
||||
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_extraction_run_service.py
|
||||
|
||||
用途:创建、查询和序列化建单前订单抽取领域 Run。
|
||||
依赖:Agent/ChatSession、ShippingNoticeIntake/Document、已发布订单 Schema、SQLAlchemy 事务。
|
||||
逻辑:服务端校验用户与会话权限,冻结 Intake/Document/Schema 输入,并以数据库唯一约束保证幂等与单 Intake 单活跃 Run。
|
||||
用途:创建、查询和序列化建单前订单抽取领域 Run;Unit 完成后独立触发 Candidate/STP 下游。
|
||||
依赖:Agent/ChatSession、ShippingNoticeIntake/Document、已发布订单 Schema、SQLAlchemy 事务、
|
||||
order_extraction.submit_order_extraction_unit_result、progress_workflow.auto_progress。
|
||||
逻辑:服务端校验用户与会话权限,冻结 Intake/Document/Schema 输入,并以数据库唯一约束保证幂等与单 Intake 单活跃 Run;
|
||||
progress_ready_extraction_unit 供 Worker 在每 PDF candidate_ready 后立即落库并推进。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -430,8 +432,11 @@ def _build_snapshot(
|
||||
'user_id': user_id,
|
||||
'owner_agent_id': owner_agent_id,
|
||||
'conversation_id': conversation_id,
|
||||
# 冻结族编码 + 版本 + checksum,保证历史 Run 在资产解耦后仍可按契约回放。
|
||||
'schema': {
|
||||
'schema_version_id': schema_version.id,
|
||||
'schema_code': schema_version.schema.schema_code if schema_version.schema else None,
|
||||
'family_code': schema_version.schema.schema_code if schema_version.schema else None,
|
||||
'version': schema_version.version,
|
||||
'checksum': schema_version.checksum,
|
||||
'extraction_contract': dify_contract(schema_version),
|
||||
@@ -1891,6 +1896,48 @@ def mark_order_extraction_persistence_started(run: ShippingOrderExtractionRun) -
|
||||
run.progress_version = int(run.progress_version or 0) + 1
|
||||
|
||||
|
||||
def progress_ready_extraction_unit(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
unit: Any,
|
||||
orders: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
单个 PDF/Unit 进入 candidate_ready 后立即物化 Candidate,并按 STP 触发下游 auto_progress。
|
||||
|
||||
核心逻辑:不依赖同 Run 其它 Unit 完成;调用 unit 级 submit;建批路径由编排器
|
||||
调用 progress_workflow.auto_progress;若仅打开既有任务则不重复推进。
|
||||
|
||||
Args:
|
||||
run: 所属抽取 Run。
|
||||
unit: 已 candidate_ready 的 Unit。
|
||||
orders: 该 Unit 订单数组。
|
||||
|
||||
Returns:
|
||||
Unit 级落库摘要(含 created / pending_orders)。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_unit_result
|
||||
|
||||
mark_order_extraction_persistence_started(run)
|
||||
result = submit_order_extraction_unit_result(run=run, unit=unit, orders=orders)
|
||||
# 建批编排器会异步调用同一 auto_progress;此处仅为无编排器的已创建任务兜底同步推进。
|
||||
created = list(result.get('created') or [])
|
||||
if created and not result.get('batch_no') and not result.get('idempotent_replay'):
|
||||
from app.services.shipping_notice.progress_workflow import auto_progress
|
||||
for item in created:
|
||||
task_no = str(item.get('task_no') or '').strip()
|
||||
if not task_no:
|
||||
continue
|
||||
try:
|
||||
auto_progress({'task_id': task_no, 'source': 'system'})
|
||||
except Exception:
|
||||
current_app.logger.exception(
|
||||
'STP auto_progress failed after unit persist run=%s unit=%s task=%s',
|
||||
run.run_no, getattr(unit, 'id', None), task_no,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def sync_order_extraction_run_after_job_recovery(job: Any) -> None:
|
||||
"""
|
||||
通用 Job 超时回收后同步领域 Run,避免 Job 已 queued/failed 而 Run 永久 running。
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_extraction_workflow.py
|
||||
|
||||
用途:提供冻结订单抽取快照的确定性模板路由及旧 Workflow 输入兼容函数。
|
||||
用途:提供冻结订单抽取快照的确定性模板路由及 STP 裁决(straight_through / needs_review)。
|
||||
依赖:MinerU 紧凑快照、订单 Profile、Schema 校验、统一错误类型。
|
||||
逻辑:Worker 先调用本模块裁决确定性解析或人工复核;旧 Workflow 函数将在阶段 1 移除,不参与新订单主链。
|
||||
逻辑:Worker 先调用本模块裁决确定性解析或人工复核,并输出 route_decision/reason_codes;
|
||||
仅严格门禁通过才可直通建单;旧 Workflow 函数将在阶段 1 移除,不参与新订单主链。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -37,6 +38,10 @@ class DeterministicRouteResult:
|
||||
|
||||
AI 触发时机:无需调用。此对象仅在 HXOPS Worker 判断已批准模板能否确定性解析
|
||||
时创建,禁止包含文档正文、字段值、坐标、Prompt 或 Provider 凭据。
|
||||
|
||||
decision 必含 STP 裁决字段:
|
||||
- route_decision: straight_through | needs_review
|
||||
- reason_codes: 严格门禁原因码列表(与 fallback_reason_codes 对齐并可能增补)
|
||||
"""
|
||||
|
||||
execution_mode: Literal['deterministic', 'review_required', 'skipped']
|
||||
@@ -44,6 +49,60 @@ class DeterministicRouteResult:
|
||||
decision: dict[str, Any]
|
||||
|
||||
|
||||
def _apply_stp_route_adjudication(
|
||||
decision: dict[str, Any],
|
||||
*,
|
||||
execution_mode: Literal['deterministic', 'review_required', 'skipped'],
|
||||
orders: list[dict[str, Any]],
|
||||
) -> DeterministicRouteResult:
|
||||
"""
|
||||
在路由结果上写入明确的 STP 裁决:straight_through | needs_review。
|
||||
|
||||
核心逻辑:严格门禁——缺字段、低置信、缺证据、未批准自动建单、无自动接受标记、
|
||||
或非 deterministic 执行态 → needs_review;仅干净直通可 straight_through。
|
||||
重复冲突在 Candidate 落库阶段再拦,不在本函数臆造。
|
||||
|
||||
Args:
|
||||
decision: 路由决策字典(就地写入 route_decision / reason_codes)。
|
||||
execution_mode: deterministic | review_required | skipped。
|
||||
orders: 本轮产出订单(用于检查 _hxops_acceptance)。
|
||||
|
||||
Returns:
|
||||
带 STP 字段的 DeterministicRouteResult。
|
||||
"""
|
||||
reason_codes = [str(code) for code in (decision.get('fallback_reason_codes') or []) if str(code).strip()]
|
||||
has_acceptance = any(
|
||||
isinstance(order, dict) and order.get('_hxops_acceptance') == 'approved_deterministic_profile_v1'
|
||||
for order in orders
|
||||
)
|
||||
|
||||
# [STEP 1] 非确定性执行一律人工复核。
|
||||
if execution_mode != 'deterministic':
|
||||
if not reason_codes:
|
||||
reason_codes.append('review_required' if execution_mode == 'review_required' else 'skipped')
|
||||
decision['fallback_reason_codes'] = reason_codes
|
||||
decision['reason_codes'] = list(reason_codes)
|
||||
decision['route_decision'] = 'needs_review'
|
||||
return DeterministicRouteResult(execution_mode=execution_mode, orders=orders, decision=decision)
|
||||
|
||||
# [STEP 2] 严格门禁:模板未批准 / 已有原因码 / 无自动接受标记 → needs_review。
|
||||
if not bool(decision.get('auto_create_approved')) and 'profile_auto_create_not_approved' not in reason_codes:
|
||||
reason_codes.append('profile_auto_create_not_approved')
|
||||
if not has_acceptance and not reason_codes:
|
||||
reason_codes.append('acceptance_marker_missing')
|
||||
if reason_codes or not has_acceptance or not bool(decision.get('auto_create_approved')):
|
||||
decision['fallback_reason_codes'] = reason_codes
|
||||
decision['reason_codes'] = list(reason_codes)
|
||||
decision['route_decision'] = 'needs_review'
|
||||
return DeterministicRouteResult(execution_mode='deterministic', orders=orders, decision=decision)
|
||||
|
||||
# [STEP 3] 全部严格门禁通过 → 直通。
|
||||
decision['fallback_reason_codes'] = []
|
||||
decision['reason_codes'] = []
|
||||
decision['route_decision'] = 'straight_through'
|
||||
return DeterministicRouteResult(execution_mode='deterministic', orders=orders, decision=decision)
|
||||
|
||||
|
||||
def _unit_snapshot(run: Any, unit: Any) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
"""从 Run 快照定位单元,并在必要时补读当前 ready layout。"""
|
||||
return resolve_unit_runtime_snapshot(run, unit)
|
||||
@@ -899,10 +958,11 @@ def _merge_confirmed_profile_order_fields(run: Any, *, unit: Any, orders: list[d
|
||||
|
||||
|
||||
def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult:
|
||||
"""计算单元的模板路由并返回仅含脱敏诊断的结构化结果。
|
||||
"""计算单元的模板路由并返回含 STP 裁决的脱敏结构化结果。
|
||||
|
||||
AI 触发时机:无需调用。Worker 在每个 Unit 执行前调用;只有唯一、已批准、
|
||||
完整且符合冻结 Schema 的模板解析可走 deterministic,其余均明确进入人工复核。
|
||||
完整且符合冻结 Schema 的模板解析可走 deterministic + straight_through,
|
||||
其余均明确 needs_review(decision.route_decision / reason_codes)。
|
||||
"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
@@ -936,14 +996,14 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
|
||||
if profile_result.get('blocking'):
|
||||
issues = profile_result.get('issues') if isinstance(profile_result.get('issues'), list) else []
|
||||
decision['fallback_reason_codes'] = [_route_reason_for_issue(str(issue)) for issue in issues]
|
||||
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
# 文档出现多个模板表时不猜测其业务关系,即使其中一个模板已批准也必须人工复核。
|
||||
if not tables:
|
||||
decision['fallback_reason_codes'] = ['business_table_not_found']
|
||||
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
if len(tables) != 1:
|
||||
decision['fallback_reason_codes'] = ['multiple_business_tables']
|
||||
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
selected = tables[0]
|
||||
decision.update({
|
||||
'selected_profile_code': selected.get('profile_code'),
|
||||
@@ -969,13 +1029,14 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
|
||||
if orders is not None:
|
||||
decision['fallback_reason_codes'] = [reason_code]
|
||||
decision['parsed_table_count'] = 1
|
||||
return DeterministicRouteResult(execution_mode='deterministic', orders=orders, decision=decision)
|
||||
# 不完整字段仍可产出草稿订单,但 STP 严格门禁必须 needs_review。
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders)
|
||||
reason_code = review_reason or reason_code
|
||||
if orders is None:
|
||||
if reason_code == 'row_needs_review':
|
||||
decision['review_details'] = _profile_row_review_details(selected)
|
||||
decision['fallback_reason_codes'] = [reason_code or 'business_table_not_found']
|
||||
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
decision['parsed_table_count'] = 1
|
||||
decision['business_table_count'] = 1
|
||||
decision['matched_table_count'] = 1
|
||||
@@ -986,7 +1047,7 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
|
||||
if isinstance(order, dict):
|
||||
order.pop('_hxops_acceptance', None)
|
||||
decision['fallback_reason_codes'] = ['profile_auto_create_not_approved']
|
||||
return DeterministicRouteResult(execution_mode='deterministic', orders=orders, decision=decision)
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders)
|
||||
|
||||
|
||||
def _profile_row_review_details(table: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
backend/app/services/shipping_notice/order_extraction_workspace_projection.py
|
||||
|
||||
用途:把订单抽取 Run/Unit 的数据库事实投影为工作台摘要和按 PDF 的详情列表。
|
||||
依赖:ShippingOrderExtractionRun/Unit/RouteDecision/ProgressEvent ORM、冻结 snapshot 和 Unit 结果 JSON。
|
||||
逻辑:只输出用户可理解的业务信息;文件名、原因码、模板摘要和可操作按钮都在这里统一裁剪与组装。
|
||||
依赖:ShippingNoticeCandidate、ShippingOrderExtractionRun/Unit/RouteDecision/ProgressEvent ORM、
|
||||
冻结 snapshot 和 Unit 结果 JSON。
|
||||
逻辑:只输出用户可理解的业务信息;文件名、原因码、模板摘要、重复订单 open_existing 入口
|
||||
与可操作按钮都在这里统一裁剪与组装。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,6 +14,7 @@ from collections import Counter
|
||||
from typing import Any
|
||||
|
||||
from app.models import (
|
||||
ShippingNoticeCandidate,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRouteDecision,
|
||||
ShippingOrderExtractionRun,
|
||||
@@ -213,26 +216,66 @@ def _current_activity_reason_codes(event: ShippingOrderExtractionProgressEvent |
|
||||
return sorted(code for code in codes if code)
|
||||
|
||||
|
||||
def _run_available_actions(run: ShippingOrderExtractionRun, units: list[ShippingOrderExtractionUnit]) -> list[str]:
|
||||
"""根据 Run 与 Unit 事实返回用户可见操作,前端不得自行推断。"""
|
||||
def _open_existing_document_ids(run: ShippingOrderExtractionRun) -> set[int]:
|
||||
"""返回本轮已判定 open_existing 且带目标任务号的 PDF document_id 集合。"""
|
||||
return {
|
||||
int(document_id)
|
||||
for document_id, duplicate in _duplicate_projection_by_document(run).items()
|
||||
if (
|
||||
str(duplicate.get('duplicate_resolution') or '') == 'open_existing'
|
||||
and str(duplicate.get('existing_task_no') or '').strip()
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def _run_available_actions(
|
||||
run: ShippingOrderExtractionRun,
|
||||
units: list[ShippingOrderExtractionUnit],
|
||||
*,
|
||||
open_existing_doc_ids: set[int] | None = None,
|
||||
) -> list[str]:
|
||||
"""根据 Run 与 Unit 事实返回用户可见操作;纯 open_existing 不暴露人工复核入口。"""
|
||||
open_ids = open_existing_doc_ids if open_existing_doc_ids is not None else _open_existing_document_ids(run)
|
||||
actions = ['view_details']
|
||||
if run.status in {'review_required', 'partially_completed'} or any(unit.status == 'review_required' for unit in units):
|
||||
needs_manual_review = any(
|
||||
str(unit.status or '') == 'review_required'
|
||||
and int(unit.document_id) not in open_ids
|
||||
for unit in units
|
||||
)
|
||||
# 无 Unit 时保留历史行为:Run 状态为复核态则仍可进复核。
|
||||
if not units and run.status in {'review_required', 'partially_completed'}:
|
||||
needs_manual_review = True
|
||||
if needs_manual_review:
|
||||
actions.append('enter_manual_review')
|
||||
if run.status == 'failed' or any(unit.status == 'failed' for unit in units):
|
||||
actions.append('retry_failed_attachments')
|
||||
return actions
|
||||
|
||||
|
||||
def _unresolved_review_document_count(run: ShippingOrderExtractionRun) -> int:
|
||||
"""统计用户仍需处理的 PDF 复核 Case,候选已生成但未确认也必须计入。"""
|
||||
def _unresolved_review_document_count(
|
||||
run: ShippingOrderExtractionRun,
|
||||
*,
|
||||
open_existing_doc_ids: set[int] | None = None,
|
||||
) -> int:
|
||||
"""统计用户仍需处理的 PDF 复核 Case;open_existing 已关联任务的 PDF 不计复核。"""
|
||||
resolved_statuses = {'confirmed', 'non_order', 'superseded'}
|
||||
open_ids = open_existing_doc_ids if open_existing_doc_ids is not None else set()
|
||||
return len({
|
||||
int(case.document_id)
|
||||
for case in getattr(run, 'review_cases', []) or []
|
||||
if str(case.status or '') not in resolved_statuses
|
||||
if (
|
||||
str(case.status or '') not in resolved_statuses
|
||||
and int(case.document_id or 0) not in open_ids
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
def _result_opened_existing_count(run: ShippingOrderExtractionRun) -> int:
|
||||
"""从 Run.result_json 读取已打开已有任务数。"""
|
||||
result = run.result_json if isinstance(run.result_json, dict) else {}
|
||||
return max(0, int(result.get('opened_existing_count') or 0))
|
||||
|
||||
|
||||
def _planned_document_count(run: ShippingOrderExtractionRun, units: list[ShippingOrderExtractionUnit]) -> int:
|
||||
"""布局等待期尚无 Unit 时,使用冻结选择计划展示用户已选附件数量。"""
|
||||
if units:
|
||||
@@ -242,8 +285,58 @@ def _planned_document_count(run: ShippingOrderExtractionRun, units: list[Shippin
|
||||
return max(0, int(selection.get('selected_attachment_count') or 0))
|
||||
|
||||
|
||||
def _document_available_actions(unit: ShippingOrderExtractionUnit) -> list[str]:
|
||||
"""按单元状态返回详情项可见操作。"""
|
||||
def _duplicate_projection_by_document(run: ShippingOrderExtractionRun) -> dict[int, dict[str, Any]]:
|
||||
"""
|
||||
按 PDF 汇总本轮 Candidate 的重复订单决策,供右侧处理面分流 open_existing。
|
||||
|
||||
核心逻辑:同一 Document 可能有多 Candidate;优先取带目标任务号的 open_existing。
|
||||
"""
|
||||
if getattr(run, 'id', None) is None:
|
||||
return {}
|
||||
rows = (
|
||||
ShippingNoticeCandidate.query.filter(
|
||||
ShippingNoticeCandidate.order_extraction_run_id == int(run.id),
|
||||
ShippingNoticeCandidate.is_current_version.is_(True),
|
||||
).all()
|
||||
)
|
||||
by_doc: dict[int, dict[str, Any]] = {}
|
||||
for candidate in rows:
|
||||
document_id = int(candidate.primary_document_id or 0)
|
||||
if document_id <= 0:
|
||||
continue
|
||||
resolution = str(candidate.duplicate_resolution or '').strip() or None
|
||||
task_no = str(candidate.duplicate_target_task_no or '').strip().upper() or None
|
||||
status = str(candidate.duplicate_status or '').strip() or None
|
||||
payload = {
|
||||
'duplicate_resolution': resolution,
|
||||
'existing_task_no': task_no,
|
||||
'duplicate_status': status,
|
||||
}
|
||||
current = by_doc.get(document_id)
|
||||
# [STEP] 有明确 open_existing + 任务号时覆盖弱结果,保证前端能跳转已有任务。
|
||||
if resolution == 'open_existing' and task_no:
|
||||
by_doc[document_id] = payload
|
||||
elif current is None:
|
||||
by_doc[document_id] = payload
|
||||
return by_doc
|
||||
|
||||
|
||||
def _document_available_actions(
|
||||
unit: ShippingOrderExtractionUnit,
|
||||
*,
|
||||
duplicate: dict[str, Any] | None = None,
|
||||
) -> list[str]:
|
||||
"""
|
||||
按单元状态与重复决策返回详情项可见操作。
|
||||
|
||||
核心逻辑:open_existing 且已有任务号时优先暴露 open_existing,不再映射为人工复核入口。
|
||||
"""
|
||||
dup = duplicate if isinstance(duplicate, dict) else {}
|
||||
if (
|
||||
str(dup.get('duplicate_resolution') or '') == 'open_existing'
|
||||
and str(dup.get('existing_task_no') or '').strip()
|
||||
):
|
||||
return ['open_existing', 'view_evidence']
|
||||
if unit.status == 'candidate_ready':
|
||||
return ['view_evidence', 'review_candidate']
|
||||
if unit.status == 'review_required':
|
||||
@@ -251,6 +344,34 @@ def _document_available_actions(unit: ShippingOrderExtractionUnit) -> list[str]:
|
||||
return []
|
||||
|
||||
|
||||
def _document_reason_code(
|
||||
unit: ShippingOrderExtractionUnit,
|
||||
*,
|
||||
duplicate: dict[str, Any] | None = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
选择面向用户的原因码;重复打开已有任务时优先暴露 duplicate_status。
|
||||
|
||||
Args:
|
||||
unit: 抽取单元。
|
||||
duplicate: 文档级重复投影。
|
||||
|
||||
Returns:
|
||||
原因码字符串,无则 None。
|
||||
"""
|
||||
dup = duplicate if isinstance(duplicate, dict) else {}
|
||||
if (
|
||||
str(dup.get('duplicate_resolution') or '') == 'open_existing'
|
||||
and str(dup.get('existing_task_no') or '').strip()
|
||||
):
|
||||
return (
|
||||
str(unit.reason_code or '').strip()
|
||||
or str(dup.get('duplicate_status') or '').strip()
|
||||
or 'duplicate_open_existing'
|
||||
)
|
||||
return unit.reason_code or ('technical_failure' if unit.status == 'failed' else None)
|
||||
|
||||
|
||||
def _planned_layout_documents(
|
||||
run: ShippingOrderExtractionRun,
|
||||
documents: dict[int, dict[str, Any]],
|
||||
@@ -288,6 +409,9 @@ def _planned_layout_documents(
|
||||
'email_supplement': {'status': 'none', 'relation_codes': [], 'conflict_count': 0},
|
||||
'reason_code': None,
|
||||
'review_details': [],
|
||||
'duplicate_resolution': None,
|
||||
'existing_task_no': None,
|
||||
'duplicate_status': None,
|
||||
'available_actions': [],
|
||||
'activity_event_code': 'layout_parsing_completed' if completed else 'layout_parsing_started' if started else None,
|
||||
'started_at': (started.occurred_at or started.received_at or started.created_at).isoformat() + 'Z' if started else None,
|
||||
@@ -364,7 +488,8 @@ def serialize_workspace_run_documents(run: ShippingOrderExtractionRun) -> list[d
|
||||
"""
|
||||
构建工作台按 PDF 展示的详情列表。
|
||||
|
||||
AI 触发时机:当工作台详情抽屉或聊天卡需要回答“哪份 PDF 成功、用了什么模板、为什么失败”时使用。
|
||||
AI 触发时机:当工作台详情抽屉或聊天卡需要回答“哪份 PDF 成功、用了什么模板、为什么失败、
|
||||
是否应打开已有任务”时使用。
|
||||
"""
|
||||
units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
|
||||
documents = _snapshot_documents(run)
|
||||
@@ -374,10 +499,12 @@ def serialize_workspace_run_documents(run: ShippingOrderExtractionRun) -> list[d
|
||||
profiles_by_key = _snapshot_profiles(run)
|
||||
field_codes = _schema_field_codes(run)
|
||||
route_by_unit = _latest_route_decisions(run)
|
||||
duplicates_by_doc = _duplicate_projection_by_document(run)
|
||||
items: list[dict[str, Any]] = []
|
||||
for unit in units:
|
||||
orders = _orders_from_unit(unit)
|
||||
document = documents.get(int(unit.document_id), {})
|
||||
duplicate = duplicates_by_doc.get(int(unit.document_id), {})
|
||||
items.append({
|
||||
'unit_id': int(unit.id),
|
||||
'document_id': int(unit.document_id),
|
||||
@@ -392,9 +519,12 @@ def serialize_workspace_run_documents(run: ShippingOrderExtractionRun) -> list[d
|
||||
'line_count': _line_count(orders),
|
||||
'profile': _profile_projection(unit, route_by_unit=route_by_unit, profiles_by_key=profiles_by_key),
|
||||
'email_supplement': _email_supplement_projection(unit, event_map, field_codes=field_codes),
|
||||
'reason_code': unit.reason_code or ('technical_failure' if unit.status == 'failed' else None),
|
||||
'reason_code': _document_reason_code(unit, duplicate=duplicate),
|
||||
'review_details': list((unit.result_json or {}).get('review_details') or []),
|
||||
'available_actions': _document_available_actions(unit),
|
||||
'duplicate_resolution': duplicate.get('duplicate_resolution'),
|
||||
'existing_task_no': duplicate.get('existing_task_no'),
|
||||
'duplicate_status': duplicate.get('duplicate_status'),
|
||||
'available_actions': _document_available_actions(unit, duplicate=duplicate),
|
||||
'activity_event_code': None,
|
||||
'started_at': getattr(unit, 'started_at', None).isoformat() + 'Z' if getattr(unit, 'started_at', None) else None,
|
||||
'last_activity_at': getattr(unit, 'last_activity_at', None).isoformat() + 'Z' if getattr(unit, 'last_activity_at', None) else None,
|
||||
@@ -413,6 +543,7 @@ def serialize_workspace_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
documents = _snapshot_documents(run)
|
||||
_, current_event = _latest_progress_events(run)
|
||||
status_counter = Counter(str(unit.status or '') for unit in units)
|
||||
open_existing_doc_ids = _open_existing_document_ids(run)
|
||||
current_activity = None
|
||||
if run.status in {'queued', 'processing'}:
|
||||
if str(run.phase or '') == 'waiting_layout':
|
||||
@@ -444,10 +575,19 @@ def serialize_workspace_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
'selection_batch': int(pending_unit.selection_batch or 0) or None,
|
||||
'reason_codes': [],
|
||||
}
|
||||
review_document_count = max(
|
||||
status_counter.get('review_required', 0),
|
||||
_unresolved_review_document_count(run),
|
||||
review_units = sum(
|
||||
1
|
||||
for unit in units
|
||||
if str(unit.status or '') == 'review_required' and int(unit.document_id) not in open_existing_doc_ids
|
||||
)
|
||||
open_existing_units = sum(
|
||||
1 for unit in units if int(unit.document_id) in open_existing_doc_ids
|
||||
)
|
||||
review_document_count = max(
|
||||
review_units,
|
||||
_unresolved_review_document_count(run, open_existing_doc_ids=open_existing_doc_ids),
|
||||
)
|
||||
opened_existing_count = max(open_existing_units, _result_opened_existing_count(run))
|
||||
return {
|
||||
'summary': {
|
||||
'total_documents': _planned_document_count(run, units),
|
||||
@@ -457,9 +597,10 @@ def serialize_workspace_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
'review_required_documents': review_document_count,
|
||||
'failed_documents': status_counter.get('failed', 0),
|
||||
'candidate_count': sum(_candidate_count(unit) for unit in units),
|
||||
'opened_existing_documents': opened_existing_count,
|
||||
},
|
||||
'current_activity': current_activity,
|
||||
'available_actions': _run_available_actions(run, units),
|
||||
'available_actions': _run_available_actions(run, units, open_existing_doc_ids=open_existing_doc_ids),
|
||||
}
|
||||
|
||||
|
||||
@@ -483,6 +624,7 @@ def serialize_workspace_run_chat_state(run: ShippingOrderExtractionRun) -> dict[
|
||||
'reviewRequiredDocuments': int(summary.get('review_required_documents') or 0),
|
||||
'failedDocuments': int(summary.get('failed_documents') or 0),
|
||||
'candidateCount': int(summary.get('candidate_count') or 0),
|
||||
'openedExistingCount': int(summary.get('opened_existing_documents') or 0),
|
||||
},
|
||||
'currentActivity': (
|
||||
{
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
services/shipping_notice/order_freeze_service.py
|
||||
|
||||
用途:将已复核的动态订单解析冻结为强类型履约快照。
|
||||
依赖:ShippingOrderExtraction/FieldValue/Observation、ShippingOrderSnapshot、ShippingTask 与统一 AppError。
|
||||
逻辑:Candidate/Extraction 阶段可继续保留动态证据;本服务通过门禁后一次写入按 field_id 冻结的 Snapshot,库存、导出和上传的后续阶段只读取该快照。
|
||||
依赖:ShippingOrderExtraction/FieldValue/Observation、ShippingOrderSnapshot、ShippingTask、
|
||||
standard_field_registry(投影列)、统一 AppError。
|
||||
逻辑:Candidate/Extraction 阶段可继续保留动态证据;本服务通过门禁后一次写入按 field_id 冻结的 Snapshot;
|
||||
冻结摘要含 family_code + schema_version/checksum;库存、导出和上传后续阶段只读取该快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -27,13 +29,10 @@ from app.models import (
|
||||
ShippingTask,
|
||||
ShippingNoticeDocument,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import (
|
||||
published_policy,
|
||||
required_field_configs,
|
||||
)
|
||||
|
||||
|
||||
# 强类型列只是既有查询/导出投影;56 项标准字段的完整事实始终写在 field_id JSON。
|
||||
# 注意:本常量须保持在 fulfillment_policy / standard_field_registry 导入之前定义,
|
||||
# 供 standard_field_registry 引用,避免三方循环导入。
|
||||
HEADER_FIELD_PROJECTIONS = {
|
||||
'customer_po_number': 'customer_po_number', 'customer_code': 'customer_code', 'customer_name': 'customer_name',
|
||||
'bill_to_customer': 'bill_to_customer', 'bill_to_address': 'bill_to_address',
|
||||
@@ -201,8 +200,21 @@ def _source_manifest(*, extraction: ShippingOrderExtraction, policy: Any) -> dic
|
||||
for item in ShippingOrderReviewEvent.query.filter_by(extraction_id=extraction.id, snapshot_id=None).all()
|
||||
]
|
||||
return {
|
||||
'family_code': getattr(extraction.schema_version.schema, 'schema_code', None),
|
||||
'schema_version_id': extraction.schema_version_id,
|
||||
'schema_version': extraction.schema_version.version,
|
||||
'schema_checksum': extraction.schema_version.checksum,
|
||||
'frozen_field_definitions': [
|
||||
{
|
||||
'field_id': item.get('field_id'),
|
||||
'field_code': item.get('field_code'),
|
||||
'scope': item.get('scope'),
|
||||
'value_type': item.get('value_type'),
|
||||
'enabled': item.get('enabled', True),
|
||||
}
|
||||
for item in (extraction.schema_version.definition_json or {}).get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True)
|
||||
],
|
||||
'fulfillment_policy': {'id': policy.id, 'version': policy.version, 'checksum': policy.checksum},
|
||||
'fields': fields,
|
||||
'manual_reviews': reviews,
|
||||
@@ -239,6 +251,12 @@ def _confirmed_ordering_customer(extraction: ShippingOrderExtraction) -> Shippin
|
||||
|
||||
def _policy_configs(extraction: ShippingOrderExtraction) -> tuple[Any, dict[str, dict[str, Any]]]:
|
||||
"""按已发布货代策略验证冻结契约,Schema 只继续承担字段目录职责。"""
|
||||
# 懒加载:避免 standard_field_registry ↔ order_freeze ↔ fulfillment_policy 循环导入。
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import (
|
||||
published_policy,
|
||||
required_field_configs,
|
||||
)
|
||||
|
||||
definition = extraction.schema_version.definition_json or {}
|
||||
policy = published_policy()
|
||||
required = required_field_configs(definition, policy)
|
||||
@@ -249,7 +267,6 @@ def _policy_configs(extraction: ShippingOrderExtraction) -> tuple[Any, dict[str,
|
||||
}
|
||||
return policy, all_configs | required
|
||||
|
||||
|
||||
def _assert_llm_review_gate(extraction: ShippingOrderExtraction, configs: dict[str, dict[str, Any]]) -> None:
|
||||
"""关键字段若由未经证据确认的 LLM fallback 参与裁决,则强制人工复核。"""
|
||||
decisions = {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_review_confirmation_service.py
|
||||
|
||||
用途:按 PDF 确认复核草稿并独立创建发货任务。
|
||||
依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task 与重复检测门禁。
|
||||
用途:按 PDF 确认复核草稿并独立创建发货任务,确认后复用同一 auto_progress 链。
|
||||
依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、progress_workflow.auto_progress。
|
||||
逻辑:确认在单事务内分别锁定 Case 与 Draft(避免 joinedload+FOR UPDATE),
|
||||
冻结不可变 Revision,物化仅供履约的人工 Candidate 与 accepted Extraction;
|
||||
全程不改写机器 Candidate,也不创建 Batch。由 workspace shipping_notice API 调用。
|
||||
全程不改写机器 Candidate,也不创建 Batch。由 workspace shipping_notice API 调用;
|
||||
API commit 后触发 progress_workflow.auto_progress(禁止平行推进链)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -301,4 +302,29 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
))
|
||||
log_task_event(task, 'task_created_from_review_case', {'case_no': case.case_no, 'confirmed_revision_id': None})
|
||||
db.session.flush()
|
||||
return {'task_no': task.task_no, 'idempotent_replay': False, 'case': serialize_review_case(case)}
|
||||
# 调用方须在 commit 后调用 trigger_auto_progress_after_review_confirm。
|
||||
return {
|
||||
'task_no': task.task_no,
|
||||
'idempotent_replay': False,
|
||||
'case': serialize_review_case(case),
|
||||
'trigger_auto_progress': True,
|
||||
}
|
||||
|
||||
|
||||
def trigger_auto_progress_after_review_confirm(*, task_no: str | None, idempotent_replay: bool = False) -> dict[str, Any] | None:
|
||||
"""
|
||||
人工复核确认建单并提交事务后,复用与 STP 直通相同的 auto_progress 入口。
|
||||
|
||||
核心逻辑:幂等回放不重复推进;系统 source,禁止平行链路。
|
||||
|
||||
Args:
|
||||
task_no: 新建或回放任务号。
|
||||
idempotent_replay: 是否幂等回放。
|
||||
|
||||
Returns:
|
||||
auto_progress 响应;无任务或回放时返回 None。
|
||||
"""
|
||||
if idempotent_replay or not task_no:
|
||||
return None
|
||||
from app.services.shipping_notice.progress_workflow import auto_progress
|
||||
return auto_progress({'task_id': str(task_no).strip(), 'source': 'system'})
|
||||
@@ -119,3 +119,69 @@ def get_user_review_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCa
|
||||
if case is None:
|
||||
raise NotFoundError('Order review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
return case
|
||||
|
||||
|
||||
def get_review_run_visible_to_user(
|
||||
run_no: str,
|
||||
user_id: int,
|
||||
*,
|
||||
is_admin: bool = False,
|
||||
) -> ShippingOrderExtractionRun:
|
||||
"""
|
||||
按 run_no 查找当前用户可见的复核 Run(创建者或管理员只读)。
|
||||
|
||||
核心逻辑:管理员可读全部 Run;普通用户仅可读自己创建且 user_id 非空的 Run。
|
||||
写操作仍须经 get_user_review_run 门禁。
|
||||
|
||||
Args:
|
||||
run_no: 抽取 Run 编号。
|
||||
user_id: 当前用户。
|
||||
is_admin: 为 True 时允许管理员只读可见。
|
||||
|
||||
Returns:
|
||||
可见 Run。
|
||||
|
||||
Raises:
|
||||
NotFoundError: Run 不存在或当前用户无权只读访问。
|
||||
"""
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=run_no).first()
|
||||
if run is None:
|
||||
raise NotFoundError('Order extraction run not found', code='SHIPPING.REVIEW_RUN_NOT_FOUND')
|
||||
if is_admin:
|
||||
return run
|
||||
if run.user_id is None or int(run.user_id) != int(user_id):
|
||||
raise NotFoundError('Order extraction run not found', code='SHIPPING.REVIEW_RUN_NOT_FOUND')
|
||||
return run
|
||||
|
||||
|
||||
def get_review_case_visible_to_user(
|
||||
case_no: str,
|
||||
user_id: int,
|
||||
*,
|
||||
is_admin: bool = False,
|
||||
) -> ShippingOrderReviewCase:
|
||||
"""
|
||||
按 case_no 查找当前用户可见的复核 Case(owner 或管理员只读)。
|
||||
|
||||
核心逻辑:管理员可读全部 Case;普通用户仅可读 owner_user_id 匹配且非空的 Case。
|
||||
写操作仍须经 get_user_review_case 门禁。
|
||||
|
||||
Args:
|
||||
case_no: 复核 Case 编号。
|
||||
user_id: 当前用户。
|
||||
is_admin: 为 True 时允许管理员只读可见。
|
||||
|
||||
Returns:
|
||||
可见 Case。
|
||||
|
||||
Raises:
|
||||
NotFoundError: Case 不存在或当前用户无权只读访问。
|
||||
"""
|
||||
case = ShippingOrderReviewCase.query.filter_by(case_no=case_no).first()
|
||||
if case is None:
|
||||
raise NotFoundError('Order review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
if is_admin:
|
||||
return case
|
||||
if case.owner_user_id is None or int(case.owner_user_id) != int(user_id):
|
||||
raise NotFoundError('Order review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
return case
|
||||
@@ -86,7 +86,8 @@ def compare_definitions(before: dict[str, Any] | None, after: dict[str, Any] | N
|
||||
before: 作为基线的完整版本 definition。
|
||||
after: 用来比较的完整版本 definition。
|
||||
Returns:
|
||||
包含新增、移除、修改和未变字段及属性变更列表的稳定 JSON 结构。
|
||||
包含新增、移除、修改和未变字段及属性变更列表的稳定 JSON 结构;
|
||||
另含顶层 auto_creation_policy 变更摘要。
|
||||
"""
|
||||
before_fields = _field_map(before)
|
||||
after_fields = _field_map(after)
|
||||
@@ -113,4 +114,20 @@ def compare_definitions(before: dict[str, Any] | None, after: dict[str, Any] | N
|
||||
'after': current,
|
||||
'changes': changes,
|
||||
})
|
||||
return {'summary': counts, 'fields': fields}
|
||||
before_policy = (before or {}).get('auto_creation_policy') if isinstance(before, dict) else None
|
||||
after_policy = (after or {}).get('auto_creation_policy') if isinstance(after, dict) else None
|
||||
before_enabled = bool((before_policy or {}).get('enabled')) if isinstance(before_policy, dict) else False
|
||||
after_enabled = bool((after_policy or {}).get('enabled')) if isinstance(after_policy, dict) else False
|
||||
auto_creation = None
|
||||
if before_enabled != after_enabled or (before_policy or {}) != (after_policy or {}):
|
||||
auto_creation = {
|
||||
'key': 'auto_creation_policy.enabled',
|
||||
'kind': 'value',
|
||||
'before': before_enabled,
|
||||
'after': after_enabled,
|
||||
}
|
||||
return {
|
||||
'summary': counts,
|
||||
'fields': fields,
|
||||
'auto_creation_policy': auto_creation,
|
||||
}
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/services/shipping_notice/order_schema/runtime.py
|
||||
|
||||
用途:编译已发布订单 Schema,并裁决 Dify 返回的动态字段 Observation。
|
||||
依赖:订单 Schema 动态模型、ShippingNoticeDocument、registry、订单客户匹配服务。
|
||||
逻辑:提交时先验证原文证据和字段规则,再以已裁决订单头匹配 Bill-to/Ship-to 客户主数据并输出业务投影。
|
||||
依赖:订单 Schema 动态模型、standard_field_registry、ShippingNoticeDocument、registry、订单客户匹配服务。
|
||||
逻辑:提交时先验证原文证据和字段规则,再以已裁决订单头匹配 Bill-to/Ship-to 客户主数据并输出业务投影;
|
||||
published_version 固定读取唯一 Schema STANDARD_SHIPPING_NOTICE(兼容历史 SHIPPING_ORDER)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -24,6 +25,7 @@ from app.models import (
|
||||
ShippingOrderFieldObservation,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice.notice_line_table import inspect_notice_table_text
|
||||
@@ -37,13 +39,41 @@ from app.services.shipping_notice.order_schema.field_rules import (
|
||||
validate_order_field_value,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
from app.services.shipping_notice.standard_field_registry import DEFAULT_SCHEMA_FAMILY_CODE
|
||||
|
||||
|
||||
def published_version() -> ShippingOrderSchemaVersion:
|
||||
"""读取当前唯一 published 订单 Schema;未发布时阻断解析。"""
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').first()
|
||||
"""
|
||||
读取唯一发货订单 Schema 的 published 版本。
|
||||
|
||||
核心逻辑:按 STANDARD_SHIPPING_NOTICE 联表查询;未命中时兼容历史 SHIPPING_ORDER 夹具。
|
||||
"""
|
||||
version = (
|
||||
ShippingOrderSchemaVersion.query
|
||||
.join(ShippingOrderSchema, ShippingOrderSchemaVersion.schema_id == ShippingOrderSchema.id)
|
||||
.filter(
|
||||
ShippingOrderSchema.schema_code == DEFAULT_SCHEMA_FAMILY_CODE,
|
||||
ShippingOrderSchemaVersion.status == 'published',
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if version is None:
|
||||
raise ConflictError('No published shipping order schema', code='SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED')
|
||||
# 兼容历史族编码夹具,避免未迁移测试环境全断。
|
||||
version = (
|
||||
ShippingOrderSchemaVersion.query
|
||||
.join(ShippingOrderSchema, ShippingOrderSchemaVersion.schema_id == ShippingOrderSchema.id)
|
||||
.filter(
|
||||
ShippingOrderSchema.schema_code == 'SHIPPING_ORDER',
|
||||
ShippingOrderSchemaVersion.status == 'published',
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if version is None:
|
||||
raise ConflictError(
|
||||
'No published shipping order schema',
|
||||
code='SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED',
|
||||
details={'schema_code': DEFAULT_SCHEMA_FAMILY_CODE},
|
||||
)
|
||||
return version
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,8 +2,11 @@
|
||||
services/shipping_notice/progress_workflow.py
|
||||
|
||||
用途:承接发货通知任务的自动推进流程,包括解析确认检查、正式库存准备与履约侧串联。
|
||||
依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、tool_response。
|
||||
逻辑:由 task_workflow 对外转调本文件;本文件按当前任务状态决定继续自动推进、停在人审检查点,或进入履约 workflow。
|
||||
依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、
|
||||
state_machine(CheckpointKind)、tool_response。
|
||||
逻辑:由 task_workflow / 复核确认 / Unit 直通落库对外转调本文件;按 checkpoint_kind 早停或继续;
|
||||
STP:must_human / wait_manual_upload 无副作用早停;货代 RPA 上传不在自动链内;
|
||||
系统触发时事件 actor_id=None 且 detail.source=system。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -28,8 +31,8 @@ from app.services.shipping_notice.inventory_source_gate import (
|
||||
)
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
|
||||
from app.services.shipping_notice.state_machine import resolve_task_ui_state
|
||||
from app.services.shipping_notice.tool_common import auto_progress_enabled
|
||||
from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state
|
||||
from app.services.shipping_notice.tool_common import auto_progress_enabled, log_task_event
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
|
||||
|
||||
@@ -38,10 +41,13 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
按任务当前状态自动串联解析确认、正式库存准备与履约动作。
|
||||
【AI 触发时机】:当用户要求“继续处理”“自动推进”“下一步全自动跑完能跑的步骤”时调用。
|
||||
亦由 STP 直通建单、人工复核确认后系统入口复用(同一函数,禁止平行链路)。
|
||||
|
||||
核心逻辑:先检查解析是否需要人工确认,再保证正式库存已按 published Profile 就绪,最后委托 fulfillment workflow 继续推进。
|
||||
核心逻辑:先按 checkpoint_kind 早停(must_human / wait_manual_upload / complete);
|
||||
再检查解析门禁与客户/库存源,保证正式库存就绪后委托 fulfillment(止于待人工上传,不触发 RPA 上传)。
|
||||
Args:
|
||||
payload: 必须能定位任务;可额外携带 lang/locale/language 以及 auto-chain 控制参数。
|
||||
payload: 必须能定位任务;可额外携带 lang/locale/language、auto-chain 控制参数,
|
||||
以及 source(system|workspace_api|tool_api|review_confirmation 等)。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: Tool 标准响应,返回自动推进后的阶段、提示和数据。
|
||||
@@ -53,10 +59,55 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
|
||||
source = str(payload.get("source") or "system").strip() or "system"
|
||||
# 系统入口不写用户 actor;人工 workspace/tool 可传 operator_id。
|
||||
actor_raw = payload.get("operator_id") or payload.get("actor_id")
|
||||
try:
|
||||
actor_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and source != "system" else None
|
||||
except (TypeError, ValueError):
|
||||
actor_id = None
|
||||
log_task_event(
|
||||
task,
|
||||
"auto_progress_started",
|
||||
{"source": source, "process_status": task.process_status, "current_step": task.current_step},
|
||||
actor_id=actor_id,
|
||||
)
|
||||
|
||||
steps: list[str] = []
|
||||
|
||||
# [STEP 0] STP 检查点早停:必须人工或待人工上传时不产生新副作用。
|
||||
ui_early = resolve_task_ui_state(task)
|
||||
if ui_early.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message="发货 Excel 已生成,请在任务处理工作台完成人工上传凭据。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui_early.human_options,
|
||||
checkpoint=ui_early.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
)
|
||||
if ui_early.checkpoint_kind == CheckpointKind.MUST_HUMAN:
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="当前任务需要人工处理,已暂停自动推进。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui_early.human_options,
|
||||
checkpoint=ui_early.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
if ui_early.checkpoint_kind == CheckpointKind.COMPLETE:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message="任务已结束,无需自动推进。",
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
# [STEP 1] 先判断解析结果是否允许进入自动链路。
|
||||
# 解析待确认或低置信度时必须立即停下,避免 Agent 在错误数据上继续做库存/出货操作。
|
||||
# 解析待确认或低置信度时必须立即停下,避免在错误数据上继续做库存/出货操作。
|
||||
threshold = current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD")
|
||||
try:
|
||||
threshold = float(threshold) if threshold is not None else 0.7
|
||||
@@ -128,8 +179,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
# [STEP 2] 保证库存已经就绪。
|
||||
# 正常任务仅复用排程或手动刷新已导出的文件;这里不得隐式触发 RPA。
|
||||
# [STEP 2] 保证库存已经就绪(仅复用已有库存快照;不得隐式触发库存 RPA)。
|
||||
if not task.inventory_lines_json:
|
||||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||||
inv_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"}
|
||||
@@ -137,15 +187,14 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
inv_payload["lang"] = lang
|
||||
inv = ensure_inventory(inv_payload)
|
||||
if inv.get("status") == "running":
|
||||
steps.append("触发 RPA 库存导出")
|
||||
steps.append("等待库存准备")
|
||||
return inv
|
||||
if inv.get("status") != "ok":
|
||||
return inv
|
||||
else:
|
||||
steps.append("载入库存")
|
||||
|
||||
# [STEP 3] 库存就绪后进入履约侧自动推进。
|
||||
# 匹配、生成 Excel、上传货代等步骤统一交给 fulfillment workflow 处理,避免本文件继续膨胀。
|
||||
# [STEP 3] 库存就绪后进入履约侧自动推进(止于待人工上传)。
|
||||
fulfillment_result = fulfillment_workflow.run_auto_progress_fulfillment_steps(task, payload, steps)
|
||||
if fulfillment_result is not None:
|
||||
return fulfillment_result
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
"""
|
||||
services/shipping_notice/query_service.py
|
||||
|
||||
用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链与重复决策字段)。
|
||||
依赖:models.ShippingBatch、ShippingCase、ShippingNoticeCandidate、ShippingTask、ShippingTaskEvent、动态订单字段编辑器。
|
||||
用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。
|
||||
依赖:models.ShippingBatch、ShippingCase、ShippingNoticeCandidate、ShippingTask、ShippingTaskEvent、
|
||||
ShippingOrderReviewCase、ShippingOrderExtractionRun、state_machine、动态订单字段编辑器。
|
||||
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
|
||||
tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉;
|
||||
SUMMARY/DETAIL 经 _task_version_chain_fields 暴露 document_version / supersedes / duplicate_*;
|
||||
SUMMARY 经 _enrich_task_center_fields 附带 todo_category / can_handle / ui_state / recent_event;
|
||||
list_my_todos / count_my_todos 合并建单前 Review Case 与 Task 待办(管理员可读全局,仅创建者 can_handle);
|
||||
客户关键字 SQL 同时过滤 Review Case(文件名/Case 号/PO)与 Task(客户快照/来源文件名);
|
||||
待办 todo_category 下推为与状态机同序的 SQL CASE;list 用 UNION ALL + COUNT/OFFSET/LIMIT,
|
||||
仅水合当前页(禁止 500 截断冒充总数);
|
||||
DETAIL 另投影 parse_validation / process_field_gate / source_candidate 供持久只读展示;
|
||||
订单行仅从任务锁定 Extraction 的 FieldValue 投影,未抽取任务返回空行集。
|
||||
"""
|
||||
@@ -17,7 +22,7 @@ from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import asc, desc
|
||||
from sqlalchemy import asc, case, desc, exists, func, literal, select, union_all
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
@@ -27,10 +32,41 @@ from app.models import (
|
||||
ShippingExportArtifactLine,
|
||||
ShippingInventoryVerification,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
CP_PARSE_REVIEW,
|
||||
CP_RSV_REQ,
|
||||
PH_INV_UNAVAIL,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
PH_LOW_CONF,
|
||||
PH_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
PH_RPA_EXHAUSTED,
|
||||
PH_RPA_PENDING,
|
||||
PH_RSV_REQ,
|
||||
PH_SHORTAGE,
|
||||
PH_UPLOAD_RESULT_UNKNOWN,
|
||||
PH_UPLOAD_RPA_FAILED,
|
||||
PH_UPLOAD_RPA_PENDING,
|
||||
RS_PARSE_REVIEW,
|
||||
RS_REJECTED,
|
||||
RS_RSV_REQ,
|
||||
RS_SHORTAGE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
CheckpointKind,
|
||||
resolve_task_ui_state,
|
||||
resolve_task_ui_state_from_fields,
|
||||
)
|
||||
from app.services.shipping_notice.task_order_field_editor import (
|
||||
current_header_field_values_or_empty,
|
||||
current_line_field_values_or_empty,
|
||||
@@ -42,6 +78,38 @@ EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.
|
||||
_TASK_NO_RE = re.compile(r"SN-\d{8}-[A-F0-9]{8}", re.IGNORECASE)
|
||||
_BUSINESS_NO_RE = re.compile(r"(?<![A-Z0-9])[A-Z]{2,6}\d{8}(?![A-Z0-9])", re.IGNORECASE)
|
||||
|
||||
# 人工复核工作台入口检查点 → todo_category=review;其余 must_human → exception
|
||||
_REVIEW_TODO_CHECKPOINTS = frozenset({
|
||||
CP_PARSE_REVIEW,
|
||||
CP_RSV_REQ,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
})
|
||||
|
||||
_PENDING_TODO_CATEGORIES = frozenset({"review", "exception", "manual_upload"})
|
||||
_TODO_BUCKET_CATEGORIES: dict[str, frozenset[str]] = {
|
||||
"pending": _PENDING_TODO_CATEGORIES,
|
||||
"processing": frozenset({"in_progress"}),
|
||||
"done": frozenset({"done"}),
|
||||
}
|
||||
|
||||
# 建单前人工复核 Case 仍开放写操作的状态(未确认建单)。
|
||||
_OPEN_REVIEW_CASE_STATUSES = frozenset({
|
||||
"unreviewed",
|
||||
"draft",
|
||||
"ready",
|
||||
"quality_issue",
|
||||
"reparse_pending",
|
||||
})
|
||||
|
||||
|
||||
_REVIEW_CASE_STATUS_TODO: dict[str, str] = {
|
||||
"unreviewed": "订单 PDF 待人工复核确认",
|
||||
"draft": "复核草稿待继续编辑",
|
||||
"ready": "复核草稿已就绪,可确认建单",
|
||||
"quality_issue": "复核标记为质量问题,待处置",
|
||||
"reparse_pending": "复核要求重识别,处理中",
|
||||
}
|
||||
|
||||
|
||||
class TaskProjection(str, Enum):
|
||||
"""任务读模型投影:Tool / 工作台列表 / 工作台详情。"""
|
||||
@@ -273,8 +341,8 @@ def list_sorted_batch_tasks(batch: ShippingBatch) -> list[ShippingTask]:
|
||||
|
||||
|
||||
def list_batch_task_summaries(batch: ShippingBatch) -> list[dict[str, Any]]:
|
||||
"""返回批次下已排序任务的摘要投影列表。"""
|
||||
return [serialize_task(item, TaskProjection.SUMMARY) for item in list_sorted_batch_tasks(batch)]
|
||||
"""返回批次下已排序任务的摘要投影列表(含任务中心 enrich 字段)。"""
|
||||
return [serialize_task_summary(item) for item in list_sorted_batch_tasks(batch)]
|
||||
|
||||
|
||||
def compute_batch_process_summary(tasks: list[ShippingTask]) -> dict[str, int]:
|
||||
@@ -750,14 +818,223 @@ def get_conversation_batch_workspace(conversation_id: str, user_id: int) -> dict
|
||||
}
|
||||
|
||||
|
||||
def serialize_task_summary(task: ShippingTask) -> dict[str, Any]:
|
||||
"""工作台任务列表用的 SUMMARY 投影。"""
|
||||
return serialize_task(task, TaskProjection.SUMMARY)
|
||||
def task_todo_category(task: ShippingTask) -> str:
|
||||
"""
|
||||
由 checkpoint_kind + 复核检查点推导待办分类(服务端唯一口径)。
|
||||
|
||||
核心逻辑:complete→done;wait_manual_upload→manual_upload;
|
||||
must_human 且属复核入口→review,其余 must_human→exception;auto_continue→in_progress。
|
||||
|
||||
Returns:
|
||||
review | exception | manual_upload | in_progress | done
|
||||
"""
|
||||
ui = resolve_task_ui_state(task)
|
||||
return _todo_category_from_ui(ui.checkpoint, ui.checkpoint_kind)
|
||||
|
||||
|
||||
def serialize_task_detail(task: ShippingTask) -> dict[str, Any]:
|
||||
"""工作台任务详情用的 DETAIL 投影(含 lines、events 等)。"""
|
||||
return serialize_task(task, TaskProjection.DETAIL)
|
||||
def _todo_category_from_ui(checkpoint: str | None, kind: CheckpointKind) -> str:
|
||||
"""将 checkpoint_kind(及复核入口集合)映射为 todo_category。"""
|
||||
if kind == CheckpointKind.COMPLETE:
|
||||
return "done"
|
||||
if kind == CheckpointKind.WAIT_MANUAL_UPLOAD:
|
||||
return "manual_upload"
|
||||
if kind == CheckpointKind.MUST_HUMAN:
|
||||
if str(checkpoint or "") in _REVIEW_TODO_CHECKPOINTS:
|
||||
return "review"
|
||||
return "exception"
|
||||
return "in_progress"
|
||||
|
||||
|
||||
def _todo_category_from_task_row(
|
||||
row: Any,
|
||||
*,
|
||||
extractions_with_lines: set[int],
|
||||
) -> str:
|
||||
"""
|
||||
用轻量任务行计算 todo_category,避免索引阶段全量 ORM + 订单行 N+1。
|
||||
|
||||
核心逻辑:委托 resolve_task_ui_state_from_fields;has_dynamic_order_lines 查批量集合。
|
||||
"""
|
||||
extraction_id = getattr(row, "current_order_extraction_id", None)
|
||||
has_lines = (
|
||||
extraction_id is not None
|
||||
and int(extraction_id) in extractions_with_lines
|
||||
)
|
||||
ui = resolve_task_ui_state_from_fields(
|
||||
process_status=getattr(row, "process_status", None),
|
||||
review_status=getattr(row, "review_status", None),
|
||||
pending_human_reason=getattr(row, "pending_human_reason", None),
|
||||
shipping_case_id=getattr(row, "shipping_case_id", None),
|
||||
customer_resolution_status=getattr(row, "customer_resolution_status", None),
|
||||
order_snapshot_id=getattr(row, "order_snapshot_id", None),
|
||||
inventory_lines_json=getattr(row, "inventory_lines_json", None),
|
||||
match_status=getattr(row, "match_status", None),
|
||||
export_file_path=getattr(row, "export_file_path", None),
|
||||
has_dynamic_order_lines=has_lines,
|
||||
upload_req_options=[],
|
||||
)
|
||||
return _todo_category_from_ui(ui.checkpoint, ui.checkpoint_kind)
|
||||
|
||||
|
||||
def _extractions_with_accepted_lines(extraction_ids: set[int]) -> set[int]:
|
||||
"""
|
||||
批量返回「已接受且至少有一行」的 extraction_id 集合。
|
||||
|
||||
核心逻辑:两次 IN 查询替代逐任务 get Extraction + first Line。
|
||||
"""
|
||||
if not extraction_ids:
|
||||
return set()
|
||||
accepted_ids = {
|
||||
int(row[0])
|
||||
for row in db.session.query(ShippingOrderExtraction.id).filter(
|
||||
ShippingOrderExtraction.id.in_(tuple(extraction_ids)),
|
||||
ShippingOrderExtraction.status == "accepted",
|
||||
).all()
|
||||
}
|
||||
if not accepted_ids:
|
||||
return set()
|
||||
return {
|
||||
int(row[0])
|
||||
for row in db.session.query(ShippingOrderLine.extraction_id).filter(
|
||||
ShippingOrderLine.extraction_id.in_(tuple(accepted_ids)),
|
||||
).distinct().all()
|
||||
}
|
||||
|
||||
|
||||
def task_can_handle(task: ShippingTask, user_id: int, *, is_admin: bool = False) -> bool:
|
||||
"""
|
||||
判断当前用户是否可对该任务执行写操作。
|
||||
|
||||
核心逻辑:仅创建者可处理(task.user_id == user_id 且非空);
|
||||
user_id IS NULL 一律不可写;管理员代操作首期不开放(他人任务 can_handle=False,
|
||||
若管理员本人是创建者仍可处理)。is_admin 保留供调用方显式传参,不单独绕过归属。
|
||||
|
||||
Args:
|
||||
task: 目标任务。
|
||||
user_id: 当前操作者用户 ID。
|
||||
is_admin: 是否管理员视图;不改变归属判定。
|
||||
|
||||
Returns:
|
||||
是否允许写操作。
|
||||
"""
|
||||
del is_admin # 首期管理员不可代操作;保留参数以对齐 API 契约。
|
||||
return task.user_id is not None and int(task.user_id) == int(user_id)
|
||||
|
||||
|
||||
def _latest_task_event_summary(task: ShippingTask) -> dict[str, Any] | None:
|
||||
"""
|
||||
取任务最近一条 ShippingTaskEvent 摘要;无事件时返回 None。
|
||||
|
||||
核心逻辑:按 created_at/id 降序取一条,投影 event_type / created_at / detail。
|
||||
"""
|
||||
if task.id is None:
|
||||
return None
|
||||
event = (
|
||||
ShippingTaskEvent.query.filter_by(task_id=task.id)
|
||||
.order_by(ShippingTaskEvent.created_at.desc(), ShippingTaskEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
if event is None:
|
||||
return None
|
||||
return {
|
||||
"event_type": event.event_type,
|
||||
"created_at": event.created_at.isoformat() if event.created_at else None,
|
||||
"detail_json": event.detail_json,
|
||||
"actor_id": event.actor_id,
|
||||
}
|
||||
|
||||
|
||||
def _artifact_summary_for_task(task: ShippingTask) -> dict[str, Any] | None:
|
||||
"""
|
||||
投影任务导出 Artifact 摘要(Excel 文件名/路径);无导出时返回 None。
|
||||
|
||||
核心逻辑:优先读任务上的 export_file_*;有路径或文件名即视为有摘要。
|
||||
"""
|
||||
file_name = str(task.export_file_name or "").strip() or None
|
||||
file_path = str(task.export_file_path or "").strip() or None
|
||||
if not file_name and not file_path:
|
||||
return None
|
||||
return {
|
||||
"export_file_name": file_name,
|
||||
"export_file_path": file_path,
|
||||
}
|
||||
|
||||
|
||||
def _enrich_task_center_fields(
|
||||
task: ShippingTask,
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
viewer_user_id: int | None = None,
|
||||
is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为 SUMMARY/DETAIL 投影补充任务中心字段(就地写入并返回 data)。
|
||||
|
||||
核心逻辑:todo_category / created_by 始终写入;viewer 给定时写入 can_handle;
|
||||
recent_event / artifact_summary / ui_state 懒加载同源状态,避免任务中心再推导。
|
||||
|
||||
Args:
|
||||
task: 源任务。
|
||||
data: 已构建的序列化字典。
|
||||
viewer_user_id: 当前查看者;为 None 时省略 can_handle。
|
||||
is_admin: 是否管理员视图(仅影响 can_handle 调用签名,不开放代操作)。
|
||||
|
||||
Returns:
|
||||
同一 data 引用(已 enrich)。
|
||||
"""
|
||||
data["todo_category"] = task_todo_category(task)
|
||||
data["item_kind"] = "task"
|
||||
data["todo_ref"] = task.task_no
|
||||
data["created_by"] = task.user_id
|
||||
if viewer_user_id is not None:
|
||||
data["can_handle"] = task_can_handle(task, int(viewer_user_id), is_admin=is_admin)
|
||||
data["recent_event"] = _latest_task_event_summary(task)
|
||||
data["artifact_summary"] = _artifact_summary_for_task(task)
|
||||
# [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
data["ui_state"] = build_task_ui_state(task)
|
||||
return data
|
||||
|
||||
|
||||
def serialize_task_summary(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
viewer_user_id: int | None = None,
|
||||
is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
工作台任务列表用的 SUMMARY 投影(含任务中心 enrich)。
|
||||
|
||||
Args:
|
||||
task: 源任务。
|
||||
viewer_user_id: 当前查看者;用于 can_handle;缺省时省略该字段。
|
||||
is_admin: 是否管理员视图。
|
||||
"""
|
||||
data = serialize_task(task, TaskProjection.SUMMARY)
|
||||
return _enrich_task_center_fields(
|
||||
task, data, viewer_user_id=viewer_user_id, is_admin=is_admin,
|
||||
)
|
||||
|
||||
|
||||
def serialize_task_detail(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
viewer_user_id: int | None = None,
|
||||
is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
工作台任务详情用的 DETAIL 投影(含 lines、events 与任务中心 enrich)。
|
||||
|
||||
Args:
|
||||
task: 源任务。
|
||||
viewer_user_id: 当前查看者;用于 can_handle。
|
||||
is_admin: 是否管理员视图。
|
||||
"""
|
||||
data = serialize_task(task, TaskProjection.DETAIL)
|
||||
return _enrich_task_center_fields(
|
||||
task, data, viewer_user_id=viewer_user_id, is_admin=is_admin,
|
||||
)
|
||||
|
||||
|
||||
def get_batch_for_user(batch_no: str, user_id: int) -> ShippingBatch | None:
|
||||
@@ -830,7 +1107,10 @@ def list_tasks_for_user(
|
||||
else:
|
||||
q = q.filter(ShippingTask.process_status == process_status)
|
||||
rows = q.order_by(desc(ShippingTask.created_at)).limit(max(1, min(limit, 500))).all()
|
||||
return [serialize_task_summary(c) for c in rows]
|
||||
return [
|
||||
serialize_task_summary(c, viewer_user_id=user_id)
|
||||
for c in rows
|
||||
]
|
||||
|
||||
|
||||
def list_tasks_page_for_user(
|
||||
@@ -887,7 +1167,10 @@ def list_tasks_page_for_user(
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
"items": [serialize_task_summary(item) for item in rows],
|
||||
"items": [
|
||||
serialize_task_summary(item, viewer_user_id=user_id)
|
||||
for item in rows
|
||||
],
|
||||
"page": normalized_page,
|
||||
"page_size": normalized_page_size,
|
||||
"total": total,
|
||||
@@ -895,10 +1178,614 @@ def list_tasks_page_for_user(
|
||||
|
||||
|
||||
def get_task_for_user(task_no: str, user_id: int) -> ShippingTask | None:
|
||||
"""按 task_no 查找任务并校验 user_id 归属。"""
|
||||
"""
|
||||
按 task_no 查找任务并校验写路径归属(严格创建者)。
|
||||
|
||||
核心逻辑:仅当 task.user_id == user_id 时返回;user_id IS NULL 一律拒绝,
|
||||
避免历史无主任务被任意登录用户写入。管理员只读请用 get_task_visible_to_user。
|
||||
"""
|
||||
task = get_task_by_ref(task_no)
|
||||
if not task:
|
||||
return None
|
||||
if task.user_id is not None and task.user_id != user_id:
|
||||
if task.user_id is None or int(task.user_id) != int(user_id):
|
||||
return None
|
||||
return task
|
||||
|
||||
|
||||
def get_task_visible_to_user(
|
||||
task_no: str,
|
||||
user_id: int,
|
||||
*,
|
||||
is_admin: bool = False,
|
||||
) -> ShippingTask | None:
|
||||
"""
|
||||
按 task_no 查找当前用户可见的任务(创建者或管理员只读)。
|
||||
|
||||
核心逻辑:管理员可读全部;普通用户仅可读自己创建且 user_id 非空的任务。
|
||||
写操作仍须经 get_task_for_user / task_can_handle 门禁。
|
||||
|
||||
Args:
|
||||
task_no: 任务编号。
|
||||
user_id: 当前用户。
|
||||
is_admin: 为 True 时允许管理员只读可见。
|
||||
|
||||
Returns:
|
||||
可见任务或 None。
|
||||
"""
|
||||
task = get_task_by_ref(task_no)
|
||||
if not task:
|
||||
return None
|
||||
if is_admin:
|
||||
return task
|
||||
if task.user_id is None or int(task.user_id) != int(user_id):
|
||||
return None
|
||||
return task
|
||||
|
||||
|
||||
def _task_matches_customer_filter(task: ShippingTask, customer: str) -> bool:
|
||||
"""待办列表客户关键字过滤:匹配 case 快照、来源文件名或当前订单头客户名。"""
|
||||
needle = str(customer or "").strip().lower()
|
||||
if not needle:
|
||||
return True
|
||||
case = task.shipping_case
|
||||
candidates: list[str] = []
|
||||
if case is not None:
|
||||
for value in (
|
||||
getattr(case, "customer_name_snapshot", None),
|
||||
getattr(case, "customer_short_code_snapshot", None),
|
||||
):
|
||||
if value:
|
||||
candidates.append(str(value))
|
||||
if task.source_file_name:
|
||||
candidates.append(str(task.source_file_name))
|
||||
header = current_header_field_values_or_empty(task)
|
||||
for key in ("customer_name", "bill_to_customer", "ship_to_customer", "customer_code"):
|
||||
value = header.get(key)
|
||||
if value:
|
||||
candidates.append(str(value))
|
||||
return any(needle in item.lower() for item in candidates)
|
||||
|
||||
|
||||
def _visible_tasks_query_for_todos(user_id: int, *, is_admin: bool = False):
|
||||
"""构造「我的待办」可见任务基础查询(活跃生命周期)。"""
|
||||
q = ShippingTask.query.filter(
|
||||
ShippingTask.deleted_at.is_(None),
|
||||
ShippingTask.lifecycle_status == "active",
|
||||
)
|
||||
if not is_admin:
|
||||
# 待办中心拒绝无主任务;仅创建者可见。
|
||||
q = q.filter(ShippingTask.user_id == user_id)
|
||||
return q
|
||||
|
||||
|
||||
def _visible_open_review_cases_query(user_id: int, *, is_admin: bool = False):
|
||||
"""
|
||||
构造建单前开放 Review Case 查询(尚未确认建单)。
|
||||
|
||||
核心逻辑:排除已确认/非订单/已替代 Case;非管理员仅 owner_user_id==user_id。
|
||||
"""
|
||||
q = ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.status.in_(tuple(_OPEN_REVIEW_CASE_STATUSES)),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
)
|
||||
if not is_admin:
|
||||
q = q.filter(ShippingOrderReviewCase.owner_user_id == int(user_id))
|
||||
return q
|
||||
|
||||
|
||||
def serialize_review_case_todo(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
viewer_user_id: int | None = None,
|
||||
is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将建单前 Review Case 投影为「我的待办」列表项,供打开人工复核深链。
|
||||
|
||||
核心逻辑:附带 review_run_no / review_case_no / owner_agent_id / conversation_id;
|
||||
todo_category 固定 review;entry_surface=review_workbench。
|
||||
|
||||
Args:
|
||||
case: 开放中的 Review Case。
|
||||
viewer_user_id: 当前查看者;用于 can_handle。
|
||||
is_admin: 是否管理员视图(不开放代操作)。
|
||||
|
||||
Returns:
|
||||
与任务 SUMMARY 兼容的待办字典。
|
||||
"""
|
||||
del is_admin
|
||||
run = db.session.get(ShippingOrderExtractionRun, case.run_id) if case.run_id else None
|
||||
document = db.session.get(ShippingNoticeDocument, case.document_id) if case.document_id else None
|
||||
source_name = None
|
||||
if document is not None:
|
||||
source_name = str(getattr(document, "filename", None) or "").strip() or None
|
||||
current_todo = _REVIEW_CASE_STATUS_TODO.get(str(case.status), "订单 PDF 待人工复核")
|
||||
can_handle = (
|
||||
viewer_user_id is not None
|
||||
and case.owner_user_id is not None
|
||||
and int(case.owner_user_id) == int(viewer_user_id)
|
||||
)
|
||||
run_no = str(getattr(run, "run_no", None) or "").strip() or None
|
||||
conversation_id = str(getattr(run, "conversation_id", None) or "").strip() or None
|
||||
owner_agent_id = getattr(run, "owner_agent_id", None)
|
||||
item: dict[str, Any] = {
|
||||
"item_kind": "review_case",
|
||||
"todo_ref": case.case_no,
|
||||
"task_no": None,
|
||||
"todo_category": "review",
|
||||
"review_run_no": run_no,
|
||||
"review_case_no": case.case_no,
|
||||
"review_case_status": case.status,
|
||||
"conversation_id": conversation_id,
|
||||
"owner_agent_id": int(owner_agent_id) if owner_agent_id is not None else None,
|
||||
"created_by": case.owner_user_id,
|
||||
"source_file_name": source_name,
|
||||
"customer_name": None,
|
||||
"process_status": None,
|
||||
"updated_at": case.updated_at.isoformat() if case.updated_at else None,
|
||||
"created_at": case.created_at.isoformat() if case.created_at else None,
|
||||
"ui_state": {
|
||||
"checkpoint": "order_review",
|
||||
"checkpoint_kind": str(CheckpointKind.MUST_HUMAN),
|
||||
"action_buttons": [],
|
||||
"summary": {
|
||||
"title": "待人工复核",
|
||||
"message": current_todo,
|
||||
"stage": "待人工复核",
|
||||
"checkpoint_kind": str(CheckpointKind.MUST_HUMAN),
|
||||
"current_todo": current_todo,
|
||||
"pause_reason": current_todo,
|
||||
"pause_reason_code": f"review_case_{case.status}",
|
||||
"next_auto_step": None,
|
||||
"event_at": case.updated_at.isoformat() if case.updated_at else None,
|
||||
"entry_surface": "review_workbench",
|
||||
"allowed_actions": [],
|
||||
"issues": [],
|
||||
"error_message": None,
|
||||
},
|
||||
},
|
||||
}
|
||||
if viewer_user_id is not None:
|
||||
item["can_handle"] = can_handle
|
||||
return item
|
||||
|
||||
|
||||
def _todo_category_sql_filter(allowed: frozenset[str]):
|
||||
"""
|
||||
将待办类别粗筛下推到 SQL,缩小活跃任务读取面。
|
||||
|
||||
核心逻辑:与 task_todo_category 对齐的保守 OR;精确分类由 _task_todo_category_sql_expr 完成。
|
||||
"""
|
||||
clauses = []
|
||||
if "done" in allowed:
|
||||
clauses.append(ShippingTask.process_status.in_(("uploaded", "closed", "rejected")))
|
||||
if "manual_upload" in allowed:
|
||||
clauses.append(
|
||||
db.or_(
|
||||
ShippingTask.process_status.in_(("waiting_upload", "upload_failed")),
|
||||
ShippingTask.export_file_path.isnot(None),
|
||||
)
|
||||
)
|
||||
if "review" in allowed:
|
||||
clauses.append(
|
||||
db.or_(
|
||||
ShippingTask.process_status == "pending_review",
|
||||
ShippingTask.review_status.isnot(None),
|
||||
)
|
||||
)
|
||||
if "exception" in allowed:
|
||||
clauses.append(ShippingTask.pending_human_reason.isnot(None))
|
||||
if "in_progress" in allowed:
|
||||
clauses.append(
|
||||
ShippingTask.process_status.in_(
|
||||
("created", "parsed", "matched", "inventory_ready")
|
||||
)
|
||||
)
|
||||
if not clauses:
|
||||
return None
|
||||
return db.or_(*clauses)
|
||||
|
||||
|
||||
def _task_has_dynamic_order_lines_sql():
|
||||
"""
|
||||
SQL 版「已接受 Extraction 且至少有一行」。
|
||||
|
||||
核心逻辑:关联 EXISTS,对齐 _task_has_dynamic_order_lines,供分类 CASE 复用。
|
||||
"""
|
||||
return exists(
|
||||
select(1)
|
||||
.select_from(ShippingOrderExtraction)
|
||||
.where(
|
||||
ShippingOrderExtraction.id == ShippingTask.current_order_extraction_id,
|
||||
ShippingOrderExtraction.status == "accepted",
|
||||
exists(
|
||||
select(1)
|
||||
.select_from(ShippingOrderLine)
|
||||
.where(ShippingOrderLine.extraction_id == ShippingOrderExtraction.id)
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _sql_json_falsy(column):
|
||||
"""JSON 列在 Python 中视为假值的 SQL 近似(None / [] / {})。"""
|
||||
return db.or_(column.is_(None), column == [], column == {})
|
||||
|
||||
|
||||
def _sql_str_blank(column):
|
||||
"""字符串列空白:NULL 或空串。"""
|
||||
return db.or_(column.is_(None), column == "")
|
||||
|
||||
|
||||
def _task_todo_category_sql_expr():
|
||||
"""
|
||||
将 resolve_task_ui_state_from_fields 同序映射为 todo_category SQL CASE。
|
||||
|
||||
核心逻辑:分支顺序与状态机一致;直接产出 review|exception|manual_upload|in_progress|done,
|
||||
供 UNION 分页与徽标 COUNT 在数据库内过滤,避免轻量全量索引。
|
||||
"""
|
||||
has_lines = _task_has_dynamic_order_lines_sql()
|
||||
reason = ShippingTask.pending_human_reason
|
||||
return case(
|
||||
(ShippingTask.process_status == "uploaded", literal("done")),
|
||||
(ShippingTask.process_status == "closed", literal("done")),
|
||||
(
|
||||
db.or_(
|
||||
ShippingTask.process_status == "rejected",
|
||||
ShippingTask.review_status == RS_REJECTED,
|
||||
),
|
||||
literal("done"),
|
||||
),
|
||||
(
|
||||
db.or_(reason == PH_RSV_REQ, ShippingTask.review_status == RS_RSV_REQ),
|
||||
literal("review"),
|
||||
),
|
||||
(
|
||||
db.or_(reason == PH_LOW_CONF, ShippingTask.review_status == RS_PARSE_REVIEW),
|
||||
literal("review"),
|
||||
),
|
||||
(reason == PH_NOTICE_TEXT_EXTRACTION_FAILED, literal("review")),
|
||||
(
|
||||
db.and_(
|
||||
ShippingTask.shipping_case_id.isnot(None),
|
||||
db.or_(
|
||||
ShippingTask.customer_resolution_status.is_(None),
|
||||
ShippingTask.customer_resolution_status != "confirmed",
|
||||
),
|
||||
),
|
||||
literal("exception"),
|
||||
),
|
||||
(
|
||||
db.and_(ShippingTask.order_snapshot_id.is_(None), has_lines),
|
||||
literal("in_progress"),
|
||||
),
|
||||
(reason == PH_RPA_EXHAUSTED, literal("exception")),
|
||||
(
|
||||
db.and_(
|
||||
ShippingTask.process_status == "parsed",
|
||||
_sql_str_blank(ShippingTask.review_status),
|
||||
_sql_str_blank(reason),
|
||||
_sql_json_falsy(ShippingTask.inventory_lines_json),
|
||||
),
|
||||
literal("in_progress"),
|
||||
),
|
||||
(
|
||||
db.and_(
|
||||
ShippingTask.process_status == "inventory_ready",
|
||||
_sql_str_blank(ShippingTask.review_status),
|
||||
_sql_str_blank(reason),
|
||||
_sql_str_blank(ShippingTask.match_status),
|
||||
has_lines,
|
||||
),
|
||||
literal("in_progress"),
|
||||
),
|
||||
(
|
||||
db.and_(
|
||||
ShippingTask.process_status == "matched",
|
||||
ShippingTask.export_file_path.isnot(None),
|
||||
),
|
||||
literal("manual_upload"),
|
||||
),
|
||||
(ShippingTask.process_status == "matched", literal("in_progress")),
|
||||
(reason == PH_INV_UNAVAIL, literal("exception")),
|
||||
(reason == PH_INVENTORY_SOURCE_UNRESOLVED, literal("exception")),
|
||||
(
|
||||
db.or_(reason == PH_SHORTAGE, ShippingTask.review_status == RS_SHORTAGE_REVIEW),
|
||||
literal("exception"),
|
||||
),
|
||||
(
|
||||
db.or_(
|
||||
reason == PH_UPLOAD_RPA_FAILED,
|
||||
ShippingTask.process_status == "upload_failed",
|
||||
),
|
||||
literal("exception"),
|
||||
),
|
||||
(reason == PH_UPLOAD_RESULT_UNKNOWN, literal("exception")),
|
||||
(reason == PH_RPA_PENDING, literal("exception")),
|
||||
(
|
||||
db.or_(
|
||||
reason == PH_UPLOAD_RPA_PENDING,
|
||||
ShippingTask.process_status == "waiting_upload",
|
||||
),
|
||||
literal("exception"),
|
||||
),
|
||||
else_=literal("in_progress"),
|
||||
)
|
||||
|
||||
|
||||
def _todo_sort_key_from_dt(value: Any, ref: str) -> tuple[str, str]:
|
||||
"""待办排序键:updated_at 降序 + 稳定引用(测试/调试辅助)。"""
|
||||
if hasattr(value, "isoformat"):
|
||||
stamp = value.isoformat()
|
||||
else:
|
||||
stamp = str(value or "")
|
||||
return (stamp, str(ref or ""))
|
||||
|
||||
|
||||
def _apply_review_case_customer_filter(cases_q, *, customer_needle: str, customer_like: str):
|
||||
"""对开放 Review Case 查询追加客户关键字过滤。"""
|
||||
if not customer_needle:
|
||||
return cases_q
|
||||
matching_document_ids = db.session.query(ShippingNoticeDocument.id).filter(
|
||||
ShippingNoticeDocument.filename.ilike(customer_like),
|
||||
)
|
||||
matching_candidate_ids = db.session.query(ShippingNoticeCandidate.id).filter(
|
||||
ShippingNoticeCandidate.po_number.ilike(customer_like),
|
||||
)
|
||||
return cases_q.filter(
|
||||
db.or_(
|
||||
ShippingOrderReviewCase.case_no.ilike(customer_like),
|
||||
ShippingOrderReviewCase.document_id.in_(matching_document_ids),
|
||||
ShippingOrderReviewCase.candidate_id.in_(matching_candidate_ids),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _todo_tasks_base_query(
|
||||
user_id: int,
|
||||
*,
|
||||
is_admin: bool,
|
||||
allowed: frozenset[str],
|
||||
normalized_bucket: str,
|
||||
customer_needle: str,
|
||||
customer_like: str,
|
||||
task_no: str | None,
|
||||
):
|
||||
"""
|
||||
构造带粗筛 + 精确 category CASE 过滤的 Task 待办查询。
|
||||
|
||||
核心逻辑:可见性 / 客户 / bucket 粗筛后,用 _task_todo_category_sql_expr().in_(allowed)。
|
||||
"""
|
||||
q = _visible_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||||
if task_no:
|
||||
q = q.filter(ShippingTask.task_no == str(task_no).strip())
|
||||
if customer_needle:
|
||||
q = q.outerjoin(ShippingCase, ShippingCase.id == ShippingTask.shipping_case_id).filter(
|
||||
db.or_(
|
||||
ShippingCase.customer_name_snapshot.ilike(customer_like),
|
||||
ShippingCase.customer_short_code_snapshot.ilike(customer_like),
|
||||
ShippingTask.source_file_name.ilike(customer_like),
|
||||
)
|
||||
)
|
||||
category_clause = _todo_category_sql_filter(allowed)
|
||||
if category_clause is not None:
|
||||
q = q.filter(category_clause)
|
||||
if normalized_bucket in {"pending", "processing"}:
|
||||
q = q.filter(
|
||||
db.or_(
|
||||
ShippingTask.pending_human_reason.isnot(None),
|
||||
ShippingTask.review_status.isnot(None),
|
||||
ShippingTask.export_file_path.isnot(None),
|
||||
ShippingTask.process_status.in_(
|
||||
(
|
||||
"pending_review",
|
||||
"matched",
|
||||
"waiting_upload",
|
||||
"upload_failed",
|
||||
"parsed",
|
||||
"inventory_ready",
|
||||
"created",
|
||||
)
|
||||
),
|
||||
)
|
||||
)
|
||||
elif normalized_bucket == "done":
|
||||
q = q.filter(
|
||||
ShippingTask.process_status.in_(("uploaded", "closed", "rejected"))
|
||||
)
|
||||
return q.filter(_task_todo_category_sql_expr().in_(tuple(sorted(allowed))))
|
||||
|
||||
|
||||
def _active_todo_tasks_scope(user_id: int, *, is_admin: bool = False):
|
||||
"""徽标统计用的活跃 Task 粗筛范围(不含 done)。"""
|
||||
return _visible_tasks_query_for_todos(user_id, is_admin=is_admin).filter(
|
||||
db.or_(
|
||||
ShippingTask.pending_human_reason.isnot(None),
|
||||
ShippingTask.review_status.isnot(None),
|
||||
ShippingTask.export_file_path.isnot(None),
|
||||
ShippingTask.process_status.in_(
|
||||
(
|
||||
"pending_review",
|
||||
"matched",
|
||||
"waiting_upload",
|
||||
"upload_failed",
|
||||
"parsed",
|
||||
"inventory_ready",
|
||||
"created",
|
||||
)
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def list_my_todos(
|
||||
user_id: int,
|
||||
*,
|
||||
bucket: str = "pending",
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
is_admin: bool = False,
|
||||
todo_category: str | None = None,
|
||||
customer: str | None = None,
|
||||
task_no: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
分页列出「我的待办」:建单前 Review Case + 建单后 Task 异常/上传。
|
||||
|
||||
核心逻辑:pending 桶合并开放 Review Case(todo_category=review,含 review_run_no 深链);
|
||||
Task 分类下推为与状态机同序的 SQL CASE;两端 UNION ALL 后数据库 COUNT + OFFSET/LIMIT,
|
||||
仅水合当前页 id(禁止 limit(500) 截断冒充总数)。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户。
|
||||
bucket: pending(review|exception|manual_upload)| processing | done。
|
||||
page / page_size: 分页参数。
|
||||
is_admin: 管理员全局只读视图。
|
||||
todo_category: 可选细分类覆盖 bucket。
|
||||
customer: 客户名/代码/来源文件名/Case 号/PO 模糊过滤(Task 与 Review Case 均参与)。
|
||||
task_no: 精确任务号过滤(仅 Task 项;复核项忽略)。
|
||||
|
||||
Returns:
|
||||
{items, page, page_size, total}
|
||||
"""
|
||||
normalized_page = max(1, int(page))
|
||||
normalized_page_size = max(1, min(int(page_size), 100))
|
||||
normalized_bucket = str(bucket or "pending").strip().lower()
|
||||
allowed = _TODO_BUCKET_CATEGORIES.get(normalized_bucket, _PENDING_TODO_CATEGORIES)
|
||||
if todo_category:
|
||||
cat = str(todo_category).strip().lower()
|
||||
allowed = frozenset({cat}) if cat in {
|
||||
"review", "exception", "manual_upload", "in_progress", "done",
|
||||
} else allowed
|
||||
|
||||
customer_needle = str(customer or "").strip()
|
||||
customer_like = f"%{customer_needle}%" if customer_needle else ""
|
||||
include_review_cases = "review" in allowed and not task_no
|
||||
|
||||
# [STEP 1] 两端投影为统一列:kind / entity_id / sort_at / sort_ref。
|
||||
branches = []
|
||||
if include_review_cases:
|
||||
cases_q = _apply_review_case_customer_filter(
|
||||
_visible_open_review_cases_query(user_id, is_admin=is_admin),
|
||||
customer_needle=customer_needle,
|
||||
customer_like=customer_like,
|
||||
)
|
||||
branches.append(
|
||||
cases_q.with_entities(
|
||||
literal("review_case").label("kind"),
|
||||
ShippingOrderReviewCase.id.label("entity_id"),
|
||||
ShippingOrderReviewCase.updated_at.label("sort_at"),
|
||||
ShippingOrderReviewCase.case_no.label("sort_ref"),
|
||||
)
|
||||
)
|
||||
|
||||
tasks_q = _todo_tasks_base_query(
|
||||
user_id,
|
||||
is_admin=is_admin,
|
||||
allowed=allowed,
|
||||
normalized_bucket=normalized_bucket,
|
||||
customer_needle=customer_needle,
|
||||
customer_like=customer_like,
|
||||
task_no=task_no,
|
||||
)
|
||||
branches.append(
|
||||
tasks_q.with_entities(
|
||||
literal("task").label("kind"),
|
||||
ShippingTask.id.label("entity_id"),
|
||||
func.coalesce(ShippingTask.updated_at, ShippingTask.created_at).label("sort_at"),
|
||||
ShippingTask.task_no.label("sort_ref"),
|
||||
)
|
||||
)
|
||||
|
||||
# [STEP 2] UNION ALL → COUNT 真总数 → OFFSET/LIMIT 仅取当前页引用。
|
||||
if len(branches) == 1:
|
||||
union_stmt = branches[0].order_by(None).statement
|
||||
else:
|
||||
union_stmt = union_all(*[branch.order_by(None).statement for branch in branches])
|
||||
combined = union_stmt.subquery("todo_union")
|
||||
total = int(
|
||||
db.session.execute(select(func.count()).select_from(combined)).scalar_one() or 0
|
||||
)
|
||||
offset = (normalized_page - 1) * normalized_page_size
|
||||
page_refs = (
|
||||
db.session.execute(
|
||||
select(combined.c.kind, combined.c.entity_id)
|
||||
.order_by(desc(combined.c.sort_at), desc(combined.c.sort_ref), desc(combined.c.entity_id))
|
||||
.offset(offset)
|
||||
.limit(normalized_page_size)
|
||||
).all()
|
||||
if total and offset < total
|
||||
else []
|
||||
)
|
||||
|
||||
# [STEP 3] 仅水合当前页 ORM 并按 UNION 顺序序列化。
|
||||
page_case_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "review_case"]
|
||||
page_task_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "task"]
|
||||
cases_by_id: dict[int, ShippingOrderReviewCase] = {}
|
||||
if page_case_ids:
|
||||
for case in ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.id.in_(page_case_ids),
|
||||
).all():
|
||||
cases_by_id[int(case.id)] = case
|
||||
tasks_by_id: dict[int, ShippingTask] = {}
|
||||
if page_task_ids:
|
||||
for task in ShippingTask.query.filter(ShippingTask.id.in_(page_task_ids)).all():
|
||||
tasks_by_id[int(task.id)] = task
|
||||
|
||||
page_rows: list[dict[str, Any]] = []
|
||||
for kind, entity_id in page_refs:
|
||||
entity_id_int = int(entity_id)
|
||||
if kind == "review_case":
|
||||
case = cases_by_id.get(entity_id_int)
|
||||
if case is None:
|
||||
continue
|
||||
page_rows.append(
|
||||
serialize_review_case_todo(
|
||||
case, viewer_user_id=user_id, is_admin=is_admin,
|
||||
)
|
||||
)
|
||||
continue
|
||||
task = tasks_by_id.get(entity_id_int)
|
||||
if task is None:
|
||||
continue
|
||||
page_rows.append(
|
||||
serialize_task_summary(task, viewer_user_id=user_id, is_admin=is_admin)
|
||||
)
|
||||
|
||||
return {
|
||||
"items": page_rows,
|
||||
"page": normalized_page,
|
||||
"page_size": normalized_page_size,
|
||||
"total": total,
|
||||
}
|
||||
|
||||
|
||||
def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]:
|
||||
"""
|
||||
统计「我的待办」各 bucket 数量,供导航徽标使用。
|
||||
|
||||
核心逻辑:开放 Review Case 计入 pending;Task 用 SQL CASE 分类后 COUNT,
|
||||
不扫描全量 ORM 行。
|
||||
|
||||
Returns:
|
||||
{pending, processing, done, total_pending_badge}
|
||||
"""
|
||||
pending = _visible_open_review_cases_query(user_id, is_admin=is_admin).count()
|
||||
category_expr = _task_todo_category_sql_expr()
|
||||
active = _active_todo_tasks_scope(user_id, is_admin=is_admin)
|
||||
pending += (
|
||||
active.filter(category_expr.in_(tuple(sorted(_PENDING_TODO_CATEGORIES)))).count()
|
||||
)
|
||||
processing = active.filter(category_expr == "in_progress").count()
|
||||
done = (
|
||||
_visible_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||||
.filter(ShippingTask.process_status.in_(("uploaded", "closed", "rejected")))
|
||||
.filter(category_expr == "done")
|
||||
.count()
|
||||
)
|
||||
return {
|
||||
"pending": pending,
|
||||
"processing": processing,
|
||||
"done": done,
|
||||
"total_pending_badge": pending,
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/standard_field_registry.py
|
||||
|
||||
用途:注册货代订单系统标准字段目录(锁定 57 项)及 Snapshot 核心投影元数据。
|
||||
依赖:shipping_order_snapshot ORM 列、order_freeze_service 投影表。
|
||||
逻辑:字段资产种子与治理校验只读本注册表;扩展字段不得占用标准 field_code;
|
||||
typed 项必须能投影到 Snapshot 物理列。启动/测试可调用 assert_registry_consistent。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
from app.models.shipping_order_snapshot import ShippingOrderSnapshot, ShippingOrderSnapshotLine
|
||||
from app.services.shipping_notice.order_freeze_service import (
|
||||
HEADER_FIELD_PROJECTIONS,
|
||||
LINE_FIELD_PROJECTIONS,
|
||||
)
|
||||
|
||||
StorageMode = Literal['typed_column', 'json_only']
|
||||
FieldScope = Literal['header', 'line']
|
||||
ValueType = Literal['string', 'decimal', 'integer', 'date', 'boolean', 'enum']
|
||||
|
||||
# 默认 Schema 族编码(本轮 UI/运行唯一启用)。
|
||||
DEFAULT_SCHEMA_FAMILY_CODE = 'STANDARD_SHIPPING_NOTICE'
|
||||
DEFAULT_SCHEMA_FAMILY_NAME = '标准发货通知'
|
||||
|
||||
# 首发建议采用集(C4);迁移不自动发布,仅供 UI/API 辅助勾选。
|
||||
DEFAULT_V1_ADOPTION_CODES: tuple[str, ...] = (
|
||||
'customer_po_number',
|
||||
'bill_to_customer',
|
||||
'bill_to_address',
|
||||
'ship_to_customer',
|
||||
'ship_to_address',
|
||||
'currency',
|
||||
'line_no',
|
||||
'part_number',
|
||||
'customer_part_number',
|
||||
'required_date',
|
||||
'qty',
|
||||
'uom',
|
||||
'line_amount_with_tax',
|
||||
'reservation_id',
|
||||
'inventory_source_hint',
|
||||
)
|
||||
|
||||
# 履约核心能力仅允许绑定的标准表身字段。
|
||||
FULFILLMENT_CORE_FIELD_CODES: frozenset[str] = frozenset({'part_number', 'reservation_id', 'qty'})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StandardFieldSpec:
|
||||
"""单条系统标准字段的不可变注册项。"""
|
||||
|
||||
field_code: str
|
||||
scope: FieldScope
|
||||
value_type: ValueType
|
||||
display_name: str
|
||||
semantic_description: str
|
||||
storage_mode: StorageMode
|
||||
storage_column: str | None = None
|
||||
fulfillment_role: str | None = None
|
||||
|
||||
|
||||
def _typed(scope: FieldScope, field_code: str) -> tuple[StorageMode, str | None]:
|
||||
"""按冻结投影表判定标准字段是否双写强类型列。"""
|
||||
projections = HEADER_FIELD_PROJECTIONS if scope == 'header' else LINE_FIELD_PROJECTIONS
|
||||
column = projections.get(field_code)
|
||||
if column:
|
||||
return 'typed_column', column
|
||||
return 'json_only', None
|
||||
|
||||
|
||||
def _spec(
|
||||
field_code: str,
|
||||
scope: FieldScope,
|
||||
value_type: ValueType,
|
||||
display_name: str,
|
||||
semantic_description: str,
|
||||
*,
|
||||
fulfillment_role: str | None = None,
|
||||
) -> StandardFieldSpec:
|
||||
"""组装标准字段注册项并自动标注存储模式。"""
|
||||
storage_mode, storage_column = _typed(scope, field_code)
|
||||
return StandardFieldSpec(
|
||||
field_code=field_code,
|
||||
scope=scope,
|
||||
value_type=value_type,
|
||||
display_name=display_name,
|
||||
semantic_description=semantic_description,
|
||||
storage_mode=storage_mode,
|
||||
storage_column=storage_column,
|
||||
fulfillment_role=fulfillment_role,
|
||||
)
|
||||
|
||||
|
||||
# [STEP 1] 锁定的 57 项标准目录(与历史 STANDARD_ORDER_FIELD_SPECS 编码/范围/类型一致)。
|
||||
_STANDARD_FIELD_SPECS: tuple[StandardFieldSpec, ...] = (
|
||||
_spec('customer_po_number', 'header', 'string', '客户 PO 号', '客户下达的采购订单标识;不得填写内部 ERP 单号'),
|
||||
_spec('order_date', 'header', 'date', '订单日期', '客户订单或发货通知上的订单日期'),
|
||||
_spec('source_order_number', 'header', 'string', '来源单号', '客户或上游系统的来源单据号'),
|
||||
_spec('contract_number', 'header', 'string', '合同号', '商务合同或框架协议编号'),
|
||||
_spec('order_type', 'header', 'string', '订单类型', '订单业务类型分类'),
|
||||
_spec('sales_channel', 'header', 'string', '销售渠道', '订单销售或交付渠道'),
|
||||
_spec('customer_code', 'header', 'string', '客户编码', '客户侧或外部系统客户编码'),
|
||||
_spec('customer_name', 'header', 'string', '客户名称', '客户法定或常用名称'),
|
||||
_spec('bill_to_customer', 'header', 'string', '账款客户', '账单/账款对象客户名称'),
|
||||
_spec('bill_to_address', 'header', 'string', '账款地址', '账单/账款地址'),
|
||||
_spec('ship_to_customer', 'header', 'string', '送货客户', '收货方客户名称'),
|
||||
_spec('ship_to_address', 'header', 'string', '送货地址', '收货地址'),
|
||||
_spec('end_customer', 'header', 'string', '最终客户', '终端使用客户'),
|
||||
_spec('customer_contact', 'header', 'string', '客户联系人', '订单相关联系人'),
|
||||
_spec('ship_from_organization', 'header', 'string', '发货组织', '发货组织或交付组织'),
|
||||
_spec('destination', 'header', 'string', '目的地', '交付目的地或口岸'),
|
||||
_spec('currency', 'header', 'string', '币种', '金额币种'),
|
||||
_spec('incoterm', 'header', 'string', '贸易条款', '国际贸易术语'),
|
||||
_spec('payment_term', 'header', 'string', '付款条款', '付款条件'),
|
||||
_spec('mark_number', 'header', 'string', '唛头', '包装唛头标识'),
|
||||
_spec('direct_ship_required', 'header', 'boolean', '是否直发', '是否要求直发'),
|
||||
_spec('urgent_order', 'header', 'boolean', '是否紧急', '是否紧急订单'),
|
||||
_spec('order_remark', 'header', 'string', '订单备注', '订单头备注'),
|
||||
_spec('line_no', 'line', 'string', '项次', '订单明细行号'),
|
||||
_spec('reservation_id', 'line', 'string', '预约单号', '库存占用/预约单标识', fulfillment_role='reservation_identity'),
|
||||
_spec('part_number', 'line', 'string', '内部料号', '公司内部主料号,用于库存匹配', fulfillment_role='part_number'),
|
||||
_spec('product_revision', 'line', 'string', '产品版本', '产品料号版本/revision'),
|
||||
_spec('customer_part_number', 'line', 'string', '客户料号', '客户侧物料编码'),
|
||||
_spec('customer_po_line_no', 'line', 'string', '客户 PO 行号', '客户采购订单行号'),
|
||||
_spec('product_feature', 'line', 'string', '产品特征', '产品特征或规格摘要'),
|
||||
_spec('qty', 'line', 'decimal', '数量', '本行需求数量,须大于 0', fulfillment_role='quantity'),
|
||||
_spec('uom', 'line', 'string', '单位', '数量计量单位'),
|
||||
_spec('reference_qty', 'line', 'decimal', '参考数量', '参考计量数量'),
|
||||
_spec('reference_uom', 'line', 'string', '参考单位', '参考计量单位'),
|
||||
_spec('pricing_qty', 'line', 'decimal', '计价数量', '计价用数量'),
|
||||
_spec('pricing_uom', 'line', 'string', '计价单位', '计价用单位'),
|
||||
_spec('required_date', 'line', 'date', '要求送货日期', '要求交货/送货日期'),
|
||||
_spec('requested_receipt_date', 'line', 'date', '要求收货日期', '要求收货日期'),
|
||||
_spec('unit_price', 'line', 'decimal', '单价', '行单价'),
|
||||
_spec('line_amount_before_tax', 'line', 'decimal', '未税金额', '行未税金额'),
|
||||
_spec('line_tax_amount', 'line', 'decimal', '税额', '行税额'),
|
||||
_spec('line_amount_with_tax', 'line', 'decimal', '含税金额', '行含税金额'),
|
||||
_spec('tax_category', 'line', 'string', '税种', '税分类'),
|
||||
_spec('tax_rate', 'line', 'decimal', '税率', '适用税率'),
|
||||
_spec('ship_from_site', 'line', 'string', '发货站点', '发货站点或库房线索'),
|
||||
_spec('line_ship_to_address', 'line', 'string', '行送货地址', '明细级送货地址'),
|
||||
_spec('requested_warehouse_code', 'line', 'string', '请求仓库', '客户或业务请求仓库编码'),
|
||||
_spec('storage_location_code', 'line', 'string', '库位编码', '库存库位编码'),
|
||||
_spec('lot_number', 'line', 'string', '批次号', '物料批次'),
|
||||
_spec('inventory_source_hint', 'line', 'string', '库存源线索', '可选库存路由线索', fulfillment_role='inventory_source_hint'),
|
||||
_spec('partial_delivery_allowed', 'line', 'boolean', '允许部分交货', '是否允许分批发货'),
|
||||
_spec('bonded_flag', 'line', 'boolean', '保税标记', '是否保税'),
|
||||
_spec('package_type', 'line', 'string', '包装类型', '包装方式'),
|
||||
_spec('project_code', 'line', 'string', '项目编码', '项目号'),
|
||||
_spec('wbs_code', 'line', 'string', 'WBS 编码', 'WBS 结构编码'),
|
||||
_spec('activity_code', 'line', 'string', '活动编码', '项目活动编码'),
|
||||
_spec('line_remark', 'line', 'string', '行备注', '明细备注'),
|
||||
)
|
||||
|
||||
STANDARD_FIELD_SPECS: dict[str, StandardFieldSpec] = {
|
||||
item.field_code: item for item in _STANDARD_FIELD_SPECS
|
||||
}
|
||||
|
||||
# 兼容旧服务中 (scope, value_type) 二元组查询。
|
||||
STANDARD_ORDER_FIELD_SPECS: dict[str, tuple[str, str]] = {
|
||||
code: (spec.scope, spec.value_type) for code, spec in STANDARD_FIELD_SPECS.items()
|
||||
}
|
||||
|
||||
|
||||
def standard_field_codes() -> frozenset[str]:
|
||||
"""返回全部标准 field_code 集合。"""
|
||||
return frozenset(STANDARD_FIELD_SPECS)
|
||||
|
||||
|
||||
def is_standard_field_code(field_code: str) -> bool:
|
||||
"""判断编码是否属于锁定的系统标准目录。"""
|
||||
return str(field_code or '').strip().lower() in STANDARD_FIELD_SPECS
|
||||
|
||||
|
||||
def get_standard_field(field_code: str) -> StandardFieldSpec | None:
|
||||
"""按编码读取标准字段注册项。"""
|
||||
return STANDARD_FIELD_SPECS.get(str(field_code or '').strip().lower())
|
||||
|
||||
|
||||
def assert_registry_consistent() -> None:
|
||||
"""
|
||||
校验注册表内部一致性及与 Snapshot ORM / 冻结投影的对齐。
|
||||
|
||||
Raises:
|
||||
AssertionError: 数量不为 57、typed 列缺失、或投影键不在标准目录中。
|
||||
"""
|
||||
# [STEP 1] 锁定数量与唯一性
|
||||
assert len(STANDARD_FIELD_SPECS) == 57, f'expected 57 standard fields, got {len(STANDARD_FIELD_SPECS)}'
|
||||
assert len(_STANDARD_FIELD_SPECS) == 57
|
||||
header_count = sum(1 for item in _STANDARD_FIELD_SPECS if item.scope == 'header')
|
||||
line_count = sum(1 for item in _STANDARD_FIELD_SPECS if item.scope == 'line')
|
||||
assert header_count == 23 and line_count == 34
|
||||
|
||||
# [STEP 2] typed 投影列必须存在于 Snapshot ORM
|
||||
header_columns = {column.key for column in ShippingOrderSnapshot.__table__.columns}
|
||||
line_columns = {column.key for column in ShippingOrderSnapshotLine.__table__.columns}
|
||||
for spec in _STANDARD_FIELD_SPECS:
|
||||
if spec.storage_mode != 'typed_column':
|
||||
continue
|
||||
assert spec.storage_column, f'{spec.field_code} typed without column'
|
||||
table_cols = header_columns if spec.scope == 'header' else line_columns
|
||||
assert spec.storage_column in table_cols, (
|
||||
f'{spec.field_code} maps to missing column {spec.storage_column}'
|
||||
)
|
||||
|
||||
# [STEP 3] 冻结投影表的每个键都必须是标准字段
|
||||
for code in HEADER_FIELD_PROJECTIONS:
|
||||
assert code in STANDARD_FIELD_SPECS and STANDARD_FIELD_SPECS[code].scope == 'header'
|
||||
for code in LINE_FIELD_PROJECTIONS:
|
||||
assert code in STANDARD_FIELD_SPECS and STANDARD_FIELD_SPECS[code].scope == 'line'
|
||||
|
||||
# [STEP 4] 建议采用集与履约核心均落在标准目录
|
||||
for code in DEFAULT_V1_ADOPTION_CODES:
|
||||
assert code in STANDARD_FIELD_SPECS
|
||||
for code in FULFILLMENT_CORE_FIELD_CODES:
|
||||
assert code in STANDARD_FIELD_SPECS and STANDARD_FIELD_SPECS[code].scope == 'line'
|
||||
@@ -1,13 +1,15 @@
|
||||
"""
|
||||
services/shipping_notice/state_machine.py
|
||||
|
||||
用途:发货通知人工节点(checkpoint)与动作按钮的单一注册表,负责任务 DB 字段与 UI 状态的映射。
|
||||
用途:发货通知检查点(checkpoint)与工作台动作按钮的单一注册表,负责任务 DB 字段与 UI 状态映射。
|
||||
依赖:models.ShippingTask、constants(CP_*/PH_*/RS_*)、rpa_attempts、order_field_purposes。
|
||||
逻辑:tools.py 通过 apply_task_transition 写库并返回 checkpoint;ui_state.py 与历史兼容模块都从本文件读取按钮/状态;新增人工节点时仅改本文件与测试;
|
||||
是否具备可匹配订单行经锁定 Extraction 的 FieldValue 判断。
|
||||
逻辑:tools/workspace 经 apply_task_transition 写库;ui_state/query_service 读取 checkpoint_kind 与按钮;
|
||||
resolve_task_ui_state_from_fields 供待办轻量索引批量分类;履约写操作入口为任务处理工作台,
|
||||
Chat 仅通知与跳转(Chat Turn 写路径已标记废弃)。
|
||||
|
||||
扩展说明(开发者):
|
||||
- checkpoint id 即 API `checkpoint` / Dify `flow_ckpt`
|
||||
- checkpoint_kind 区分 auto_continue / must_human / wait_manual_upload / complete
|
||||
- 动作按钮 id 定义于 ACTION_SPECS;DB 写入统一走 TaskTransition
|
||||
- GET /tools/checkpoint-catalog 供文档/CI,不接入 Dify 画布
|
||||
"""
|
||||
@@ -56,6 +58,10 @@ from app.services.shipping_notice.constants import (
|
||||
RS_RSV_REQ,
|
||||
RS_SHORTAGE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
inventory_rpa_attempts,
|
||||
max_rpa_inventory_attempts,
|
||||
)
|
||||
|
||||
|
||||
def _task_has_dynamic_order_lines(task: ShippingTask) -> bool:
|
||||
@@ -67,13 +73,24 @@ def _task_has_dynamic_order_lines(task: ShippingTask) -> bool:
|
||||
if extraction is None or extraction.status != "accepted":
|
||||
return False
|
||||
return ShippingOrderLine.query.filter_by(extraction_id=extraction.id).first() is not None
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
inventory_rpa_attempts,
|
||||
max_rpa_inventory_attempts,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Action buttons (id → label / message / variant)
|
||||
# Checkpoint kind(STP 检查点分类;不写入 DB,由注册表静态映射)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class CheckpointKind(StrEnum):
|
||||
"""STP 检查点分类:自动可继续 / 必须人工 / 待人工上传 / 完成。"""
|
||||
|
||||
AUTO_CONTINUE = "auto_continue"
|
||||
MUST_HUMAN = "must_human"
|
||||
WAIT_MANUAL_UPLOAD = "wait_manual_upload"
|
||||
COMPLETE = "complete"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Action buttons (id → label / message / variant) — 任务处理工作台动作目录
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
ACTION_SPECS: dict[str, dict[str, str]] = {
|
||||
@@ -88,6 +105,11 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
|
||||
"retry_resolve_inventory_source": {"label": "重新判断", "message": "重新判断库存查询来源", "variant": "secondary"},
|
||||
"refresh": {"label": "刷新", "message": "刷新", "variant": "secondary"},
|
||||
"retry_upload": {"label": "重试上传", "message": "重试上传货代", "variant": "secondary"},
|
||||
"upload_inventory_file": {
|
||||
"label": "上传库存文件",
|
||||
"message": "上传库存 Excel",
|
||||
"variant": "primary",
|
||||
},
|
||||
"download_excel": {"label": "下载 Excel", "message": "下载发货 Excel", "variant": "secondary"},
|
||||
"generate_excel": {"label": "生成发货 Excel", "message": "生成发货 Excel", "variant": "primary"},
|
||||
"mark_manual_uploaded": {
|
||||
@@ -107,7 +129,7 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
|
||||
},
|
||||
}
|
||||
|
||||
# checkpoint id → default human option ids (HTTP / Dify before task reload)
|
||||
# checkpoint id → default human option ids
|
||||
CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
|
||||
CP_PARSE_REVIEW: ("confirm", "reject", "reparse"),
|
||||
CP_CUSTOMER_REVIEW: ("confirm_customer",),
|
||||
@@ -133,6 +155,29 @@ CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
|
||||
CP_COMPLETED: (),
|
||||
}
|
||||
|
||||
# checkpoint id → STP kind(静态;无 checkpoint 时视为 auto_continue)
|
||||
CHECKPOINT_KIND_REGISTRY: dict[str, CheckpointKind] = {
|
||||
CP_PARSE_REVIEW: CheckpointKind.MUST_HUMAN,
|
||||
CP_CUSTOMER_REVIEW: CheckpointKind.MUST_HUMAN,
|
||||
CP_UPLOAD_REQ: CheckpointKind.MUST_HUMAN,
|
||||
CP_INVENTORY_PENDING: CheckpointKind.AUTO_CONTINUE,
|
||||
CP_INVENTORY_SOURCE_REVIEW: CheckpointKind.MUST_HUMAN,
|
||||
CP_ORDER_FREEZE: CheckpointKind.AUTO_CONTINUE,
|
||||
CP_RSV_REQ: CheckpointKind.MUST_HUMAN,
|
||||
RS_SHORTAGE_REVIEW: CheckpointKind.MUST_HUMAN,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED: CheckpointKind.MUST_HUMAN,
|
||||
CP_UPLOAD_FAILED: CheckpointKind.MUST_HUMAN,
|
||||
CP_WAITING_UPLOAD: CheckpointKind.MUST_HUMAN,
|
||||
CP_UPLOAD_RESULT_UNKNOWN: CheckpointKind.MUST_HUMAN,
|
||||
CP_READY_MATCH: CheckpointKind.AUTO_CONTINUE,
|
||||
CP_READY_EXPORT: CheckpointKind.AUTO_CONTINUE,
|
||||
CP_EXPORT_READY: CheckpointKind.WAIT_MANUAL_UPLOAD,
|
||||
CP_EXPORT_GENERATED: CheckpointKind.WAIT_MANUAL_UPLOAD,
|
||||
CP_REJECTED: CheckpointKind.COMPLETE,
|
||||
CP_UPLOADED: CheckpointKind.COMPLETE,
|
||||
CP_COMPLETED: CheckpointKind.COMPLETE,
|
||||
}
|
||||
|
||||
ALL_CHECKPOINT_IDS: frozenset[str] = frozenset(CHECKPOINT_REGISTRY.keys())
|
||||
ALL_ACTION_IDS: frozenset[str] = frozenset(ACTION_SPECS.keys())
|
||||
|
||||
@@ -143,8 +188,11 @@ OPTIONS_RPA_OR_UPLOAD: tuple[str, ...] = ("upload_inventory_file", "retry_rpa")
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TaskUiState:
|
||||
"""统一任务 UI 状态:checkpoint + STP kind + 工作台可用动作。"""
|
||||
|
||||
checkpoint: str | None
|
||||
human_options: list[str] | None
|
||||
checkpoint_kind: CheckpointKind = CheckpointKind.AUTO_CONTINUE
|
||||
|
||||
@property
|
||||
def action_buttons(self) -> list[dict[str, str]]:
|
||||
@@ -164,11 +212,31 @@ def build_action_buttons(option_ids: list[str] | None) -> list[dict[str, str]]:
|
||||
return buttons
|
||||
|
||||
|
||||
def checkpoint_kind_for(checkpoint: str | None) -> CheckpointKind:
|
||||
"""
|
||||
按 checkpoint id 解析 STP 检查点分类。
|
||||
|
||||
核心逻辑:查 CHECKPOINT_KIND_REGISTRY;无 checkpoint(系统推进中)视为 auto_continue。
|
||||
"""
|
||||
if not checkpoint:
|
||||
return CheckpointKind.AUTO_CONTINUE
|
||||
return CHECKPOINT_KIND_REGISTRY.get(str(checkpoint).strip(), CheckpointKind.MUST_HUMAN)
|
||||
|
||||
|
||||
def _task_ui_state(checkpoint: str | None, human_options: list[str] | None) -> TaskUiState:
|
||||
"""构造带 checkpoint_kind 的 TaskUiState。"""
|
||||
return TaskUiState(
|
||||
checkpoint=checkpoint,
|
||||
human_options=human_options,
|
||||
checkpoint_kind=checkpoint_kind_for(checkpoint),
|
||||
)
|
||||
|
||||
|
||||
def inventory_source_action_buttons(task: ShippingTask) -> list[dict[str, str]]:
|
||||
"""
|
||||
将库存源候选项转成聊天区可直接点击的确认按钮。
|
||||
将库存源候选项转成工作台可直接点击的确认按钮。
|
||||
|
||||
核心逻辑:库存源待确认时,按钮必须携带 source_code,前端点击后可直接调用确认接口并触发 RPA,
|
||||
核心逻辑:库存源待确认时,按钮必须携带 source_code,前端点击后可直接调用确认接口,
|
||||
避免先把候选源文本发给 Agent 再等待二次确认。
|
||||
"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
@@ -222,7 +290,7 @@ def ui_state_for_checkpoint(checkpoint: str | None) -> TaskUiState:
|
||||
cp = str(checkpoint).strip() if checkpoint else None
|
||||
if cp and cp not in CHECKPOINT_REGISTRY:
|
||||
cp = None
|
||||
return TaskUiState(checkpoint=cp, human_options=options)
|
||||
return _task_ui_state(cp, options)
|
||||
|
||||
|
||||
def upload_req_options_for_task(task: ShippingTask) -> list[str]:
|
||||
@@ -249,133 +317,138 @@ def human_options_for_task_or_checkpoint(
|
||||
return human_options_for_checkpoint(checkpoint)
|
||||
|
||||
|
||||
def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
|
||||
def resolve_task_ui_state_from_fields(
|
||||
*,
|
||||
process_status: str | None,
|
||||
review_status: str | None,
|
||||
pending_human_reason: str | None,
|
||||
shipping_case_id: int | None,
|
||||
customer_resolution_status: str | None,
|
||||
order_snapshot_id: int | None,
|
||||
inventory_lines_json: Any,
|
||||
match_status: str | None,
|
||||
export_file_path: str | None,
|
||||
has_dynamic_order_lines: bool,
|
||||
upload_req_options: list[str] | None = None,
|
||||
upload_req_task: ShippingTask | None = None,
|
||||
) -> TaskUiState:
|
||||
"""
|
||||
将 ShippingTask DB 字段映射为 checkpoint + human_options,供统一 UI State 读模型消费。
|
||||
由任务标量字段映射 checkpoint / checkpoint_kind(无 ORM、无额外查询)。
|
||||
|
||||
核心逻辑:终态 → 正向流程节点 → pending_human_reason 分支 → 默认 None。
|
||||
核心逻辑:与 resolve_task_ui_state 同序分支;has_dynamic_order_lines 由调用方批量预计算,
|
||||
供待办索引在不全量水合 Task 时保持与单任务路径一致的分类口径。
|
||||
upload_req_options / upload_req_task 仅在命中 upload_req 分支时解析按钮列表。
|
||||
"""
|
||||
|
||||
def _upload_opts() -> list[str]:
|
||||
if upload_req_options is not None:
|
||||
return list(upload_req_options)
|
||||
if upload_req_task is not None:
|
||||
return upload_req_options_for_task(upload_req_task)
|
||||
return list(CHECKPOINT_REGISTRY[CP_UPLOAD_REQ])
|
||||
|
||||
# [STEP 1] 终态:已上传、已关闭、已驳回 — 无可用按钮。
|
||||
if task.process_status == "uploaded":
|
||||
return TaskUiState(checkpoint=CP_UPLOADED, human_options=[])
|
||||
if task.process_status == "closed":
|
||||
return TaskUiState(checkpoint=CP_COMPLETED, human_options=[])
|
||||
if process_status == "uploaded":
|
||||
return _task_ui_state(CP_UPLOADED, [])
|
||||
if process_status == "closed":
|
||||
return _task_ui_state(CP_COMPLETED, [])
|
||||
|
||||
if task.process_status == "rejected" or task.review_status == "rejected":
|
||||
return TaskUiState(checkpoint=CP_REJECTED, human_options=[])
|
||||
if process_status == "rejected" or review_status == "rejected":
|
||||
return _task_ui_state(CP_REJECTED, [])
|
||||
|
||||
# [STEP 2] 先完成订单解析复核,再暴露客户确认节点。
|
||||
reason = task.pending_human_reason
|
||||
if reason == PH_RSV_REQ or task.review_status == RS_RSV_REQ:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_RSV_REQ,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_RSV_REQ]),
|
||||
)
|
||||
if reason == PH_LOW_CONF or task.review_status == RS_PARSE_REVIEW:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_PARSE_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_PARSE_REVIEW]),
|
||||
)
|
||||
reason = pending_human_reason
|
||||
if reason == PH_RSV_REQ or review_status == RS_RSV_REQ:
|
||||
return _task_ui_state(CP_RSV_REQ, list(CHECKPOINT_REGISTRY[CP_RSV_REQ]))
|
||||
if reason == PH_LOW_CONF or review_status == RS_PARSE_REVIEW:
|
||||
return _task_ui_state(CP_PARSE_REVIEW, list(CHECKPOINT_REGISTRY[CP_PARSE_REVIEW]))
|
||||
if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_NOTICE_TEXT_EXTRACTION_FAILED]),
|
||||
return _task_ui_state(
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
list(CHECKPOINT_REGISTRY[CP_NOTICE_TEXT_EXTRACTION_FAILED]),
|
||||
)
|
||||
|
||||
if task.shipping_case_id is not None and task.customer_resolution_status != "confirmed":
|
||||
return TaskUiState(
|
||||
checkpoint=CP_CUSTOMER_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_CUSTOMER_REVIEW]),
|
||||
)
|
||||
if shipping_case_id is not None and customer_resolution_status != "confirmed":
|
||||
return _task_ui_state(CP_CUSTOMER_REVIEW, list(CHECKPOINT_REGISTRY[CP_CUSTOMER_REVIEW]))
|
||||
|
||||
# [STEP 3] 库存、Excel 与上传只能消费冻结快照;冻结动作始终在 Chat Turn 执行。
|
||||
if not task.order_snapshot_id and _task_has_dynamic_order_lines(task):
|
||||
return TaskUiState(
|
||||
checkpoint=CP_ORDER_FREEZE,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_ORDER_FREEZE]),
|
||||
)
|
||||
# [STEP 3] 库存、Excel 与上传只能消费冻结快照;冻结由自动推进或任务工作台执行。
|
||||
if not order_snapshot_id and has_dynamic_order_lines:
|
||||
return _task_ui_state(CP_ORDER_FREEZE, list(CHECKPOINT_REGISTRY[CP_ORDER_FREEZE]))
|
||||
|
||||
# [STEP 4] 客户确认并冻结订单后,才进入库存和履约节点。
|
||||
if reason == PH_RPA_EXHAUSTED:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
human_options=upload_req_options_for_task(task),
|
||||
)
|
||||
return _task_ui_state(CP_UPLOAD_REQ, _upload_opts())
|
||||
|
||||
if (
|
||||
task.process_status == "parsed"
|
||||
and not task.review_status
|
||||
and not task.pending_human_reason
|
||||
and not task.inventory_lines_json
|
||||
process_status == "parsed"
|
||||
and not review_status
|
||||
and not pending_human_reason
|
||||
and not inventory_lines_json
|
||||
):
|
||||
return TaskUiState(
|
||||
checkpoint=CP_INVENTORY_PENDING,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_INVENTORY_PENDING]),
|
||||
)
|
||||
return _task_ui_state(CP_INVENTORY_PENDING, list(CHECKPOINT_REGISTRY[CP_INVENTORY_PENDING]))
|
||||
|
||||
if (
|
||||
task.process_status == "inventory_ready"
|
||||
and not task.review_status
|
||||
and not task.pending_human_reason
|
||||
and not task.match_status
|
||||
and bool(_task_has_dynamic_order_lines(task))
|
||||
process_status == "inventory_ready"
|
||||
and not review_status
|
||||
and not pending_human_reason
|
||||
and not match_status
|
||||
and has_dynamic_order_lines
|
||||
):
|
||||
return TaskUiState(
|
||||
checkpoint=CP_READY_MATCH,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_READY_MATCH]),
|
||||
)
|
||||
return _task_ui_state(CP_READY_MATCH, list(CHECKPOINT_REGISTRY[CP_READY_MATCH]))
|
||||
|
||||
# [STEP 4] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel。
|
||||
if task.process_status == "matched":
|
||||
if task.export_file_path:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_EXPORT_READY,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_EXPORT_READY]),
|
||||
)
|
||||
return TaskUiState(
|
||||
checkpoint=CP_READY_EXPORT,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_READY_EXPORT]),
|
||||
)
|
||||
# [STEP 5] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel(STP 停点)。
|
||||
if process_status == "matched":
|
||||
if export_file_path:
|
||||
return _task_ui_state(CP_EXPORT_READY, list(CHECKPOINT_REGISTRY[CP_EXPORT_READY]))
|
||||
return _task_ui_state(CP_READY_EXPORT, list(CHECKPOINT_REGISTRY[CP_READY_EXPORT]))
|
||||
|
||||
# [STEP 5] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。
|
||||
# [STEP 6] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。
|
||||
if reason == PH_INV_UNAVAIL:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
human_options=upload_req_options_for_task(task),
|
||||
)
|
||||
return _task_ui_state(CP_UPLOAD_REQ, _upload_opts())
|
||||
if reason == PH_INVENTORY_SOURCE_UNRESOLVED:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_INVENTORY_SOURCE_REVIEW]),
|
||||
)
|
||||
if reason == PH_SHORTAGE or task.review_status == RS_SHORTAGE_REVIEW:
|
||||
return TaskUiState(
|
||||
checkpoint=RS_SHORTAGE_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[RS_SHORTAGE_REVIEW]),
|
||||
)
|
||||
if reason == PH_UPLOAD_RPA_FAILED or task.process_status == "upload_failed":
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_FAILED,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_UPLOAD_FAILED]),
|
||||
return _task_ui_state(
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
list(CHECKPOINT_REGISTRY[CP_INVENTORY_SOURCE_REVIEW]),
|
||||
)
|
||||
if reason == PH_SHORTAGE or review_status == RS_SHORTAGE_REVIEW:
|
||||
return _task_ui_state(RS_SHORTAGE_REVIEW, list(CHECKPOINT_REGISTRY[RS_SHORTAGE_REVIEW]))
|
||||
if reason == PH_UPLOAD_RPA_FAILED or process_status == "upload_failed":
|
||||
return _task_ui_state(CP_UPLOAD_FAILED, list(CHECKPOINT_REGISTRY[CP_UPLOAD_FAILED]))
|
||||
if reason == PH_UPLOAD_RESULT_UNKNOWN:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_RESULT_UNKNOWN,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_UPLOAD_RESULT_UNKNOWN]),
|
||||
return _task_ui_state(
|
||||
CP_UPLOAD_RESULT_UNKNOWN,
|
||||
list(CHECKPOINT_REGISTRY[CP_UPLOAD_RESULT_UNKNOWN]),
|
||||
)
|
||||
if reason == PH_RPA_PENDING or (
|
||||
task.process_status == "waiting_inventory" and reason == PH_RPA_PENDING
|
||||
process_status == "waiting_inventory" and reason == PH_RPA_PENDING
|
||||
):
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
human_options=upload_req_options_for_task(task),
|
||||
)
|
||||
if reason == PH_UPLOAD_RPA_PENDING or task.process_status == "waiting_upload":
|
||||
return TaskUiState(
|
||||
checkpoint=CP_WAITING_UPLOAD,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_WAITING_UPLOAD]),
|
||||
)
|
||||
return TaskUiState(checkpoint=None, human_options=None)
|
||||
return _task_ui_state(CP_UPLOAD_REQ, _upload_opts())
|
||||
if reason == PH_UPLOAD_RPA_PENDING or process_status == "waiting_upload":
|
||||
return _task_ui_state(CP_WAITING_UPLOAD, list(CHECKPOINT_REGISTRY[CP_WAITING_UPLOAD]))
|
||||
return _task_ui_state(None, None)
|
||||
|
||||
|
||||
def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
|
||||
"""
|
||||
将 ShippingTask DB 字段映射为 checkpoint + checkpoint_kind + human_options。
|
||||
|
||||
核心逻辑:委托 resolve_task_ui_state_from_fields;订单行动态存在性按需查库;
|
||||
upload_req 按钮仅在命中对应分支时惰性解析(兼容测试用轻量 stub)。
|
||||
履约写操作由任务处理工作台消费 action_buttons;Chat 不再作为写入口。
|
||||
"""
|
||||
return resolve_task_ui_state_from_fields(
|
||||
process_status=task.process_status,
|
||||
review_status=task.review_status,
|
||||
pending_human_reason=task.pending_human_reason,
|
||||
shipping_case_id=task.shipping_case_id,
|
||||
customer_resolution_status=task.customer_resolution_status,
|
||||
order_snapshot_id=task.order_snapshot_id,
|
||||
inventory_lines_json=task.inventory_lines_json,
|
||||
match_status=task.match_status,
|
||||
export_file_path=task.export_file_path,
|
||||
has_dynamic_order_lines=_task_has_dynamic_order_lines(task),
|
||||
upload_req_task=task,
|
||||
)
|
||||
|
||||
|
||||
def checkpoint_for_task(task: ShippingTask) -> str | None:
|
||||
@@ -396,6 +469,7 @@ def build_checkpoint_catalog() -> dict[str, Any]:
|
||||
checkpoints.append(
|
||||
{
|
||||
"id": checkpoint_id,
|
||||
"checkpoint_kind": str(checkpoint_kind_for(checkpoint_id)),
|
||||
"human_options": list(option_ids),
|
||||
"action_buttons": buttons,
|
||||
}
|
||||
@@ -403,6 +477,7 @@ def build_checkpoint_catalog() -> dict[str, Any]:
|
||||
return {
|
||||
"checkpoints": checkpoints,
|
||||
"action_specs": ACTION_SPECS,
|
||||
"checkpoint_kinds": {k: str(v) for k, v in CHECKPOINT_KIND_REGISTRY.items()},
|
||||
"dify_fallback": {
|
||||
cp: build_action_buttons(list(opts)) for cp, opts in CHECKPOINT_REGISTRY.items()
|
||||
},
|
||||
@@ -410,12 +485,17 @@ def build_checkpoint_catalog() -> dict[str, Any]:
|
||||
|
||||
|
||||
def validate_registry() -> list[str]:
|
||||
"""校验 CHECKPOINT_REGISTRY 中 action id 是否均存在于 ACTION_SPECS;测试用。"""
|
||||
"""校验 CHECKPOINT_REGISTRY 动作完整性与 KIND 覆盖;测试用。"""
|
||||
errors: list[str] = []
|
||||
for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items():
|
||||
for option_id in option_ids:
|
||||
if option_id not in ACTION_SPECS:
|
||||
errors.append(f"checkpoint {checkpoint_id}: unknown action id {option_id!r}")
|
||||
if checkpoint_id not in CHECKPOINT_KIND_REGISTRY:
|
||||
errors.append(f"checkpoint {checkpoint_id}: missing checkpoint_kind")
|
||||
for checkpoint_id in CHECKPOINT_KIND_REGISTRY:
|
||||
if checkpoint_id not in CHECKPOINT_REGISTRY:
|
||||
errors.append(f"checkpoint_kind {checkpoint_id}: not in CHECKPOINT_REGISTRY")
|
||||
return errors
|
||||
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ def current_order_field_display(task: ShippingTask) -> dict[str, Any]:
|
||||
extraction = _current_extraction(task)
|
||||
global_sequences = {
|
||||
str(field.field_code): int(field.display_sequence or 0)
|
||||
for field in ShippingOrderField.query.filter_by(schema_id=extraction.schema_version.schema_id).all()
|
||||
for field in ShippingOrderField.query.all()
|
||||
}
|
||||
fields = sorted(
|
||||
[
|
||||
|
||||
@@ -253,14 +253,32 @@ def build_task_action_event_detail(
|
||||
return detail
|
||||
|
||||
|
||||
def log_task_event(task: ShippingTask, event_type: str, detail: dict[str, Any] | None = None) -> None:
|
||||
"""写入 ShippingTaskEvent 审计记录(task 尚未 flush 时自动 flush)。"""
|
||||
def log_task_event(
|
||||
task: ShippingTask,
|
||||
event_type: str,
|
||||
detail: dict[str, Any] | None = None,
|
||||
*,
|
||||
actor_id: int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
写入 ShippingTaskEvent 审计记录(task 尚未 flush 时自动 flush)。
|
||||
|
||||
核心逻辑:actor_id 为 None 表示系统动作(STP auto_progress / orchestrator);
|
||||
人工动作传入真实用户 ID。detail 可含 source=system|workspace_api|tool_api 等。
|
||||
|
||||
Args:
|
||||
task: 目标任务。
|
||||
event_type: 事件类型码。
|
||||
detail: 结构化明细;可含 source。
|
||||
actor_id: 操作者用户 ID;系统事件传 None。
|
||||
"""
|
||||
if task.id is None:
|
||||
db.session.flush()
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=task.id,
|
||||
event_type=event_type,
|
||||
detail_json=detail or {},
|
||||
actor_id=actor_id,
|
||||
))
|
||||
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
"""
|
||||
services/shipping_notice/ui_state.py
|
||||
|
||||
用途:发货通知任务/批次 UI 状态读模型,作为 Chat 按钮、步骤条与工作台的统一状态来源。
|
||||
用途:发货通知任务/批次 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。
|
||||
依赖:models.ShippingTask/ShippingBatch、state_machine、query_service、constants。
|
||||
逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/action_buttons,再补充七步流程与用户可读摘要;
|
||||
文件解析阶段额外汇总 summary.issues(解析复核 / RSV / 库存源门禁 + parse warnings)。
|
||||
逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/checkpoint_kind/action_buttons,
|
||||
再补充七步流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口);
|
||||
批次 UI 仅作会话上传集合摘要,不作为履约写操作面。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,6 +15,8 @@ from typing import Any
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_COMPLETED,
|
||||
CP_CUSTOMER_REVIEW,
|
||||
CP_EXPORT_GENERATED,
|
||||
CP_EXPORT_READY,
|
||||
CP_INVENTORY_PENDING,
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
@@ -47,6 +50,7 @@ from app.services.shipping_notice.query_service import (
|
||||
serialize_task_summary,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
CheckpointKind,
|
||||
inventory_source_action_buttons,
|
||||
resolve_task_ui_state,
|
||||
)
|
||||
@@ -90,6 +94,38 @@ _BLOCKED_CHECKPOINTS = {
|
||||
CP_UPLOAD_REQ,
|
||||
CP_UPLOAD_FAILED,
|
||||
CP_UPLOAD_RESULT_UNKNOWN,
|
||||
CP_CUSTOMER_REVIEW,
|
||||
CP_EXPORT_READY,
|
||||
CP_EXPORT_GENERATED,
|
||||
}
|
||||
|
||||
_REVIEW_ENTRY_CHECKPOINTS = {
|
||||
CP_PARSE_REVIEW,
|
||||
CP_RSV_REQ,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
}
|
||||
|
||||
_NEXT_AUTO_STEP_BY_CHECKPOINT: dict[str, str] = {
|
||||
CP_INVENTORY_PENDING: "ensure_inventory",
|
||||
CP_ORDER_FREEZE: "freeze_order",
|
||||
CP_READY_MATCH: "match_inventory",
|
||||
CP_READY_EXPORT: "generate_excel",
|
||||
}
|
||||
|
||||
_PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = {
|
||||
CP_PARSE_REVIEW: ("parse_review_required", "解析结果需要人工确认"),
|
||||
CP_RSV_REQ: ("rsv_required", "缺少后续匹配必需字段"),
|
||||
CP_CUSTOMER_REVIEW: ("customer_ambiguous", "客户未唯一确认"),
|
||||
CP_UPLOAD_REQ: ("inventory_unavailable", "需要提供库存数据或重试库存获取"),
|
||||
CP_INVENTORY_SOURCE_REVIEW: ("inventory_source_unresolved", "库存源尚未唯一确定"),
|
||||
CP_ORDER_FREEZE: ("order_freeze_pending", "订单待冻结后进入库存履约"),
|
||||
RS_SHORTAGE_REVIEW: ("shortage", "库存存在缺口"),
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("notice_text_extraction_failed", "通知文本解析失败"),
|
||||
CP_UPLOAD_FAILED: ("upload_failed", "货代上传失败"),
|
||||
CP_UPLOAD_RESULT_UNKNOWN: ("upload_result_unknown", "货代上传结果未知"),
|
||||
CP_WAITING_UPLOAD: ("waiting_upload", "等待货代上传结果"),
|
||||
CP_EXPORT_READY: ("wait_manual_upload", "Excel 已生成,待人工上传并提交凭据"),
|
||||
CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,待人工上传并提交凭据"),
|
||||
}
|
||||
|
||||
|
||||
@@ -276,20 +312,67 @@ def _collect_parse_stage_issues(task: ShippingTask, checkpoint: str | None) -> l
|
||||
return issues
|
||||
|
||||
|
||||
def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str, Any]:
|
||||
"""输出用户可读任务摘要,供 Chat 文案与工作台卡片复用。"""
|
||||
def _entry_surface_for(checkpoint: str | None, kind: CheckpointKind) -> str:
|
||||
"""
|
||||
解析当前操作应进入的工作台类型。
|
||||
|
||||
Returns:
|
||||
review_workbench | task_workbench | none
|
||||
"""
|
||||
if kind == CheckpointKind.COMPLETE:
|
||||
return "none"
|
||||
if str(checkpoint or "") in _REVIEW_ENTRY_CHECKPOINTS:
|
||||
return "review_workbench"
|
||||
if kind in {CheckpointKind.MUST_HUMAN, CheckpointKind.WAIT_MANUAL_UPLOAD}:
|
||||
return "task_workbench"
|
||||
if kind == CheckpointKind.AUTO_CONTINUE and checkpoint in {
|
||||
CP_ORDER_FREEZE,
|
||||
CP_READY_MATCH,
|
||||
CP_READY_EXPORT,
|
||||
CP_INVENTORY_PENDING,
|
||||
}:
|
||||
# 自动链可继续,但仍允许工作台手动兜底
|
||||
return "task_workbench"
|
||||
return "none"
|
||||
|
||||
|
||||
def _current_todo_label(checkpoint: str | None, action_buttons: list[dict[str, str]]) -> str | None:
|
||||
"""从当前动作按钮推导「当前待办」文案;无人工动作时返回 None。"""
|
||||
if not action_buttons:
|
||||
pause = _PAUSE_REASON_BY_CHECKPOINT.get(str(checkpoint or ""))
|
||||
return pause[1] if pause else None
|
||||
primary = next((b for b in action_buttons if b.get("variant") == "primary"), action_buttons[0])
|
||||
label = str(primary.get("label") or "").strip()
|
||||
return label or None
|
||||
|
||||
|
||||
def _build_task_summary(
|
||||
task: ShippingTask,
|
||||
checkpoint: str | None,
|
||||
*,
|
||||
checkpoint_kind: CheckpointKind,
|
||||
action_buttons: list[dict[str, str]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
输出可解释任务摘要,供通知卡、人工复核与任务工作台同源消费。
|
||||
|
||||
核心逻辑:保留 title/message/issues;补充 stage、checkpoint_kind、current_todo、
|
||||
pause_reason、next_auto_step、event_at、entry_surface、allowed_actions。
|
||||
"""
|
||||
title = user_facing_task_stage(task)
|
||||
message_by_checkpoint: dict[str, str] = {
|
||||
CP_PARSE_REVIEW: "解析结果需要人工确认后才能继续。",
|
||||
CP_RSV_REQ: "发货通知缺少后续匹配必需字段,请补充或重新上传。",
|
||||
CP_CUSTOMER_REVIEW: "客户尚未唯一确认,请在任务处理中选择标准客户。",
|
||||
CP_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。",
|
||||
CP_INVENTORY_PENDING: "发货通知已就绪,等待库存数据。",
|
||||
CP_INVENTORY_PENDING: "发货通知已就绪,系统将自动准备库存数据。",
|
||||
CP_INVENTORY_SOURCE_REVIEW: "库存源尚未确定,请先选择正式库存源。",
|
||||
CP_ORDER_FREEZE: "订单已复核,冻结订单后才能进入库存履约。",
|
||||
CP_ORDER_FREEZE: "订单已复核,系统将自动冻结后进入库存履约。",
|
||||
RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。",
|
||||
CP_READY_MATCH: "库存已就绪,可以继续执行匹配。",
|
||||
CP_READY_EXPORT: "库存匹配已满足发货条件,可以生成发货文件。",
|
||||
CP_EXPORT_READY: "发货文件已生成,可以下载或确认上传。",
|
||||
CP_READY_MATCH: "库存已就绪,系统将自动执行匹配。",
|
||||
CP_READY_EXPORT: "库存匹配已满足发货条件,系统将自动生成发货文件。",
|
||||
CP_EXPORT_READY: "发货文件已生成,请下载并在货代系统上传后提交截图/PDF 凭据。",
|
||||
CP_EXPORT_GENERATED: "发货文件已生成,请下载并在货代系统上传后提交截图/PDF 凭据。",
|
||||
CP_WAITING_UPLOAD: "系统正在等待货代上传结果。",
|
||||
CP_UPLOAD_FAILED: "货代上传失败,需要重试或手工确认。",
|
||||
CP_REJECTED: "任务已驳回,无需继续处理。",
|
||||
@@ -297,11 +380,34 @@ def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str,
|
||||
CP_COMPLETED: "任务已关闭。",
|
||||
}
|
||||
issues = _collect_parse_stage_issues(task, checkpoint)
|
||||
pause = _PAUSE_REASON_BY_CHECKPOINT.get(str(checkpoint or ""))
|
||||
pause_reason_code = pause[0] if pause else (task.pending_human_reason or None)
|
||||
pause_reason = pause[1] if pause else (task.error_message or task.upload_error_message or None)
|
||||
if checkpoint_kind == CheckpointKind.AUTO_CONTINUE:
|
||||
pause_reason = None
|
||||
pause_reason_code = None
|
||||
allowed_actions = [str(btn.get("id")) for btn in action_buttons if btn.get("id")]
|
||||
event_at = None
|
||||
if task.updated_at is not None:
|
||||
event_at = task.updated_at.isoformat()
|
||||
return {
|
||||
"title": title,
|
||||
"message": message_by_checkpoint.get(str(checkpoint or ""), title),
|
||||
"error_message": task.error_message or task.upload_error_message,
|
||||
"issues": issues,
|
||||
"stage": title,
|
||||
"checkpoint_kind": str(checkpoint_kind),
|
||||
"current_todo": _current_todo_label(checkpoint, action_buttons),
|
||||
"pause_reason": pause_reason,
|
||||
"pause_reason_code": pause_reason_code,
|
||||
"next_auto_step": (
|
||||
_NEXT_AUTO_STEP_BY_CHECKPOINT.get(str(checkpoint or ""))
|
||||
if checkpoint_kind == CheckpointKind.AUTO_CONTINUE
|
||||
else None
|
||||
),
|
||||
"event_at": event_at,
|
||||
"entry_surface": _entry_surface_for(checkpoint, checkpoint_kind),
|
||||
"allowed_actions": allowed_actions,
|
||||
}
|
||||
|
||||
|
||||
@@ -309,8 +415,8 @@ def build_task_ui_state(task: ShippingTask) -> dict[str, Any]:
|
||||
"""
|
||||
构建单票任务 UI State。
|
||||
|
||||
核心逻辑:所有 UI 入口只消费这里输出的 checkpoint/action_buttons/step,避免 Chat、顶部步骤条、
|
||||
右侧工作台分别推导状态导致不一致。
|
||||
核心逻辑:所有 UI 入口只消费这里输出的 checkpoint/checkpoint_kind/action_buttons/summary,
|
||||
禁止 Chat、通知卡与任务中心分别推导状态。
|
||||
"""
|
||||
ui = resolve_task_ui_state(task)
|
||||
action_buttons = _action_buttons_for_task(task)
|
||||
@@ -321,13 +427,19 @@ def build_task_ui_state(task: ShippingTask) -> dict[str, Any]:
|
||||
"task_no": task.task_no,
|
||||
"batch_no": task.batch.batch_no if task.batch is not None else None,
|
||||
"checkpoint": ui.checkpoint,
|
||||
"checkpoint_kind": str(ui.checkpoint_kind),
|
||||
"process_status": task.process_status,
|
||||
"review_status": task.review_status,
|
||||
"pending_human_reason": task.pending_human_reason,
|
||||
"match_status": task.match_status,
|
||||
"current_step": current_step,
|
||||
"steps": steps,
|
||||
"summary": _build_task_summary(task, ui.checkpoint),
|
||||
"summary": _build_task_summary(
|
||||
task,
|
||||
ui.checkpoint,
|
||||
checkpoint_kind=ui.checkpoint_kind,
|
||||
action_buttons=action_buttons,
|
||||
),
|
||||
"action_buttons": action_buttons,
|
||||
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
|
||||
}
|
||||
@@ -335,9 +447,10 @@ def build_task_ui_state(task: ShippingTask) -> dict[str, Any]:
|
||||
|
||||
def build_batch_ui_state(batch: ShippingBatch) -> dict[str, Any]:
|
||||
"""
|
||||
构建批次级 UI State。
|
||||
构建批次级会话上传集合摘要(非履约写操作面)。
|
||||
|
||||
核心逻辑:批次摘要、焦点任务、任务卡片均包含同源 task ui_state,供右侧工作台统一消费。
|
||||
核心逻辑:批次仅聚合各 PDF/Task 的同源 ui_state,供会话右侧「本次上传」摘要消费;
|
||||
履约写操作一律进入任务处理工作台。
|
||||
"""
|
||||
tasks = list_sorted_batch_tasks(batch)
|
||||
focus_task_no = str(batch.current_focus_task_no or "").strip()
|
||||
@@ -353,6 +466,7 @@ def build_batch_ui_state(batch: ShippingBatch) -> dict[str, Any]:
|
||||
]
|
||||
return {
|
||||
**serialize_batch_summary(batch),
|
||||
"role": "upload_session_summary",
|
||||
"process_summary": batch.process_summary_json or compute_batch_process_summary(tasks),
|
||||
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
|
||||
"focus_task_ui_state": build_task_ui_state(focus_task) if focus_task else None,
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
migrations/versions/1a2b3c4d5e60_freeze_auto_creation_into_schema_versions.py
|
||||
|
||||
用途:将 Schema 容器上的自动建单策略回填到各版本 definition_json,便于历史版本可追溯。
|
||||
依赖:shipping_order_schemas.auto_creation_policy_json、shipping_order_schema_versions.definition_json。
|
||||
逻辑:仅当 version.definition 缺少 auto_creation_policy 键时写入;已有键不覆盖。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = '1a2b3c4d5e60'
|
||||
down_revision = '1b2c3d4e5f6a'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""
|
||||
回填各 Schema 版本 definition 中的 auto_creation_policy。
|
||||
|
||||
核心逻辑:读取容器列策略;对缺少该键的 definition 写入规范化 enabled。
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
schemas = sa.table(
|
||||
'shipping_order_schemas',
|
||||
sa.column('id', sa.Integer),
|
||||
sa.column('auto_creation_policy_json', sa.JSON),
|
||||
)
|
||||
versions = sa.table(
|
||||
'shipping_order_schema_versions',
|
||||
sa.column('id', sa.Integer),
|
||||
sa.column('schema_id', sa.Integer),
|
||||
sa.column('definition_json', sa.JSON),
|
||||
)
|
||||
policy_by_schema: dict[int, dict] = {}
|
||||
for row in bind.execute(sa.select(schemas.c.id, schemas.c.auto_creation_policy_json)).mappings():
|
||||
raw = row['auto_creation_policy_json'] if isinstance(row['auto_creation_policy_json'], dict) else {}
|
||||
policy_by_schema[int(row['id'])] = {'enabled': bool(raw.get('enabled'))}
|
||||
|
||||
for row in bind.execute(
|
||||
sa.select(versions.c.id, versions.c.schema_id, versions.c.definition_json)
|
||||
).mappings():
|
||||
definition = copy.deepcopy(row['definition_json'] or {})
|
||||
if not isinstance(definition, dict):
|
||||
definition = {}
|
||||
if 'auto_creation_policy' in definition:
|
||||
continue
|
||||
definition['auto_creation_policy'] = policy_by_schema.get(
|
||||
int(row['schema_id']), {'enabled': False},
|
||||
)
|
||||
bind.execute(
|
||||
versions.update().where(versions.c.id == row['id']).values(definition_json=definition),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""
|
||||
从各版本 definition 移除 auto_creation_policy 键;不回写容器列。
|
||||
|
||||
核心逻辑:仅删除键,保留其余定义;策略仍以容器兼容缓存为准。
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
versions = sa.table(
|
||||
'shipping_order_schema_versions',
|
||||
sa.column('id', sa.Integer),
|
||||
sa.column('definition_json', sa.JSON),
|
||||
)
|
||||
for row in bind.execute(sa.select(versions.c.id, versions.c.definition_json)).mappings():
|
||||
definition = copy.deepcopy(row['definition_json'] or {})
|
||||
if not isinstance(definition, dict) or 'auto_creation_policy' not in definition:
|
||||
continue
|
||||
definition.pop('auto_creation_policy', None)
|
||||
bind.execute(
|
||||
versions.update().where(versions.c.id == row['id']).values(definition_json=definition),
|
||||
)
|
||||
@@ -0,0 +1,627 @@
|
||||
"""
|
||||
backend/migrations/versions/1b2c3d4e5f6a_rebuild_shipping_field_governance.py
|
||||
|
||||
用途:重建货代字段资产治理——全局标准/扩展字段、Schema 族约束放宽、审计扩展;清空旧配置并种子 57 标准资产。
|
||||
依赖:前序 head 0a1b2c3d4e5f;standard_field_registry。
|
||||
逻辑:
|
||||
upgrade — 软化**历史运行域**硬 FK(Extraction/Run/Snapshot/Artifact/Review 等保留 orphan ID,
|
||||
不再 enforce field_id / schema_version_id);按依赖清空**可写配置域**(模板/策略/身份/字段绑定等)→
|
||||
改表结构并同步 CHECK → 种子标准字段与空默认族 → **恢复配置域 FK**(policies/routing/identity/
|
||||
profiles/schema_versions/audit.schema_id)。
|
||||
downgrade — 删除本迁移种子与审计行;**结构回退** fields(恢复 nullable schema_id、去掉 asset 列)与
|
||||
audit(去掉 field_id);**不恢复** upgrade 已清空的模板/策略/身份/Excel 等业务配置数据。
|
||||
禁止 try/except 吞 DELETE(PG 会中止事务)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = '1b2c3d4e5f6a'
|
||||
down_revision = '0a1b2c3d4e5f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _table_exists(table: str) -> bool:
|
||||
"""判断当前库是否存在指定表(SQLite / PostgreSQL 通用)。"""
|
||||
return table in sa.inspect(op.get_bind()).get_table_names()
|
||||
|
||||
|
||||
def _drop_fk_if_exists(table: str, fk_name: str) -> None:
|
||||
"""幂等删除外键(PostgreSQL);SQLite 批测由 batch 路径覆盖。"""
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name == 'sqlite':
|
||||
return
|
||||
if not _table_exists(table):
|
||||
return
|
||||
op.execute(sa.text(
|
||||
f"ALTER TABLE {table} DROP CONSTRAINT IF EXISTS {fk_name}"
|
||||
))
|
||||
|
||||
|
||||
def _drop_all_fks_to_table(target_table: str) -> None:
|
||||
"""
|
||||
删除所有引用 target_table 的外键(PostgreSQL)。
|
||||
|
||||
核心逻辑:从 pg_constraint 枚举依赖,避免漏掉 Excel 导出产物、质量批次等配置/运行表导致 DELETE 被阻断。
|
||||
SQLite 测试库通常无跨表硬 FK 或由 recreate 覆盖,此处跳过。
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name != 'postgresql':
|
||||
return
|
||||
rows = bind.execute(sa.text(
|
||||
"""
|
||||
SELECT
|
||||
conrelid::regclass::text AS table_name,
|
||||
conname AS constraint_name
|
||||
FROM pg_constraint
|
||||
WHERE contype = 'f'
|
||||
AND confrelid = to_regclass(:target)
|
||||
"""
|
||||
), {'target': target_table}).mappings().all()
|
||||
for row in rows:
|
||||
table_name = str(row['table_name']).strip('"')
|
||||
constraint_name = str(row['constraint_name'])
|
||||
op.execute(sa.text(
|
||||
f'ALTER TABLE {table_name} DROP CONSTRAINT IF EXISTS "{constraint_name}"'
|
||||
))
|
||||
|
||||
|
||||
def _delete_if_exists(table: str) -> None:
|
||||
"""表存在时清空;禁止用 try/except 吞失败——PostgreSQL 失败后事务已中止。"""
|
||||
if _table_exists(table):
|
||||
op.execute(sa.text(f'DELETE FROM {table}'))
|
||||
|
||||
|
||||
def _execute_if_exists(table: str, sql: str) -> None:
|
||||
"""仅在表存在时执行 SQL(用于 NULLable 解绑等)。"""
|
||||
if _table_exists(table):
|
||||
op.execute(sa.text(sql))
|
||||
|
||||
|
||||
def _sqlite_strip_foreign_keys(table: str) -> None:
|
||||
"""
|
||||
SQLite 无法 DROP CONSTRAINT;用 CTAS 重建去掉外键,保留行数据与 orphan 引用。
|
||||
|
||||
核心逻辑:生产走 PostgreSQL 卸 FK;SQLite 批测/本地库在事务内 PRAGMA foreign_keys
|
||||
无效,必须物理重建表才能 DELETE 被引用的配置行。
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name != 'sqlite' or not _table_exists(table):
|
||||
return
|
||||
tmp = f'{table}__no_fk'
|
||||
op.execute(sa.text(f'DROP TABLE IF EXISTS "{tmp}"'))
|
||||
op.execute(sa.text(f'CREATE TABLE "{tmp}" AS SELECT * FROM "{table}"'))
|
||||
op.execute(sa.text(f'DROP TABLE "{table}"'))
|
||||
op.execute(sa.text(f'ALTER TABLE "{tmp}" RENAME TO "{table}"'))
|
||||
|
||||
|
||||
def _column_exists(table: str, column: str) -> bool:
|
||||
"""判断指定表是否包含某列。"""
|
||||
if not _table_exists(table):
|
||||
return False
|
||||
return column in {item['name'] for item in sa.inspect(op.get_bind()).get_columns(table)}
|
||||
|
||||
|
||||
def _fk_exists(table: str, fk_name: str) -> bool:
|
||||
"""判断指定表是否已存在具名外键。"""
|
||||
if not _table_exists(table):
|
||||
return False
|
||||
return fk_name in {
|
||||
str(fk.get('name'))
|
||||
for fk in sa.inspect(op.get_bind()).get_foreign_keys(table)
|
||||
if fk.get('name')
|
||||
}
|
||||
|
||||
|
||||
def _create_fk_if_not_exists(
|
||||
table: str,
|
||||
fk_name: str,
|
||||
referent_table: str,
|
||||
local_cols: list[str],
|
||||
remote_cols: list[str],
|
||||
*,
|
||||
ondelete: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
幂等创建 PostgreSQL 外键;SQLite 测试库跳过(CTAS 路径通常无跨表硬 FK)。
|
||||
|
||||
核心逻辑:表/列存在且外键未创建时才 op.create_foreign_key。
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name == 'sqlite':
|
||||
return
|
||||
if not _table_exists(table) or not _table_exists(referent_table):
|
||||
return
|
||||
if _fk_exists(table, fk_name):
|
||||
return
|
||||
insp = sa.inspect(bind)
|
||||
local_names = {col['name'] for col in insp.get_columns(table)}
|
||||
remote_names = {col['name'] for col in insp.get_columns(referent_table)}
|
||||
if not set(local_cols) <= local_names or not set(remote_cols) <= remote_names:
|
||||
return
|
||||
kwargs: dict[str, str] = {}
|
||||
if ondelete:
|
||||
kwargs['ondelete'] = ondelete
|
||||
op.create_foreign_key(fk_name, table, referent_table, local_cols, remote_cols, **kwargs)
|
||||
|
||||
|
||||
def _restore_config_domain_foreign_keys() -> None:
|
||||
"""
|
||||
在 upgrade 末尾恢复可写配置域外键;历史运行域表保持软引用(不重建 FK)。
|
||||
|
||||
恢复清单:fulfillment_policies.schema_id、inventory_routing.order_field_id、
|
||||
identity_definitions.context_field_id、document_profiles.schema_version_id、
|
||||
schema_versions.schema_id、schema_audit_events.schema_id。
|
||||
"""
|
||||
# [STEP 6] 配置域 FK — 仅 PostgreSQL;运行域 Extraction/Artifact/Observation 等保持 orphan 容忍。
|
||||
_create_fk_if_not_exists(
|
||||
'shipping_order_schema_versions',
|
||||
'shipping_order_schema_versions_schema_id_fkey',
|
||||
'shipping_order_schemas',
|
||||
['schema_id'],
|
||||
['id'],
|
||||
)
|
||||
_create_fk_if_not_exists(
|
||||
'shipping_order_schema_audit_events',
|
||||
'shipping_order_schema_audit_events_schema_id_fkey',
|
||||
'shipping_order_schemas',
|
||||
['schema_id'],
|
||||
['id'],
|
||||
)
|
||||
_create_fk_if_not_exists(
|
||||
'shipping_fulfillment_policies',
|
||||
'shipping_fulfillment_policies_schema_id_fkey',
|
||||
'shipping_order_schemas',
|
||||
['schema_id'],
|
||||
['id'],
|
||||
)
|
||||
_create_fk_if_not_exists(
|
||||
'shipping_inventory_routing_rule_conditions',
|
||||
'fk_inventory_routing_conditions_order_field',
|
||||
'shipping_order_fields',
|
||||
['order_field_id'],
|
||||
['id'],
|
||||
)
|
||||
_create_fk_if_not_exists(
|
||||
'shipping_identity_definitions',
|
||||
'fk_shipping_identity_definitions_context_field',
|
||||
'shipping_order_fields',
|
||||
['context_field_id'],
|
||||
['id'],
|
||||
)
|
||||
_create_fk_if_not_exists(
|
||||
'shipping_order_document_profiles',
|
||||
'shipping_order_document_profiles_schema_version_id_fkey',
|
||||
'shipping_order_schema_versions',
|
||||
['schema_version_id'],
|
||||
['id'],
|
||||
)
|
||||
|
||||
|
||||
def _revert_shipping_order_fields_structure(is_sqlite: bool) -> None:
|
||||
"""
|
||||
结构回退 shipping_order_fields:去掉资产治理列,恢复 nullable schema_id 与旧唯一/索引约束。
|
||||
|
||||
不恢复 upgrade 删除的业务字段行;仅还原列与 CHECK/索引形态供 Alembic revision 与 ORM 前序版本对齐。
|
||||
"""
|
||||
governance_columns = (
|
||||
'asset_kind',
|
||||
'storage_mode',
|
||||
'storage_column',
|
||||
'semantic_description',
|
||||
'display_name_default',
|
||||
'fulfillment_role',
|
||||
'retired_reason',
|
||||
'retired_by_id',
|
||||
'retired_at',
|
||||
'restored_by_id',
|
||||
'restored_at',
|
||||
)
|
||||
if is_sqlite:
|
||||
with op.batch_alter_table('shipping_order_fields', recreate='always') as batch:
|
||||
for column in governance_columns:
|
||||
if _column_exists('shipping_order_fields', column):
|
||||
batch.drop_column(column)
|
||||
if not _column_exists('shipping_order_fields', 'schema_id'):
|
||||
batch.add_column(sa.Column('schema_id', sa.Integer(), nullable=True))
|
||||
batch.drop_constraint('uq_shipping_order_fields_field_code', type_='unique')
|
||||
batch.create_unique_constraint(
|
||||
'uq_shipping_order_fields_schema_code',
|
||||
['schema_id', 'field_code'],
|
||||
)
|
||||
batch.create_index('ix_shipping_order_fields_schema_scope', ['schema_id', 'scope'])
|
||||
batch.drop_constraint('ck_shipping_order_fields_asset_kind', type_='check')
|
||||
batch.drop_constraint('ck_shipping_order_fields_storage_mode', type_='check')
|
||||
batch.drop_constraint('ck_shipping_order_fields_category', type_='check')
|
||||
batch.drop_constraint('ck_shipping_order_fields_collection_mode', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_order_fields_category',
|
||||
"field_category IN ('general_context', 'order_header', 'order_line')",
|
||||
)
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_order_fields_collection_mode',
|
||||
"collection_mode IN ('deterministic_context', 'llm_extraction')",
|
||||
)
|
||||
return
|
||||
|
||||
op.execute(sa.text('DROP INDEX IF EXISTS ix_shipping_order_fields_scope_status'))
|
||||
op.execute(sa.text('DROP INDEX IF EXISTS ix_shipping_order_fields_asset_kind'))
|
||||
op.execute(sa.text(
|
||||
'ALTER TABLE shipping_order_fields DROP CONSTRAINT IF EXISTS uq_shipping_order_fields_field_code'
|
||||
))
|
||||
op.execute(sa.text(
|
||||
'ALTER TABLE shipping_order_fields DROP CONSTRAINT IF EXISTS ck_shipping_order_fields_asset_kind'
|
||||
))
|
||||
op.execute(sa.text(
|
||||
'ALTER TABLE shipping_order_fields DROP CONSTRAINT IF EXISTS ck_shipping_order_fields_storage_mode'
|
||||
))
|
||||
for column in governance_columns:
|
||||
if _column_exists('shipping_order_fields', column):
|
||||
op.drop_column('shipping_order_fields', column)
|
||||
if not _column_exists('shipping_order_fields', 'schema_id'):
|
||||
op.add_column('shipping_order_fields', sa.Column('schema_id', sa.Integer(), nullable=True))
|
||||
op.create_unique_constraint(
|
||||
'uq_shipping_order_fields_schema_code',
|
||||
'shipping_order_fields',
|
||||
['schema_id', 'field_code'],
|
||||
)
|
||||
op.create_index('ix_shipping_order_fields_schema_scope', 'shipping_order_fields', ['schema_id', 'scope'])
|
||||
_create_fk_if_not_exists(
|
||||
'shipping_order_fields',
|
||||
'shipping_order_fields_schema_id_fkey',
|
||||
'shipping_order_schemas',
|
||||
['schema_id'],
|
||||
['id'],
|
||||
)
|
||||
op.execute(sa.text('ALTER TABLE shipping_order_fields DROP CONSTRAINT IF EXISTS ck_shipping_order_fields_category'))
|
||||
op.execute(sa.text('ALTER TABLE shipping_order_fields DROP CONSTRAINT IF EXISTS ck_shipping_order_fields_collection_mode'))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_fields ADD CONSTRAINT ck_shipping_order_fields_category "
|
||||
"CHECK (field_category IN ('general_context', 'order_header', 'order_line'))"
|
||||
))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_fields ADD CONSTRAINT ck_shipping_order_fields_collection_mode "
|
||||
"CHECK (collection_mode IN ('deterministic_context', 'llm_extraction'))"
|
||||
))
|
||||
|
||||
|
||||
def _revert_schema_audit_events_structure(is_sqlite: bool) -> None:
|
||||
"""结构回退审计表:去掉 field_id;event_type CHECK 恢复为 upgrade 前枚举(schema_id 可空保持)。"""
|
||||
if is_sqlite:
|
||||
# SQLite 测试库迁移前表常无具名 CHECK;仅去掉 field_id 列即可。
|
||||
if _column_exists('shipping_order_schema_audit_events', 'field_id'):
|
||||
with op.batch_alter_table('shipping_order_schema_audit_events', recreate='always') as batch:
|
||||
batch.drop_column('field_id')
|
||||
return
|
||||
|
||||
if _column_exists('shipping_order_schema_audit_events', 'field_id'):
|
||||
op.drop_column('shipping_order_schema_audit_events', 'field_id')
|
||||
op.execute(sa.text(
|
||||
'ALTER TABLE shipping_order_schema_audit_events DROP CONSTRAINT IF EXISTS ck_shipping_order_schema_audit_event_type'
|
||||
))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_schema_audit_events ADD CONSTRAINT ck_shipping_order_schema_audit_event_type "
|
||||
"CHECK (event_type IN ("
|
||||
"'draft_created', 'draft_saved', 'published', 'draft_deleted', 'cloned', "
|
||||
"'field_saved', 'field_retired', 'field_deleted'"
|
||||
"))"
|
||||
))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""清空旧字段配置并重建为全局字段资产 + 多族 Schema。"""
|
||||
conn = op.get_bind()
|
||||
is_sqlite = conn.dialect.name == 'sqlite'
|
||||
|
||||
# [STEP 1] 软化运行域硬 FK,保留孤儿 ID 供历史 Run/Snapshot/证据只读。
|
||||
# 先按已知名单卸 FK,再兜底卸掉一切仍指向 schema_versions / fields 的外键,
|
||||
# 防止 Excel Artifact、模板子树等漏网约束阻断 DELETE。
|
||||
for table, fk in (
|
||||
('shipping_order_field_observations', 'shipping_order_field_observations_field_id_fkey'),
|
||||
('shipping_order_field_decisions', 'shipping_order_field_decisions_field_id_fkey'),
|
||||
('shipping_order_field_values', 'shipping_order_field_values_field_id_fkey'),
|
||||
('shipping_order_extraction_runs', 'shipping_order_extraction_runs_schema_version_id_fkey'),
|
||||
('shipping_order_extractions', 'shipping_order_extractions_schema_version_id_fkey'),
|
||||
('shipping_order_snapshots', 'shipping_order_snapshots_schema_version_id_fkey'),
|
||||
('shipping_order_review_drafts', 'shipping_order_review_drafts_schema_version_id_fkey'),
|
||||
(
|
||||
'shipping_order_review_confirmed_revisions',
|
||||
'shipping_order_review_confirmed_revision_schema_version_id_fkey',
|
||||
),
|
||||
('shipping_export_artifacts', 'shipping_export_artifacts_order_schema_version_id_fkey'),
|
||||
(
|
||||
'shipping_customer_shadow_resolutions',
|
||||
'shipping_customer_shadow_resolutio_order_schema_version_id_fkey',
|
||||
),
|
||||
(
|
||||
'shipping_order_extraction_quality_batches',
|
||||
'shipping_order_extraction_quality_batche_schema_version_id_fkey',
|
||||
),
|
||||
(
|
||||
'shipping_order_extraction_route_decisions',
|
||||
'shipping_order_extraction_route_decisi_selected_profile_id_fkey',
|
||||
),
|
||||
):
|
||||
_drop_fk_if_exists(table, fk)
|
||||
_drop_all_fks_to_table('shipping_order_schema_versions')
|
||||
_drop_all_fks_to_table('shipping_order_fields')
|
||||
_drop_all_fks_to_table('shipping_order_schemas')
|
||||
|
||||
# [STEP 2] 清空配置域(不删运行域 Extraction/Run/Snapshot/Artifact 行)
|
||||
# 顺序:模板子树 → Excel 模板配置(库存源先解绑)→ 策略/身份/库存字段绑定 → schema 审计/版本/字段/族。
|
||||
for table in (
|
||||
'shipping_order_document_profile_publish_check_reports',
|
||||
'shipping_order_document_profile_suggestion_decisions',
|
||||
'shipping_order_document_profile_validation_runs',
|
||||
'shipping_document_profile_auto_freeze_qualifications',
|
||||
'shipping_document_profile_test_runs',
|
||||
'shipping_document_profile_test_samples',
|
||||
'shipping_document_profile_test_suites',
|
||||
'shipping_order_document_profile_audits',
|
||||
'shipping_order_document_profile_draft_revisions',
|
||||
'shipping_order_document_profile_edit_leases',
|
||||
'shipping_order_document_profile_samples',
|
||||
):
|
||||
_delete_if_exists(table)
|
||||
_execute_if_exists(
|
||||
'shipping_order_document_profiles',
|
||||
'UPDATE shipping_order_document_profiles SET source_profile_id = NULL',
|
||||
)
|
||||
_delete_if_exists('shipping_order_document_profiles')
|
||||
# Excel 模板属配置域:先关闭库存源再解绑,避免 CHECK(enabled→须有模板) 阻断。
|
||||
# 历史导出 Artifact 保留 orphan template_id / schema_version_id,仅软化 FK。
|
||||
_drop_fk_if_exists('shipping_export_artifacts', 'shipping_export_artifacts_template_id_fkey')
|
||||
_drop_fk_if_exists('shipping_export_artifacts', 'shipping_export_artifacts_order_schema_version_id_fkey')
|
||||
_drop_all_fks_to_table('shipping_excel_templates')
|
||||
# SQLite:事务内无法靠 PRAGMA 关闭 FK,CTAS 剥离 Artifact 外键后再删模板/版本。
|
||||
_sqlite_strip_foreign_keys('shipping_export_artifacts')
|
||||
_execute_if_exists(
|
||||
'shipping_inventory_sources',
|
||||
'UPDATE shipping_inventory_sources SET enabled = false, excel_template_id = NULL',
|
||||
)
|
||||
_sqlite_strip_foreign_keys('shipping_inventory_sources')
|
||||
_delete_if_exists('shipping_excel_templates')
|
||||
_delete_if_exists('shipping_fulfillment_policies')
|
||||
_delete_if_exists('shipping_order_schema_audit_events')
|
||||
_delete_if_exists('shipping_order_extraction_quality_batches')
|
||||
# 库存条件 source=order_field 时 CHECK 要求 order_field_id 非空,只能删绑定行,留给切换清单重绑。
|
||||
_execute_if_exists(
|
||||
'shipping_inventory_routing_rule_conditions',
|
||||
"DELETE FROM shipping_inventory_routing_rule_conditions WHERE order_field_id IS NOT NULL",
|
||||
)
|
||||
_drop_fk_if_exists(
|
||||
'shipping_inventory_routing_rule_conditions',
|
||||
'fk_inventory_routing_conditions_order_field',
|
||||
)
|
||||
# 身份定义属配置,但证据表属运行痕迹:只软化 context_field FK,保留定义/证据行供重绑。
|
||||
_drop_fk_if_exists(
|
||||
'shipping_identity_definitions',
|
||||
'fk_shipping_identity_definitions_context_field',
|
||||
)
|
||||
_sqlite_strip_foreign_keys('shipping_order_fields')
|
||||
_sqlite_strip_foreign_keys('shipping_order_schema_versions')
|
||||
_sqlite_strip_foreign_keys('shipping_fulfillment_policies')
|
||||
_delete_if_exists('shipping_order_schema_versions')
|
||||
_delete_if_exists('shipping_order_fields')
|
||||
_delete_if_exists('shipping_order_schemas')
|
||||
|
||||
# [STEP 3] 改造 shipping_order_fields:去 schema_id,加资产治理列
|
||||
if is_sqlite:
|
||||
# SQLite 用 recreate 避免依赖可能不存在的旧约束/索引名,并同步模型 CHECK。
|
||||
with op.batch_alter_table('shipping_order_fields', recreate='always') as batch:
|
||||
batch.drop_column('schema_id')
|
||||
batch.add_column(sa.Column('asset_kind', sa.String(32), nullable=False, server_default='extension'))
|
||||
batch.add_column(sa.Column('storage_mode', sa.String(32), nullable=False, server_default='json_only'))
|
||||
batch.add_column(sa.Column('storage_column', sa.String(64), nullable=True))
|
||||
batch.add_column(sa.Column('semantic_description', sa.Text(), nullable=True))
|
||||
batch.add_column(sa.Column('display_name_default', sa.String(128), nullable=True))
|
||||
batch.add_column(sa.Column('fulfillment_role', sa.String(64), nullable=True))
|
||||
batch.add_column(sa.Column('retired_reason', sa.Text(), nullable=True))
|
||||
batch.add_column(sa.Column('retired_by_id', sa.Integer(), nullable=True))
|
||||
batch.add_column(sa.Column('retired_at', sa.DateTime(), nullable=True))
|
||||
batch.add_column(sa.Column('restored_by_id', sa.Integer(), nullable=True))
|
||||
batch.add_column(sa.Column('restored_at', sa.DateTime(), nullable=True))
|
||||
batch.create_unique_constraint('uq_shipping_order_fields_field_code', ['field_code'])
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_order_fields_category',
|
||||
"field_category IN ('order_header', 'order_line')",
|
||||
)
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_order_fields_collection_mode',
|
||||
"collection_mode IN ('llm_extraction')",
|
||||
)
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_order_fields_asset_kind',
|
||||
"asset_kind IN ('system_standard', 'extension')",
|
||||
)
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_order_fields_storage_mode',
|
||||
"storage_mode IN ('typed_column', 'json_only')",
|
||||
)
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_order_fields_status',
|
||||
"status IN ('active', 'retired')",
|
||||
)
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_order_fields_scope',
|
||||
"scope IN ('header', 'line')",
|
||||
)
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_order_fields_value_type',
|
||||
"value_type IN ('string', 'decimal', 'integer', 'date', 'boolean', 'enum')",
|
||||
)
|
||||
else:
|
||||
_drop_fk_if_exists('shipping_order_fields', 'shipping_order_fields_schema_id_fkey')
|
||||
op.execute(sa.text('ALTER TABLE shipping_order_fields DROP CONSTRAINT IF EXISTS uq_shipping_order_fields_schema_code'))
|
||||
op.execute(sa.text('DROP INDEX IF EXISTS ix_shipping_order_fields_schema_scope'))
|
||||
op.drop_column('shipping_order_fields', 'schema_id')
|
||||
op.add_column('shipping_order_fields', sa.Column('asset_kind', sa.String(32), nullable=False, server_default='extension'))
|
||||
op.add_column('shipping_order_fields', sa.Column('storage_mode', sa.String(32), nullable=False, server_default='json_only'))
|
||||
op.add_column('shipping_order_fields', sa.Column('storage_column', sa.String(64), nullable=True))
|
||||
op.add_column('shipping_order_fields', sa.Column('semantic_description', sa.Text(), nullable=True))
|
||||
op.add_column('shipping_order_fields', sa.Column('display_name_default', sa.String(128), nullable=True))
|
||||
op.add_column('shipping_order_fields', sa.Column('fulfillment_role', sa.String(64), nullable=True))
|
||||
op.add_column('shipping_order_fields', sa.Column('retired_reason', sa.Text(), nullable=True))
|
||||
op.add_column('shipping_order_fields', sa.Column('retired_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True))
|
||||
op.add_column('shipping_order_fields', sa.Column('retired_at', sa.DateTime(), nullable=True))
|
||||
op.add_column('shipping_order_fields', sa.Column('restored_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True))
|
||||
op.add_column('shipping_order_fields', sa.Column('restored_at', sa.DateTime(), nullable=True))
|
||||
op.create_unique_constraint('uq_shipping_order_fields_field_code', 'shipping_order_fields', ['field_code'])
|
||||
op.create_index('ix_shipping_order_fields_scope_status', 'shipping_order_fields', ['scope', 'status'])
|
||||
op.create_index('ix_shipping_order_fields_asset_kind', 'shipping_order_fields', ['asset_kind'])
|
||||
# 放宽/替换字段分类与采集模式约束:去掉 general_context
|
||||
op.execute(sa.text('ALTER TABLE shipping_order_fields DROP CONSTRAINT IF EXISTS ck_shipping_order_fields_category'))
|
||||
op.execute(sa.text('ALTER TABLE shipping_order_fields DROP CONSTRAINT IF EXISTS ck_shipping_order_fields_collection_mode'))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_fields ADD CONSTRAINT ck_shipping_order_fields_category "
|
||||
"CHECK (field_category IN ('order_header', 'order_line'))"
|
||||
))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_fields ADD CONSTRAINT ck_shipping_order_fields_collection_mode "
|
||||
"CHECK (collection_mode IN ('llm_extraction'))"
|
||||
))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_fields ADD CONSTRAINT ck_shipping_order_fields_asset_kind "
|
||||
"CHECK (asset_kind IN ('system_standard', 'extension'))"
|
||||
))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_fields ADD CONSTRAINT ck_shipping_order_fields_storage_mode "
|
||||
"CHECK (storage_mode IN ('typed_column', 'json_only'))"
|
||||
))
|
||||
|
||||
# [STEP 4] Schema 族:去掉唯一 SHIPPING_ORDER 约束;审计表 schema_id 可空 + field_id
|
||||
if is_sqlite:
|
||||
with op.batch_alter_table('shipping_order_schema_audit_events', recreate='always') as batch:
|
||||
batch.alter_column('schema_id', existing_type=sa.Integer(), nullable=True)
|
||||
batch.add_column(sa.Column('field_id', sa.String(36), nullable=True))
|
||||
else:
|
||||
op.execute(sa.text('ALTER TABLE shipping_order_schemas DROP CONSTRAINT IF EXISTS ck_shipping_order_schemas_single_code'))
|
||||
op.execute(sa.text('ALTER TABLE shipping_order_schema_audit_events DROP CONSTRAINT IF EXISTS ck_shipping_order_schema_audit_event_type'))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_schema_audit_events ADD CONSTRAINT ck_shipping_order_schema_audit_event_type "
|
||||
"CHECK (event_type IN ("
|
||||
"'draft_created', 'draft_saved', 'published', 'draft_deleted', 'cloned', "
|
||||
"'field_saved', 'field_retired', 'field_restored', "
|
||||
"'extension_created', 'extension_updated', 'extension_retired', 'extension_restored', "
|
||||
"'family_created', 'field_adopted', 'field_unadopted', 'publish_blocked'"
|
||||
"))"
|
||||
))
|
||||
op.alter_column('shipping_order_schema_audit_events', 'schema_id', existing_type=sa.Integer(), nullable=True)
|
||||
op.add_column('shipping_order_schema_audit_events', sa.Column('field_id', sa.String(36), nullable=True))
|
||||
|
||||
# [STEP 5] 种子 57 标准字段 + 空默认族
|
||||
from app.services.shipping_notice.standard_field_registry import (
|
||||
DEFAULT_SCHEMA_FAMILY_CODE,
|
||||
DEFAULT_SCHEMA_FAMILY_NAME,
|
||||
STANDARD_FIELD_SPECS,
|
||||
assert_registry_consistent,
|
||||
)
|
||||
|
||||
assert_registry_consistent()
|
||||
now = datetime.utcnow()
|
||||
fields_table = sa.table(
|
||||
'shipping_order_fields',
|
||||
sa.column('id', sa.String),
|
||||
sa.column('field_code', sa.String),
|
||||
sa.column('scope', sa.String),
|
||||
sa.column('value_type', sa.String),
|
||||
sa.column('field_category', sa.String),
|
||||
sa.column('collection_mode', sa.String),
|
||||
sa.column('asset_kind', sa.String),
|
||||
sa.column('storage_mode', sa.String),
|
||||
sa.column('storage_column', sa.String),
|
||||
sa.column('semantic_description', sa.Text),
|
||||
sa.column('display_name_default', sa.String),
|
||||
sa.column('fulfillment_role', sa.String),
|
||||
sa.column('display_sequence', sa.Integer),
|
||||
sa.column('status', sa.String),
|
||||
sa.column('published_once', sa.Boolean),
|
||||
sa.column('created_at', sa.DateTime),
|
||||
sa.column('updated_at', sa.DateTime),
|
||||
)
|
||||
rows = []
|
||||
for sequence, spec in enumerate(STANDARD_FIELD_SPECS.values(), start=1):
|
||||
rows.append({
|
||||
'id': str(uuid.uuid4()),
|
||||
'field_code': spec.field_code,
|
||||
'scope': spec.scope,
|
||||
'value_type': spec.value_type,
|
||||
'field_category': 'order_header' if spec.scope == 'header' else 'order_line',
|
||||
'collection_mode': 'llm_extraction',
|
||||
'asset_kind': 'system_standard',
|
||||
'storage_mode': spec.storage_mode,
|
||||
'storage_column': spec.storage_column,
|
||||
'semantic_description': spec.semantic_description,
|
||||
'display_name_default': spec.display_name,
|
||||
'fulfillment_role': spec.fulfillment_role,
|
||||
'display_sequence': sequence,
|
||||
'status': 'active',
|
||||
'published_once': False,
|
||||
'created_at': now,
|
||||
'updated_at': now,
|
||||
})
|
||||
op.bulk_insert(fields_table, rows)
|
||||
|
||||
schemas = sa.table(
|
||||
'shipping_order_schemas',
|
||||
sa.column('schema_code', sa.String),
|
||||
sa.column('display_name', sa.String),
|
||||
sa.column('description', sa.Text),
|
||||
sa.column('auto_creation_policy_json', sa.JSON),
|
||||
sa.column('status', sa.String),
|
||||
sa.column('created_at', sa.DateTime),
|
||||
sa.column('updated_at', sa.DateTime),
|
||||
)
|
||||
op.bulk_insert(schemas, [{
|
||||
'schema_code': DEFAULT_SCHEMA_FAMILY_CODE,
|
||||
'display_name': DEFAULT_SCHEMA_FAMILY_NAME,
|
||||
'description': '默认发货通知 Schema 族;版本由管理员手动创建并发布',
|
||||
'auto_creation_policy_json': {},
|
||||
'status': 'active',
|
||||
'created_at': now,
|
||||
'updated_at': now,
|
||||
}])
|
||||
|
||||
# [STEP 6] 种子完成后恢复配置域 FK;历史运行域保持软引用。
|
||||
_restore_config_domain_foreign_keys()
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""
|
||||
结构回退到 upgrade 前骨架并清空本迁移写入的种子行。
|
||||
|
||||
重要:upgrade 已 DELETE 的模板、Excel 配置、履约策略、身份定义、文档 Profile 等
|
||||
业务配置**不会**在此恢复;downgrade 仅保证 Alembic revision 与表结构一致。
|
||||
"""
|
||||
conn = op.get_bind()
|
||||
is_sqlite = conn.dialect.name == 'sqlite'
|
||||
|
||||
# [STEP 1] 清空本迁移种子与审计(不恢复 upgrade 删掉的业务配置)。
|
||||
_delete_if_exists('shipping_order_schema_audit_events')
|
||||
_delete_if_exists('shipping_order_schema_versions')
|
||||
_delete_if_exists('shipping_order_fields')
|
||||
_delete_if_exists('shipping_order_schemas')
|
||||
|
||||
# [STEP 2] 结构回退 fields:去掉 asset 列,恢复 nullable schema_id。
|
||||
_revert_shipping_order_fields_structure(is_sqlite)
|
||||
|
||||
# [STEP 3] 结构回退 audit:去掉 field_id,恢复旧 event_type CHECK。
|
||||
if _table_exists('shipping_order_schema_audit_events'):
|
||||
_revert_schema_audit_events_structure(is_sqlite)
|
||||
|
||||
# [STEP 4] 恢复 Schema 族「唯一 SHIPPING_ORDER」约束(PG);多族形态回退。
|
||||
if not is_sqlite:
|
||||
op.execute(sa.text(
|
||||
'ALTER TABLE shipping_order_schemas DROP CONSTRAINT IF EXISTS ck_shipping_order_schemas_single_code'
|
||||
))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_schemas ADD CONSTRAINT ck_shipping_order_schemas_single_code "
|
||||
"CHECK (schema_code = 'SHIPPING_ORDER')"
|
||||
))
|
||||
@@ -101,7 +101,8 @@ def _shipping_notice_stable_auto_config(app, request, monkeypatch):
|
||||
return
|
||||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
|
||||
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = True
|
||||
# STP 首期禁止货代 RPA 自动上传;单测默认与产品一致关闭。
|
||||
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False
|
||||
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
|
||||
app.config["ENV_NAME"] = "dev"
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = False
|
||||
|
||||
@@ -46,14 +46,11 @@ def _customer(code: str = 'WYC') -> ShippingCustomer:
|
||||
|
||||
|
||||
def _context_field() -> ShippingOrderField:
|
||||
"""创建身份定义非空外键所需的最小统一字段。"""
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
field = ShippingOrderField(schema_id=schema.id, field_code='sender_email', scope='header', value_type='string')
|
||||
db.session.add(field)
|
||||
db.session.flush()
|
||||
return field
|
||||
"""返回身份定义外键可用的标准 Header 字段(非 mail/context 编码)。"""
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
return ShippingOrderField.query.filter_by(field_code='bill_to_customer').one()
|
||||
|
||||
|
||||
def test_unused_customer_can_delete_and_identifiers_are_cascade_only(app):
|
||||
|
||||
@@ -45,14 +45,11 @@ def _customer(name: str, code: str, *, status: str = 'active') -> ShippingCustom
|
||||
|
||||
|
||||
def _context_field() -> ShippingOrderField:
|
||||
"""创建身份定义非空外键所需的最小统一字段。"""
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
field = ShippingOrderField(schema_id=schema.id, field_code='sender_email', scope='header', value_type='string')
|
||||
db.session.add(field)
|
||||
db.session.flush()
|
||||
return field
|
||||
"""返回身份定义外键可用的标准 Header 字段(非 mail/context 编码)。"""
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
return ShippingOrderField.query.filter_by(field_code='bill_to_customer').one()
|
||||
|
||||
|
||||
def test_merge_moves_future_configuration_and_preserves_history(app):
|
||||
|
||||
@@ -14,33 +14,36 @@ from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingCustomer, ShippingOrderField, ShippingOrderSchema, ShippingOrderSchemaVersion
|
||||
from app.services.shipping_notice.identity_rules import service
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
|
||||
def _published_header_field(
|
||||
*, code: str = 'sender_email', available: bool = True, option_key: str | None = 'from_email',
|
||||
scope: str = 'header', field_category: str | None = None,
|
||||
*, code: str = 'bill_to_customer', available: bool = True,
|
||||
scope: str = 'header',
|
||||
) -> ShippingOrderField:
|
||||
"""创建已发布 Header 字段;available 决定是否能进入客户识别目录。"""
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
if schema is None:
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
field = ShippingOrderField(
|
||||
schema_id=schema.id, field_code=code, scope=scope, value_type='string',
|
||||
field_category=field_category or ('general_context' if option_key else 'order_header'),
|
||||
collection_mode='deterministic_context' if option_key else 'llm_extraction',
|
||||
)
|
||||
db.session.add(field)
|
||||
db.session.flush()
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
field = ShippingOrderField.query.filter_by(field_code=code).one_or_none()
|
||||
if field is None:
|
||||
field = ShippingOrderField(
|
||||
field_code=code, scope=scope, value_type='string',
|
||||
field_category='order_header' if scope == 'header' else 'order_line',
|
||||
collection_mode='llm_extraction', asset_kind='extension', storage_mode='json_only',
|
||||
status='active', display_name_default=code,
|
||||
)
|
||||
db.session.add(field)
|
||||
db.session.flush()
|
||||
config = {
|
||||
'field_id': field.id, 'field_code': field.field_code, 'display_name': code,
|
||||
'scope': scope, 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': available, 'normalizer_key': 'lowercase_trim',
|
||||
}
|
||||
if option_key:
|
||||
config['context_source'] = {'provider_key': 'mail_header', 'option_key': option_key}
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
if version is None:
|
||||
version = ShippingOrderSchemaVersion(
|
||||
@@ -69,8 +72,8 @@ def _definition(field: ShippingOrderField, *, target: str = 'customer', automati
|
||||
def test_catalog_only_lists_published_identity_enabled_header_fields(app):
|
||||
"""目录只能显示当前发布版本中明确允许客户识别的 Header 字段。"""
|
||||
with app.app_context():
|
||||
enabled = _published_header_field(code='sender_email', available=True)
|
||||
_published_header_field(code='internal_note', available=False, option_key=None)
|
||||
enabled = _published_header_field(code='bill_to_customer', available=True)
|
||||
_published_header_field(code='internal_note', available=False)
|
||||
|
||||
catalog = service.list_definitions()
|
||||
|
||||
@@ -86,7 +89,7 @@ def test_definition_uses_context_field_only_and_defaults_to_manual_review(app):
|
||||
created = _definition(field)
|
||||
|
||||
assert created['context_field_id'] == field.id
|
||||
assert created['context_field']['field_code'] == 'sender_email'
|
||||
assert created['context_field']['field_code'] == 'bill_to_customer'
|
||||
assert created['max_automation'] == 'none'
|
||||
assert not {'source_adapter_key', 'source_selector', 'order_field_id', 'attribute_key'} & set(created)
|
||||
|
||||
@@ -94,7 +97,7 @@ def test_definition_uses_context_field_only_and_defaults_to_manual_review(app):
|
||||
def test_order_header_field_can_be_identity_evidence_without_automatic_confirmation(app):
|
||||
"""订单信息 Header 可进入客户识别,但不能单独获得自动确认能力。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field(code='bill_to_customer', option_key=None)
|
||||
field = _published_header_field(code='bill_to_customer')
|
||||
|
||||
created = _definition(field)
|
||||
catalog = service.list_definitions()
|
||||
@@ -107,7 +110,7 @@ def test_order_header_field_can_be_identity_evidence_without_automatic_confirmat
|
||||
def test_order_header_automation_can_be_explicitly_authorized(app):
|
||||
"""订单 Header 默认人工确认,但管理员可显式授权受控自动确认。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field(code='bill_to_customer', option_key=None)
|
||||
field = _published_header_field(code='bill_to_customer')
|
||||
|
||||
created = _definition(field, automation='conditional')
|
||||
|
||||
@@ -118,7 +121,7 @@ def test_order_line_field_cannot_be_enabled_for_customer_identity(app):
|
||||
"""货品明细即使发布快照误标为可识别,也不能进入目录或建立识别定义。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field(
|
||||
code='customer_part_number', option_key=None, scope='line', field_category='order_line',
|
||||
code='customer_part_number', scope='line',
|
||||
)
|
||||
|
||||
assert service.list_definitions()['context_fields'] == []
|
||||
@@ -130,7 +133,7 @@ def test_order_line_field_cannot_be_enabled_for_customer_identity(app):
|
||||
def test_published_rule_set_contains_saved_order_header_definition(app):
|
||||
"""保存规则集勾选后发布,客户证据目录必须读取同一份已发布 Header 定义。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field(code='bill_to_customer', option_key=None)
|
||||
field = _published_header_field(code='bill_to_customer')
|
||||
definition = _definition(field)
|
||||
draft = service.create_rule_set({}, actor_id=1)
|
||||
saved = service.save_rule_set(draft['id'], {
|
||||
@@ -150,27 +153,29 @@ def test_published_rule_set_contains_saved_order_header_definition(app):
|
||||
def test_unpublished_or_identity_disabled_field_is_rejected(app):
|
||||
"""未开放客户识别的字段不能通过伪造 payload 建立定义。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field(available=False, option_key=None)
|
||||
field = _published_header_field(available=False)
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
_definition(field)
|
||||
assert caught.value.code == 'SHIPPING.IDENTITY_ORDER_FIELD_INVALID'
|
||||
|
||||
|
||||
def test_definition_and_rule_snapshot_block_field_retirement(app):
|
||||
"""启用定义及发布快照引用均阻断字段退役,避免运行期悬空。"""
|
||||
"""发布规则集快照引用字段时,影响分析须标记 identity_rule_set 阻断弃用。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field()
|
||||
from app.services.shipping_notice import field_impact_analysis
|
||||
|
||||
field = _published_header_field(code='identity_retire_guard_ext')
|
||||
definition = _definition(field)
|
||||
draft = service.create_rule_set({}, actor_id=1)
|
||||
saved = service.save_rule_set(draft['id'], {
|
||||
'expected_lock_version': draft['lock_version'], 'definition_ids': [definition['id']],
|
||||
}, actor_id=1)
|
||||
service.publish_rule_set(draft['id'], expected_lock_version=saved['lock_version'], actor_id=1)
|
||||
service.retire_definition(definition['id'], actor_id=1)
|
||||
|
||||
with pytest.raises(ConflictError) as caught:
|
||||
order_schema_service.retire_field(field.id, actor_id=1)
|
||||
assert caught.value.code == 'SHIPPING.ORDER_FIELD_RETIRE_BLOCKED'
|
||||
impact = field_impact_analysis.analyze_field_impact(field.id)
|
||||
|
||||
assert 'identity_rule_set' in impact['blocking_kinds']
|
||||
assert impact['can_retire_extension'] is False
|
||||
|
||||
|
||||
def test_published_rule_set_freezes_order_schema_anchor(app):
|
||||
@@ -222,7 +227,7 @@ def test_publish_recompiles_latest_schema_field_snapshot(app):
|
||||
}, actor_id=1)
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
changed = dict(version.definition_json['fields'][0])
|
||||
changed['display_name'] = 'Current sender email'
|
||||
changed['display_name'] = 'Current bill to customer'
|
||||
changed['normalizer_key'] = 'trim'
|
||||
version.definition_json = {'fields': [changed]}
|
||||
db.session.commit()
|
||||
@@ -232,14 +237,14 @@ def test_publish_recompiles_latest_schema_field_snapshot(app):
|
||||
)
|
||||
|
||||
snapshot = published['definition']['definitions'][0]
|
||||
assert snapshot['field_config']['display_name'] == 'Current sender email'
|
||||
assert snapshot['field_config']['display_name'] == 'Current bill to customer'
|
||||
assert snapshot['field_config']['normalizer_key'] == 'trim'
|
||||
|
||||
|
||||
def test_rule_set_lock_and_email_evidence_normalization(app):
|
||||
"""规则集保持乐观锁;邮箱证据使用发布字段语义规范化并保持唯一。"""
|
||||
"""规则集保持乐观锁;邮箱形态证据使用发布字段语义规范化并保持唯一。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field()
|
||||
field = _published_header_field(code='identity_email_norm_ext')
|
||||
definition = _definition(field)
|
||||
draft = service.create_rule_set({}, actor_id=1)
|
||||
saved = service.save_rule_set(draft['id'], {
|
||||
@@ -264,7 +269,7 @@ def test_rule_set_lock_and_email_evidence_normalization(app):
|
||||
def test_evidence_normalization_uses_published_rule_snapshot(app):
|
||||
"""Schema 后续变化不能静默改变当前已发布识别规则集的证据标准化语义。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field()
|
||||
field = _published_header_field(code='identity_email_norm_ext')
|
||||
definition = _definition(field)
|
||||
draft = service.create_rule_set({}, actor_id=1)
|
||||
saved = service.save_rule_set(draft['id'], {
|
||||
@@ -272,8 +277,11 @@ def test_evidence_normalization_uses_published_rule_snapshot(app):
|
||||
}, actor_id=1)
|
||||
service.publish_rule_set(draft['id'], expected_lock_version=saved['lock_version'], actor_id=1)
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
changed = dict(version.definition_json['fields'][0])
|
||||
changed['context_source'] = None
|
||||
changed = next(
|
||||
dict(item) for item in (version.definition_json or {}).get('fields', [])
|
||||
if str(item.get('field_id') or '') == field.id
|
||||
)
|
||||
changed['display_name'] = 'Changed identity field'
|
||||
changed['normalizer_key'] = 'uppercase_trim'
|
||||
version.definition_json = {'fields': [changed]}
|
||||
customer = ShippingCustomer(standard_name='Snapshot Customer', short_code='SNP', status='active')
|
||||
@@ -285,19 +293,20 @@ def test_evidence_normalization_uses_published_rule_snapshot(app):
|
||||
data={'definition_id': definition['id'], 'raw_value': 'Buyer@Example.COM', 'status': 'approved'}, actor_id=1,
|
||||
)
|
||||
|
||||
assert evidence['normalized_value'] == 'buyer@example.com'
|
||||
# 非 mail/context 字段按规则集快照走默认大写规范化,不受后续 Schema 改写影响。
|
||||
assert evidence['normalized_value'] == 'BUYER@EXAMPLE.COM'
|
||||
|
||||
|
||||
def test_referenced_definition_cannot_change_context_field_binding(app):
|
||||
"""定义 ID 被规则快照引用后不能改绑字段,避免旧证据被新字段语义复用。"""
|
||||
with app.app_context():
|
||||
first = _published_header_field(code='sender_email')
|
||||
first = _published_header_field(code='bill_to_customer')
|
||||
definition = _definition(first)
|
||||
draft = service.create_rule_set({}, actor_id=1)
|
||||
service.save_rule_set(draft['id'], {
|
||||
'expected_lock_version': draft['lock_version'], 'definition_ids': [definition['id']],
|
||||
}, actor_id=1)
|
||||
second = _published_header_field(code='sender_domain', option_key='from_domain')
|
||||
second = _published_header_field(code='ship_to_customer')
|
||||
|
||||
with pytest.raises(ConflictError) as caught:
|
||||
service.save_definition({
|
||||
|
||||
@@ -48,21 +48,28 @@ def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension:
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Frozen order')
|
||||
db.session.add_all([user, task, schema])
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
definitions = []
|
||||
fields: dict[str, ShippingOrderField] = {}
|
||||
field_codes = [*HEADER_FIELD_PROJECTIONS, *LINE_FIELD_PROJECTIONS]
|
||||
if with_extension:
|
||||
field_codes.append('packing_reference')
|
||||
for position, code in enumerate(field_codes, start=1):
|
||||
scope = 'header' if code in HEADER_FIELD_PROJECTIONS else 'line'
|
||||
value_type = 'decimal' if code in {'qty', 'unit_price', 'line_amount_with_tax'} else ('date' if code in {'required_date', 'order_date'} else 'string')
|
||||
field = ShippingOrderField(
|
||||
schema_id=schema.id, field_code=code, scope=scope, value_type=value_type,
|
||||
field_category='order_header' if scope == 'header' else 'order_line',
|
||||
collection_mode='llm_extraction', display_sequence=position,
|
||||
extension = ShippingOrderField(
|
||||
field_code='packing_reference', scope='line', value_type='string',
|
||||
field_category='order_line', collection_mode='llm_extraction',
|
||||
asset_kind='extension', storage_mode='json_only', status='active',
|
||||
display_name_default='Packing Reference',
|
||||
)
|
||||
db.session.add(field)
|
||||
db.session.add(extension)
|
||||
db.session.flush()
|
||||
field_codes.append('packing_reference')
|
||||
for code in field_codes:
|
||||
if code == 'packing_reference':
|
||||
field = extension
|
||||
else:
|
||||
field = ShippingOrderField.query.filter_by(field_code=code).one()
|
||||
scope = 'header' if code in HEADER_FIELD_PROJECTIONS else 'line'
|
||||
value_type = field.value_type
|
||||
fields[code] = field
|
||||
definitions.append({'field_id': field.id, 'field_code': code, 'scope': scope, 'value_type': value_type, 'enabled': True})
|
||||
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={'fields': definitions}, checksum='snapshot-test')
|
||||
|
||||
@@ -39,25 +39,25 @@ def _create_users() -> None:
|
||||
|
||||
|
||||
def _identity_field() -> ShippingOrderField:
|
||||
"""发布 API 测试使用的客户识别邮箱字段。"""
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
field = ShippingOrderField(
|
||||
schema_id=schema.id, field_code='sender_email', scope='header', value_type='string',
|
||||
field_category='general_context', collection_mode='deterministic_context',
|
||||
)
|
||||
db.session.add(field)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={'fields': [{
|
||||
'field_id': field.id, 'field_code': field.field_code, 'display_name': 'Sender email',
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': True,
|
||||
'context_source': {'provider_key': 'mail_header', 'option_key': 'from_email'},
|
||||
}]}, checksum='1' * 64,
|
||||
))
|
||||
db.session.commit()
|
||||
"""发布 API 测试使用的客户识别 Header 字段(标准 bill_to_customer)。"""
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
field = ShippingOrderField.query.filter_by(field_code='bill_to_customer').one()
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
if schema is None:
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
if ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none() is None:
|
||||
db.session.add(ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={'fields': [{
|
||||
'field_id': field.id, 'field_code': field.field_code, 'display_name': 'Bill To Customer',
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': True, 'normalizer_key': 'lowercase_trim',
|
||||
}]}, checksum='1' * 64,
|
||||
))
|
||||
db.session.commit()
|
||||
return field
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"""
|
||||
backend/tests/test_field_impact_analysis.py
|
||||
|
||||
用途:验证字段影响分析在 Schema 取消采用时的下游阻断(如 Excel 模板引用)。
|
||||
依赖:field_impact_analysis、ShippingExcelTemplate、field_asset_service。
|
||||
逻辑:发布模板引用 order_field 后,analyze_unadopt_impact 须阻断该字段取消采用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from openpyxl import Workbook
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app.models import ShippingOrderField
|
||||
from app.services.shipping_notice import excel_template
|
||||
from app.services.shipping_notice import field_impact_analysis
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
|
||||
def _workbook_upload() -> FileStorage:
|
||||
"""构造最小 xlsx 上传对象供模板发布测试使用。"""
|
||||
stream = BytesIO()
|
||||
wb = Workbook()
|
||||
wb.active.title = 'Detail'
|
||||
wb.save(stream)
|
||||
stream.seek(0)
|
||||
return FileStorage(
|
||||
stream=stream, filename='impact.xlsx',
|
||||
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
|
||||
|
||||
def test_unadopt_blocked_when_excel_template_references_field(app, tmp_path, monkeypatch):
|
||||
"""Excel 模板 draft/published 引用字段时,取消 Schema 采用须被阻断。"""
|
||||
objects: dict[str, bytes] = {}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.excel_template.file_asset_storage.upload_bytes',
|
||||
lambda *, storage_key, data, content_type: objects.__setitem__(storage_key, bytes(data)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.excel_template.file_asset_storage.get_bytes',
|
||||
lambda storage_key: objects[storage_key],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.excel_template.file_asset_storage.delete_object',
|
||||
lambda storage_key: objects.pop(storage_key, None),
|
||||
)
|
||||
monkeypatch.setattr('app.services.shipping_notice.excel_template.file_asset_storage.bucket_name', 'test-bucket')
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
part = ShippingOrderField.query.filter_by(field_code='part_number').one()
|
||||
order_schema_service.initialize_schema({'display_name': 'Impact Test Schema'}, actor_id=None)
|
||||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
saved = order_schema_service.save_draft(draft['id'], {
|
||||
'fields': [{
|
||||
'field_id': part.id, 'display_name': 'Part Number', 'required': True,
|
||||
'aliases': [], 'normalizer_key': 'uppercase_trim', 'validator_keys': ['non_empty'],
|
||||
'enum_options': [], 'evidence_policy': {
|
||||
'required': True, 'source_precedence': ['attachment_table'],
|
||||
'conflict_policy': 'block', 'allow_single_source': True,
|
||||
},
|
||||
'relation_role': None, 'comparator_key': 'normalized_text',
|
||||
}],
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
}, actor_id=None)
|
||||
order_schema_service.publish(
|
||||
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'],
|
||||
)
|
||||
|
||||
draft = excel_template.create_draft(_workbook_upload(), {
|
||||
'template_code': 'IMPACT_BLOCK',
|
||||
'display_name': 'Impact Block',
|
||||
'definition': {
|
||||
'filename_pattern': '{task_no}.xlsx',
|
||||
'mappings': [{
|
||||
'sheet': 'Detail', 'row_mode': 'line', 'start_row': 1, 'target_column': 1,
|
||||
'source_kind': 'order_field', 'source_key': part.id, 'formatter': 'text',
|
||||
}],
|
||||
},
|
||||
}, actor_id=None)
|
||||
excel_template.publish(draft['id'], actor_id=None)
|
||||
|
||||
impact = field_impact_analysis.analyze_unadopt_impact(
|
||||
previous_field_ids={part.id},
|
||||
next_field_ids=set(),
|
||||
)
|
||||
|
||||
assert impact['can_publish'] is False
|
||||
assert part.id in impact['blocked']
|
||||
assert 'excel_template' in impact['blocked'][part.id]['kinds']
|
||||
assert impact['blocked'][part.id]['items']
|
||||
assert impact['blocked'][part.id]['items'][0]['kind'] == 'excel_template'
|
||||
assert impact['blocked'][part.id]['items'][0]['object_id'] is not None
|
||||
assert 'mappings' in impact['blocked'][part.id]['items'][0]['reference_path']
|
||||
assert part.id in impact['blocked_field_ids']
|
||||
@@ -0,0 +1,51 @@
|
||||
"""
|
||||
backend/tests/test_fulfillment_core_rejects_extension.py
|
||||
|
||||
用途:验证履约核心能力拒绝绑定扩展字段资产(阶段 5 收口)。
|
||||
依赖:fulfillment_policy_registry、field_asset_service、Flask 测试 app。
|
||||
逻辑:初始化 Schema 族后,用扩展字段绑 fulfillment.part_number 须抛 FULFILLMENT_FIELD_INVALID。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.models.shipping_order_schema import ShippingOrderField
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
from app.services.shipping_notice import fulfillment_policy_registry
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
|
||||
def test_core_fulfillment_binding_rejects_extension_field(app):
|
||||
"""关键断言:扩展资产不可绑定履约核心 capability。"""
|
||||
with app.app_context():
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
order_schema_service.initialize_schema({'display_name': 'Fulfillment Gate'}, actor_id=None)
|
||||
extension = field_asset_service.create_extension({
|
||||
'field_code': 'custom_part_alias',
|
||||
'scope': 'line',
|
||||
'value_type': 'string',
|
||||
'display_name': '自定义料号',
|
||||
}, actor_id=None)
|
||||
reservation = ShippingOrderField.query.filter_by(field_code='reservation_id').one()
|
||||
qty = ShippingOrderField.query.filter_by(field_code='qty').one()
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
fulfillment_policy_registry.create_draft({
|
||||
'field_bindings': [
|
||||
{
|
||||
'capability_code': 'fulfillment.reservation_identity',
|
||||
'field_id': reservation.id,
|
||||
},
|
||||
{
|
||||
'capability_code': 'fulfillment.part_number',
|
||||
'field_id': extension['id'],
|
||||
},
|
||||
{
|
||||
'capability_code': 'fulfillment.quantity',
|
||||
'field_id': qty.id,
|
||||
},
|
||||
],
|
||||
'change_note': 'must fail',
|
||||
}, actor_id=None)
|
||||
assert exc.value.code == 'SHIPPING.FULFILLMENT_FIELD_INVALID'
|
||||
@@ -8,6 +8,8 @@ backend/tests/test_order_document_profile_creation_service.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
from app.extensions import db
|
||||
@@ -25,7 +27,7 @@ from tests.test_shipping_order_document_profile_service import _bind_ready_profi
|
||||
def _wizard_payload(schema_id: int, document_id: int, *, table_id: str = 'sample-table') -> dict:
|
||||
"""构造已完成三步向导的最小请求,避免测试通过旧 from-sample 创建路径。"""
|
||||
return {
|
||||
'profile_code': 'WIZARD_PROFILE', 'display_name': 'Wizard profile',
|
||||
'display_name': 'Wizard profile',
|
||||
'schema_version_id': schema_id, 'document_id': document_id,
|
||||
'main_table_id': table_id, 'browser_session_id': 'wizard-tab-a', 'operation_id': 'wizard-create-op',
|
||||
}
|
||||
@@ -44,14 +46,21 @@ def test_wizard_completion_creates_profile_sample_revision_audit_and_lease_atomi
|
||||
db.session.add(seed)
|
||||
db.session.commit()
|
||||
sample = _bind_ready_profile_sample(seed.id)
|
||||
created = creation_service.complete_wizard(_wizard_payload(schema.id, sample.document_id), actor_id=None)
|
||||
request_data = _wizard_payload(schema.id, sample.document_id)
|
||||
request_data['profile_code'] = 'CLIENT_SUPPLIED_CODE'
|
||||
created = creation_service.complete_wizard(request_data, actor_id=None)
|
||||
profile_id = created['id']
|
||||
assert re.fullmatch(r'ODP-\d{8}-[A-F0-9]{12}', created['profile_code'])
|
||||
assert created['profile_code'] != 'CLIENT_SUPPLIED_CODE'
|
||||
assert created['draft_revision']['revision_no'] == 1
|
||||
assert created['edit_lease']['browser_session_id'] == 'wizard-tab-a'
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='annotation').count() == 1
|
||||
assert ShippingOrderDocumentProfileDraftRevision.query.filter_by(profile_id=profile_id, revision_no=1).count() == 1
|
||||
assert ShippingOrderDocumentProfileEditLease.query.filter_by(profile_id=profile_id).count() == 1
|
||||
assert ShippingOrderDocumentProfileAudit.query.filter_by(profile_id=profile_id, event_type='wizard_created', operation_id='wizard-create-op').count() == 1
|
||||
audit = ShippingOrderDocumentProfileAudit.query.filter_by(
|
||||
profile_id=profile_id, event_type='wizard_created', operation_id='wizard-create-op',
|
||||
).one()
|
||||
assert audit.detail_json['profile_code'] == created['profile_code']
|
||||
|
||||
|
||||
def test_wizard_completion_invalid_main_table_rolls_back_without_profile(app):
|
||||
@@ -69,6 +78,6 @@ def test_wizard_completion_invalid_main_table_rolls_back_without_profile(app):
|
||||
with pytest.raises(Exception) as caught:
|
||||
creation_service.complete_wizard(_wizard_payload(schema.id, sample.document_id, table_id='missing-table'), actor_id=None)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
|
||||
assert ShippingOrderDocumentProfile.query.filter_by(profile_code='WIZARD_PROFILE').count() == 0
|
||||
assert ShippingOrderDocumentProfile.query.count() == 1
|
||||
assert ShippingOrderDocumentProfileDraftRevision.query.count() == 0
|
||||
assert ShippingOrderDocumentProfileEditLease.query.count() == 0
|
||||
@@ -18,6 +18,8 @@ from app.services.shipping_notice.chat_action_handlers import (
|
||||
ShippingFreezeOrderAction,
|
||||
ShippingGenerateExcelAction,
|
||||
ShippingMarkManualUploadedAction,
|
||||
ShippingRetryUploadAction,
|
||||
_CHAT_FULFILLMENT_WRITE_DISABLED_CODE,
|
||||
)
|
||||
|
||||
|
||||
@@ -38,7 +40,8 @@ def _create_task(user_id: int) -> str:
|
||||
return task.task_no
|
||||
|
||||
|
||||
def test_generate_excel_handler_yields_ui_state_and_message(app, monkeypatch):
|
||||
def test_generate_excel_handler_rejects_chat_turn(app, monkeypatch):
|
||||
"""关键断言:Chat Turn 不得再执行 generate_excel,须改走任务工作台。"""
|
||||
user = User(username="handler_user", email="handler_user@example.com", role="admin", status="active")
|
||||
user.set_password("password")
|
||||
db.session.add(user)
|
||||
@@ -56,9 +59,10 @@ def test_generate_excel_handler_yields_ui_state_and_message(app, monkeypatch):
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
|
||||
called = {"generate_excel": False}
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.chat_action_handlers.shipping_tools.generate_excel",
|
||||
lambda payload: {"status": "ok", "message": "Excel 已生成。", "task_id": task_no, "data": {}},
|
||||
lambda payload: called.update({"generate_excel": True}) or {"status": "ok"},
|
||||
)
|
||||
|
||||
ctx = TurnContext(
|
||||
@@ -76,14 +80,11 @@ def test_generate_excel_handler_yields_ui_state_and_message(app, monkeypatch):
|
||||
),
|
||||
refs={"task_no": task_no},
|
||||
)
|
||||
handler = ShippingGenerateExcelAction()
|
||||
events = list(handler.stream(ctx))
|
||||
event_names = [event.event for event in events]
|
||||
assert "step.started" in event_names
|
||||
assert "ui_state.updated" in event_names
|
||||
assert "message.completed" in event_names
|
||||
completed = next(item for item in events if item.event == "message.completed")
|
||||
assert "Excel 已生成" in str(completed.data.get("content") or "")
|
||||
with pytest.raises(ValidationError) as error:
|
||||
list(ShippingGenerateExcelAction().stream(ctx))
|
||||
|
||||
assert error.value.code == _CHAT_FULFILLMENT_WRITE_DISABLED_CODE
|
||||
assert called["generate_excel"] is False
|
||||
|
||||
|
||||
def test_create_batch_from_intakes_handler_forwards_candidate_nos(app, monkeypatch):
|
||||
@@ -176,8 +177,8 @@ def test_freeze_order_handler_requires_the_chat_version_and_emits_snapshot(app):
|
||||
assert "message.completed" in [event.event for event in events]
|
||||
|
||||
|
||||
def test_manual_upload_handler_forwards_private_evidence_and_actor(app, monkeypatch):
|
||||
"""关键断言:Chat 人工上传只能使用当前用户的回执资产,不接受无证据提交。"""
|
||||
def test_manual_upload_handler_rejects_chat_turn_with_evidence(app, monkeypatch):
|
||||
"""关键断言:即便携带回执证据,Chat 也不得调用 upload_to_freight。"""
|
||||
user = User(username="manual-handler", email="manual-handler@example.com", role="user", status="active")
|
||||
user.set_password("password")
|
||||
db.session.add(user)
|
||||
@@ -189,10 +190,10 @@ def test_manual_upload_handler_forwards_private_evidence_and_actor(app, monkeypa
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
captured: dict = {}
|
||||
called = {"upload": False}
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.chat_action_handlers.shipping_tools.upload_to_freight",
|
||||
lambda payload: captured.update(payload) or {"status": "ok", "message": "已登记"},
|
||||
lambda payload: called.update({"upload": True}) or {"status": "ok", "message": "已登记"},
|
||||
)
|
||||
ctx = TurnContext(
|
||||
turn_id="turn-manual", run_id="turn-manual", session_id="sess-manual", request_id="req-manual",
|
||||
@@ -204,11 +205,11 @@ def test_manual_upload_handler_forwards_private_evidence_and_actor(app, monkeypa
|
||||
refs={"task_no": task_no},
|
||||
)
|
||||
|
||||
events = list(ShippingMarkManualUploadedAction().stream(ctx))
|
||||
with pytest.raises(ValidationError) as error:
|
||||
list(ShippingMarkManualUploadedAction().stream(ctx))
|
||||
|
||||
assert captured["operator_id"] == user.id
|
||||
assert captured["evidence_asset_no"] == "FA-RECEIPT-001"
|
||||
assert any(event.event == "message.completed" for event in events)
|
||||
assert error.value.code == _CHAT_FULFILLMENT_WRITE_DISABLED_CODE
|
||||
assert called["upload"] is False
|
||||
|
||||
|
||||
def test_manual_upload_handler_rejects_chat_turn_without_evidence(app):
|
||||
@@ -235,3 +236,38 @@ def test_manual_upload_handler_rejects_chat_turn_without_evidence(app):
|
||||
list(ShippingMarkManualUploadedAction().stream(ctx))
|
||||
|
||||
assert error.value.code == "SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED"
|
||||
|
||||
|
||||
def test_retry_upload_handler_rejects_chat_turn(app, monkeypatch):
|
||||
"""关键断言:Chat Turn 不得重试货代上传。"""
|
||||
user = User(username="retry-handler", email="retry-handler@example.com", role="user", status="active")
|
||||
user.set_password("password")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
task_no = _create_task(user.id)
|
||||
agent = Agent(
|
||||
name="重试上传 Agent", description="t", dify_api_key="k", api_base_url="http://example.com",
|
||||
agent_code="shipping_notice_retry", runtime_provider="hybrid", conversation_mode="task_chat",
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
called = {"upload": False}
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.chat_action_handlers.shipping_tools.upload_to_freight",
|
||||
lambda payload: called.update({"upload": True}) or {"status": "ok"},
|
||||
)
|
||||
ctx = TurnContext(
|
||||
turn_id="turn-retry", run_id="turn-retry", session_id="sess-retry", request_id="req-retry",
|
||||
user=user, agent=agent,
|
||||
input=TurnInput(
|
||||
type="action", display_text="重试上传", action_type="shipping.retry_upload",
|
||||
payload={"task_no": task_no},
|
||||
),
|
||||
refs={"task_no": task_no},
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as error:
|
||||
list(ShippingRetryUploadAction().stream(ctx))
|
||||
|
||||
assert error.value.code == _CHAT_FULFILLMENT_WRITE_DISABLED_CODE
|
||||
assert called["upload"] is False
|
||||
@@ -45,25 +45,20 @@ from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
|
||||
|
||||
def _auto_definition() -> tuple[ShippingIdentityDefinition, ShippingIdentityRuleSet]:
|
||||
"""创建管理员配置的邮箱定义及冻结发布规则集快照。"""
|
||||
"""创建管理员配置的识别定义及冻结发布规则集快照(使用标准 bill_to_customer)。"""
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
if schema is None:
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
field = ShippingOrderField.query.filter_by(schema_id=schema.id, field_code='sender_email').one_or_none()
|
||||
if field is None:
|
||||
field = ShippingOrderField(
|
||||
schema_id=schema.id, field_code='sender_email', scope='header', value_type='string',
|
||||
field_category='general_context', collection_mode='deterministic_context',
|
||||
)
|
||||
db.session.add(field)
|
||||
db.session.flush()
|
||||
field = ShippingOrderField.query.filter_by(field_code='bill_to_customer').one()
|
||||
field_config = {
|
||||
'field_id': field.id, 'field_code': field.field_code, 'display_name': 'Sender email',
|
||||
'field_id': field.id, 'field_code': field.field_code, 'display_name': 'Bill To Customer',
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': True, 'normalizer_key': 'lowercase_trim',
|
||||
'context_source': {'provider_key': 'mail_header', 'option_key': 'from_email'},
|
||||
}
|
||||
schema_version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
if schema_version is None:
|
||||
|
||||
@@ -60,28 +60,33 @@ def _seed_candidate(*, sender: str = ''):
|
||||
|
||||
def _published_field(*, code: str, option_key: str | None = None):
|
||||
"""发布允许客户识别的 Header 字段,并返回字段、版本和冻结配置。"""
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
|
||||
del option_key # mail/context 字段不再登记为订单资产;测试改用语义等价的 Header 字段值。
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
if schema is None:
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
field = ShippingOrderField(
|
||||
schema_id=schema.id, field_code=code, scope='header', value_type='string',
|
||||
field_category='general_context' if option_key else 'order_header',
|
||||
collection_mode='deterministic_context' if option_key else 'llm_extraction',
|
||||
)
|
||||
db.session.add(field)
|
||||
db.session.flush()
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
field = ShippingOrderField.query.filter_by(field_code=code).one_or_none()
|
||||
if field is None:
|
||||
field = ShippingOrderField(
|
||||
field_code=code, scope='header', value_type='string',
|
||||
field_category='order_header', collection_mode='llm_extraction',
|
||||
asset_kind='extension', storage_mode='json_only', status='active',
|
||||
display_name_default=code,
|
||||
)
|
||||
db.session.add(field)
|
||||
db.session.flush()
|
||||
current = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
if current is not None:
|
||||
current.status = 'retired'
|
||||
config = {
|
||||
'field_id': field.id, 'field_code': code, 'display_name': code, 'scope': 'header',
|
||||
'value_type': 'string', 'enabled': True, 'available_for_customer_identity': True,
|
||||
'normalizer_key': 'lowercase_trim' if option_key == 'from_email' else 'uppercase_trim',
|
||||
'normalizer_key': 'lowercase_trim',
|
||||
}
|
||||
if option_key:
|
||||
config['context_source'] = {'provider_key': 'mail_header', 'option_key': option_key}
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=ShippingOrderSchemaVersion.query.count() + 1,
|
||||
status='published', definition_json={'fields': [config]}, checksum=f'{ShippingOrderSchemaVersion.query.count() + 1:064x}',
|
||||
@@ -138,7 +143,7 @@ def _customer(name, code):
|
||||
def test_accepted_field_value_resolves_customer_without_mail_header_bypass(app):
|
||||
"""客户命中必须来自 accepted FieldValue;Intake 邮件头即使不同也不能覆盖。"""
|
||||
with app.app_context():
|
||||
field, version = _published_field(code='sender_email', option_key='from_email')
|
||||
field, version = _published_field(code='bill_to_customer')
|
||||
definition, rule_set = _definition(field)
|
||||
customer = _customer('无锡宇辰有限公司', 'WYC')
|
||||
identity_rules.create_evidence(
|
||||
@@ -216,7 +221,7 @@ def test_site_field_resolves_site_only_and_freezes_context_field_snapshot(app):
|
||||
def test_equal_customer_matches_remain_ambiguous(app):
|
||||
"""同一已裁决字段值映射多个客户时必须保留歧义。"""
|
||||
with app.app_context():
|
||||
field, version = _published_field(code='sender_email', option_key='from_email')
|
||||
field, version = _published_field(code='bill_to_customer')
|
||||
definition, _rule_set = _definition(field)
|
||||
for customer in (_customer('客户甲', 'AAA'), _customer('客户乙', 'BBB')):
|
||||
identity_rules.create_evidence(
|
||||
@@ -236,7 +241,7 @@ def test_equal_customer_matches_remain_ambiguous(app):
|
||||
def test_shadow_resolution_is_idempotent_and_accuracy_uses_labels_only(app):
|
||||
"""重算复用同一记录;准确率只统计人工标签且不反向绑定业务。"""
|
||||
with app.app_context():
|
||||
field, version = _published_field(code='sender_email', option_key='from_email')
|
||||
field, version = _published_field(code='bill_to_customer')
|
||||
definition, _rule_set = _definition(field)
|
||||
customer = _customer('ACME', 'ACM')
|
||||
identity_rules.create_evidence(
|
||||
|
||||
@@ -118,6 +118,35 @@ def test_layout_schedule_is_idempotent_and_force_creates_next_version(app):
|
||||
assert job.payload_json == {'layout_version_id': forced.id}
|
||||
|
||||
|
||||
def test_layout_schedule_reuses_same_owner_completed_layout_for_duplicate_document(app):
|
||||
"""相同管理员重复上传相同文件时,新 Document 必须直接复用可用布局。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
original = _document()
|
||||
ready = record_inline_layout_snapshot(original, _snapshot())
|
||||
duplicate_intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-LAYOUT-DUPLICATE', asset_id=original.asset_id,
|
||||
user_id=db.session.get(ShippingNoticeIntake, original.intake_id).user_id,
|
||||
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6',
|
||||
)
|
||||
db.session.add(duplicate_intake)
|
||||
db.session.flush()
|
||||
duplicate = ShippingNoticeDocument(
|
||||
intake_id=duplicate_intake.id, asset_id=original.asset_id, document_type='attachment',
|
||||
attachment_key='duplicate.pdf', filename='duplicate.pdf', content_hash=original.content_hash,
|
||||
classification='order_notice', parse_status='parsed',
|
||||
)
|
||||
db.session.add(duplicate)
|
||||
db.session.flush()
|
||||
|
||||
reused = schedule_layout_version(duplicate)
|
||||
db.session.commit()
|
||||
|
||||
assert reused.id == ready.id
|
||||
assert duplicate.current_layout_version_id == ready.id
|
||||
assert ShippingDocumentLayoutVersion.query.count() == 1
|
||||
|
||||
|
||||
def test_layout_parser_revision_change_creates_new_version_without_force(app):
|
||||
"""运维提升 parser revision 后不得复用旧 Provider/模型结果。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
|
||||
@@ -26,9 +26,17 @@ from app.services.shipping_notice import excel_template
|
||||
from app.services.shipping_notice.export import _filename, _system_fact, generate_shipment_excel
|
||||
from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export
|
||||
from app.services.shipping_notice.reservation_service import record_inventory_verification
|
||||
from app.services.shipping_notice.standard_field_registry import DEFAULT_SCHEMA_FAMILY_CODE
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
|
||||
|
||||
def _lookup_standard_fields(*codes: str) -> dict[str, ShippingOrderField]:
|
||||
"""从全局标准资产目录取字段,供模板测试引用稳定 field_id。"""
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
return {code: ShippingOrderField.query.filter_by(field_code=code).one() for code in codes}
|
||||
|
||||
|
||||
def _inventory_field_id(field_code: str) -> str:
|
||||
"""返回库存字段目录 ID,使模板测试覆盖当前发布契约。"""
|
||||
return str(ShippingInventoryField.query.filter_by(field_code=field_code).one().id)
|
||||
@@ -159,14 +167,13 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
"""发布模板后按稳定 field_id 写入订单值,并锁定模板、Schema、Profile 与库存快照。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||||
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
customer = ShippingOrderField(schema_id=schema.id, field_code='customer_code', scope='header', value_type='string')
|
||||
po_number = ShippingOrderField(schema_id=schema.id, field_code='po_number', scope='header', value_type='string')
|
||||
part = ShippingOrderField(schema_id=schema.id, field_code='part_number', scope='line', value_type='string')
|
||||
db.session.add_all([customer, po_number, part])
|
||||
db.session.flush()
|
||||
fields = _lookup_standard_fields('customer_code', 'customer_po_number', 'part_number')
|
||||
customer = fields['customer_code']
|
||||
po_number = fields['customer_po_number']
|
||||
part = fields['part_number']
|
||||
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={
|
||||
'fields': [{'field_id': customer.id}, {'field_id': po_number.id}, {'field_id': part.id}],
|
||||
}, checksum='s' * 64)
|
||||
@@ -263,12 +270,10 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
def test_header_mapping_rejects_line_order_field(app):
|
||||
"""订单头区域不得引用明细字段,避免把多行值错误压缩为单个表头值。"""
|
||||
with app.app_context():
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||||
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
part = ShippingOrderField(schema_id=schema.id, field_code='part_number', scope='line', value_type='string')
|
||||
db.session.add(part)
|
||||
db.session.flush()
|
||||
part = _lookup_standard_fields('part_number')['part_number']
|
||||
db.session.add(ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published',
|
||||
definition_json={'fields': [{'field_id': part.id}]}, checksum='s' * 64,
|
||||
@@ -363,10 +368,9 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path
|
||||
"""库存行顺序与订单相反时仍须按稳定 match_keys 写入正确 ODM,禁止按数组下标配对。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||||
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
|
||||
db.session.add(schema); db.session.flush()
|
||||
part = ShippingOrderField(schema_id=schema.id, field_code='part_number', scope='line', value_type='string')
|
||||
db.session.add(part); db.session.flush()
|
||||
part = _lookup_standard_fields('part_number')['part_number']
|
||||
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={
|
||||
'fields': [{'field_id': part.id}],
|
||||
})
|
||||
@@ -499,9 +503,11 @@ def test_template_publish_rejects_order_field_removed_from_current_schema(app):
|
||||
order_schema_service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
old_field = order_schema_service.save_field({
|
||||
'field_code': 'old_part', 'scope': 'line', 'value_type': 'string',
|
||||
'display_name': '旧料号',
|
||||
}, actor_id=None)
|
||||
new_field = order_schema_service.save_field({
|
||||
'field_code': 'new_part', 'scope': 'line', 'value_type': 'string',
|
||||
'display_name': '新料号',
|
||||
}, actor_id=None)
|
||||
|
||||
def config(field_id: str) -> dict:
|
||||
@@ -539,11 +545,11 @@ def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app,
|
||||
"""同一匹配键对应多个不同 ODM 时必须阻断,且不得留下半成品 Excel。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||||
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
|
||||
db.session.add(schema); db.session.flush()
|
||||
part = ShippingOrderField(schema_id=schema.id, field_code='part_number', scope='line', value_type='string')
|
||||
part = _lookup_standard_fields('part_number')['part_number']
|
||||
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
|
||||
db.session.add_all([part, version]); db.session.flush()
|
||||
db.session.add(version); db.session.flush()
|
||||
draft = excel_template.create_draft(_workbook_upload(), {
|
||||
'template_code': 'AMBIGUOUS', 'display_name': 'Ambiguous',
|
||||
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
"""
|
||||
backend/tests/test_shipping_field_asset_governance.py
|
||||
|
||||
用途:字段资产治理回归——标准种子、扩展生命周期、标准不可弃用、物理删除禁止。
|
||||
依赖:pytest、app 测试夹具、field_asset_service、standard_field_registry。
|
||||
逻辑:覆盖阶段 1–3 关键闸门;不依赖前端。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app import db
|
||||
from app.services.shipping_notice import field_asset_service as assets
|
||||
from app.services.shipping_notice.standard_field_registry import (
|
||||
DEFAULT_V1_ADOPTION_CODES,
|
||||
STANDARD_FIELD_SPECS,
|
||||
assert_registry_consistent,
|
||||
)
|
||||
|
||||
|
||||
def test_registry_is_consistent_and_suggests_fifteen():
|
||||
"""断言:57 项注册表自洽;默认建议采用集恰好 15 且均在标准目录内。"""
|
||||
assert_registry_consistent()
|
||||
assert len(STANDARD_FIELD_SPECS) == 57
|
||||
assert len(DEFAULT_V1_ADOPTION_CODES) == 15
|
||||
assert set(DEFAULT_V1_ADOPTION_CODES) <= set(STANDARD_FIELD_SPECS)
|
||||
|
||||
|
||||
def test_ensure_standard_assets_seeded(app):
|
||||
"""断言:种子后至少 57 个 system_standard active 资产。"""
|
||||
with app.app_context():
|
||||
inserted = assets.ensure_standard_assets_seeded(actor_id=None)
|
||||
assert inserted >= 0
|
||||
listed = assets.list_assets(asset_kind='system_standard', status='active')
|
||||
assert listed['standard_count'] == 57
|
||||
assert 'part_number' in {item['field_code'] for item in listed['items']}
|
||||
|
||||
|
||||
def test_extension_create_retire_restore_and_forbid_delete(app):
|
||||
"""断言:扩展可创建/弃用/恢复;标准不可弃用;物理删除统一拒绝。"""
|
||||
with app.app_context():
|
||||
assets.ensure_standard_assets_seeded()
|
||||
created = assets.create_extension(
|
||||
{
|
||||
'field_code': 'ext_project_code',
|
||||
'scope': 'header',
|
||||
'value_type': 'string',
|
||||
'display_name': '客户项目号',
|
||||
},
|
||||
actor_id=None,
|
||||
)
|
||||
assert created['asset_kind'] == 'extension'
|
||||
assert created['storage_mode'] == 'json_only'
|
||||
assert created['storage_kind'] == 'extension_json'
|
||||
assert 'header_values_json' in created['storage_path']
|
||||
|
||||
with pytest.raises(ConflictError) as blocked:
|
||||
assets.forbid_physical_delete()
|
||||
assert blocked.value.code == 'SHIPPING.FIELD_ASSET_DELETE_FORBIDDEN'
|
||||
|
||||
standard = next(
|
||||
item for item in assets.list_assets(asset_kind='system_standard')['items']
|
||||
if item['field_code'] == 'qty'
|
||||
)
|
||||
assert standard['storage_kind'] == 'typed_column'
|
||||
assert 'shipping_order_snapshot_lines' in standard['storage_path']
|
||||
|
||||
json_only_standard = next(
|
||||
item for item in assets.list_assets(asset_kind='system_standard')['items']
|
||||
if item['field_code'] == 'contract_number'
|
||||
)
|
||||
assert json_only_standard['storage_mode'] == 'json_only'
|
||||
assert json_only_standard['storage_kind'] == 'standard_json'
|
||||
|
||||
with pytest.raises(ConflictError):
|
||||
assets.retire_extension(standard['id'], reason='should fail', actor_id=None)
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
assets.retire_extension(created['id'], reason=' ', actor_id=None)
|
||||
|
||||
retired = assets.retire_extension(created['id'], reason='no longer needed', actor_id=None)
|
||||
assert retired['status'] == 'retired'
|
||||
audits = assets.list_asset_audits(created['id'])
|
||||
assert any(item['event_type'] == 'extension_retired' for item in audits['items'])
|
||||
restored = assets.restore_extension(created['id'], reason='needed again', actor_id=None)
|
||||
assert restored['status'] == 'active'
|
||||
|
||||
# 乐观锁:缺少/错误 expected_updated_at 须冲突
|
||||
with pytest.raises(ValidationError) as lock_required:
|
||||
assets.update_extension(
|
||||
created['id'],
|
||||
{'display_name': '新名称'},
|
||||
actor_id=None,
|
||||
)
|
||||
assert lock_required.value.code == 'SHIPPING.FIELD_ASSET_LOCK_REQUIRED'
|
||||
current = assets.get_asset(created['id'])
|
||||
with pytest.raises(ConflictError) as lock_conflict:
|
||||
assets.update_extension(
|
||||
created['id'],
|
||||
{'display_name': '新名称', 'expected_updated_at': '2000-01-01T00:00:00'},
|
||||
actor_id=None,
|
||||
)
|
||||
assert lock_conflict.value.code == 'SHIPPING.FIELD_ASSET_VERSION_CONFLICT'
|
||||
updated = assets.update_extension(
|
||||
created['id'],
|
||||
{'display_name': '新名称', 'expected_updated_at': current['updated_at']},
|
||||
actor_id=None,
|
||||
)
|
||||
assert updated['display_name_default'] == '新名称'
|
||||
|
||||
|
||||
def test_schema_adopt_writes_per_field_audits(app):
|
||||
"""断言:保存草稿采用/取消采用时按 field_id 写审计,字段资产时间线可查。"""
|
||||
from app.models import ShippingOrderSchemaAuditEvent, ShippingOrderSchemaVersion
|
||||
from app.services.shipping_notice.order_schema import service
|
||||
|
||||
def _cfg(field_id: str, *, name: str, value_type: str = 'string') -> dict:
|
||||
"""构造可保存的最小字段采用配置。"""
|
||||
is_decimal = value_type == 'decimal'
|
||||
return {
|
||||
'field_id': field_id,
|
||||
'display_name': name,
|
||||
'required': True,
|
||||
'aliases': ['Alias'],
|
||||
'normalizer_key': 'decimal' if is_decimal else 'uppercase_trim',
|
||||
'validator_keys': ['positive_decimal'] if is_decimal else [],
|
||||
'enum_options': [],
|
||||
'evidence_policy': {
|
||||
'required': True,
|
||||
'source_precedence': ['attachment_table', 'email_body_table', 'dify_llm'],
|
||||
'conflict_policy': 'block',
|
||||
'allow_single_source': True,
|
||||
},
|
||||
'relation_role': None,
|
||||
'comparator_key': 'decimal' if is_decimal else 'normalized_text',
|
||||
'extraction_instruction': '仅提取订单明确出现的值',
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
qty = next(
|
||||
item for item in assets.list_assets(asset_kind='system_standard')['items']
|
||||
if item['field_code'] == 'qty'
|
||||
)
|
||||
po = next(
|
||||
item for item in assets.list_assets(asset_kind='system_standard')['items']
|
||||
if item['field_code'] == 'customer_po_number'
|
||||
)
|
||||
assert po['storage_kind'] == 'typed_column'
|
||||
contract_number = next(
|
||||
item for item in assets.list_assets(asset_kind='system_standard')['items']
|
||||
if item['field_code'] == 'contract_number'
|
||||
)
|
||||
assert contract_number['storage_kind'] == 'standard_json'
|
||||
|
||||
draft = service.create_draft({'change_note': 'adopt audit'}, actor_id=None)
|
||||
version = db.session.get(ShippingOrderSchemaVersion, draft['id'])
|
||||
assert version is not None
|
||||
service.save_draft(draft['id'], {
|
||||
'fields': [
|
||||
_cfg(qty['id'], name='数量', value_type='decimal'),
|
||||
_cfg(po['id'], name='客户PO'),
|
||||
],
|
||||
'expected_lock_version': version.lock_version,
|
||||
})
|
||||
adopted = (
|
||||
ShippingOrderSchemaAuditEvent.query
|
||||
.filter_by(field_id=qty['id'], event_type='field_adopted')
|
||||
.all()
|
||||
)
|
||||
assert len(adopted) == 1
|
||||
assert adopted[0].change_summary_json.get('field_id') == qty['id']
|
||||
|
||||
timeline = assets.list_asset_audits(qty['id'])
|
||||
assert any(item['event_type'] == 'field_adopted' for item in timeline['items'])
|
||||
|
||||
version = db.session.get(ShippingOrderSchemaVersion, draft['id'])
|
||||
assert version is not None
|
||||
service.save_draft(draft['id'], {
|
||||
'fields': [_cfg(po['id'], name='客户PO')],
|
||||
'expected_lock_version': version.lock_version,
|
||||
})
|
||||
unadopted = (
|
||||
ShippingOrderSchemaAuditEvent.query
|
||||
.filter_by(field_id=qty['id'], event_type='field_unadopted')
|
||||
.all()
|
||||
)
|
||||
assert len(unadopted) == 1
|
||||
timeline2 = assets.list_asset_audits(qty['id'])
|
||||
assert {item['event_type'] for item in timeline2['items']} >= {
|
||||
'field_adopted', 'field_unadopted',
|
||||
}
|
||||
|
||||
detail = assets.get_asset(po['id'])
|
||||
assert any(item['schema_version_id'] == draft['id'] for item in detail['adoptions'])
|
||||
assert any(item.get('schema_code') for item in detail['adoptions'])
|
||||
|
||||
|
||||
def test_retire_extension_requires_impact_confirmation_when_blocked(app, tmp_path, monkeypatch):
|
||||
"""断言:扩展字段被 Excel 模板引用时,弃用须 confirm_impact。"""
|
||||
from io import BytesIO
|
||||
|
||||
from openpyxl import Workbook
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app.services.shipping_notice import excel_template
|
||||
from app.services.shipping_notice.order_schema import service
|
||||
|
||||
objects: dict[str, bytes] = {}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.excel_template.file_asset_storage.upload_bytes',
|
||||
lambda *, storage_key, data, content_type: objects.__setitem__(storage_key, bytes(data)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.excel_template.file_asset_storage.get_bytes',
|
||||
lambda storage_key: objects[storage_key],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.excel_template.file_asset_storage.delete_object',
|
||||
lambda storage_key: objects.pop(storage_key, None),
|
||||
)
|
||||
monkeypatch.setattr('app.services.shipping_notice.excel_template.file_asset_storage.bucket_name', 'test-bucket')
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
|
||||
stream = BytesIO()
|
||||
Workbook().save(stream)
|
||||
stream.seek(0)
|
||||
upload = FileStorage(
|
||||
stream=stream, filename='retire.xlsx',
|
||||
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': 'Retire Gate'}, actor_id=None)
|
||||
created = assets.create_extension(
|
||||
{
|
||||
'field_code': 'ext_retire_gate',
|
||||
'scope': 'header',
|
||||
'value_type': 'string',
|
||||
'display_name': '弃用门禁字段',
|
||||
},
|
||||
actor_id=None,
|
||||
)
|
||||
draft = excel_template.create_draft(upload, {
|
||||
'template_code': 'RETIRE_GATE',
|
||||
'display_name': 'Retire Gate',
|
||||
'definition': {
|
||||
'filename_pattern': '{task_no}.xlsx',
|
||||
'mappings': [{
|
||||
'sheet': 'Sheet', 'row_mode': 'header', 'start_row': 1, 'target_column': 1,
|
||||
'source_kind': 'order_field', 'source_key': created['id'], 'formatter': 'text',
|
||||
}],
|
||||
},
|
||||
}, actor_id=None)
|
||||
# draft 状态模板引用同样阻断弃用,无需发布 Schema/模板。
|
||||
assert draft['status'] == 'draft'
|
||||
|
||||
with pytest.raises(ConflictError) as blocked:
|
||||
assets.retire_extension(created['id'], reason='still referenced', actor_id=None)
|
||||
assert blocked.value.code == 'SHIPPING.FIELD_ASSET_RETIRE_IMPACT_CONFIRM_REQUIRED'
|
||||
assert blocked.value.details.get('blocking_items')
|
||||
|
||||
retired = assets.retire_extension(
|
||||
created['id'], reason='confirmed with impact', actor_id=None, confirm_impact=True,
|
||||
)
|
||||
assert retired['status'] == 'retired'
|
||||
|
||||
|
||||
def test_second_schema_family_is_not_supported(app):
|
||||
"""断言:系统仅允许唯一 STANDARD_SHIPPING_NOTICE,禁止新建第二族。"""
|
||||
from app.core.errors import ConflictError
|
||||
from app.services.shipping_notice.order_schema import service
|
||||
from app.services.shipping_notice.standard_field_registry import DEFAULT_SCHEMA_FAMILY_CODE
|
||||
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '发货订单 Schema'}, actor_id=None)
|
||||
families = service.list_schema_families()
|
||||
assert families['default_family_code'] == DEFAULT_SCHEMA_FAMILY_CODE
|
||||
assert len(families['items']) == 1
|
||||
assert families['items'][0]['schema_code'] == DEFAULT_SCHEMA_FAMILY_CODE
|
||||
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
service.create_schema_family(
|
||||
{'schema_code': 'ALT_SHIPPING_FAMILY', 'display_name': '备选族'},
|
||||
actor_id=None,
|
||||
)
|
||||
assert exc.value.code == 'SHIPPING.SCHEMA_FAMILY_NOT_SUPPORTED'
|
||||
|
||||
|
||||
def test_single_schema_supports_multi_version_draft(app):
|
||||
"""断言:唯一 Schema 可创建草稿并出现在 get_state 版本列表。"""
|
||||
from app.services.shipping_notice.order_schema import service
|
||||
from app.services.shipping_notice.standard_field_registry import DEFAULT_SCHEMA_FAMILY_CODE
|
||||
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '发货订单 Schema'}, actor_id=None)
|
||||
draft = service.create_draft({'change_note': 'first draft'}, actor_id=None)
|
||||
state = service.get_state()
|
||||
assert state['schema']['schema_code'] == DEFAULT_SCHEMA_FAMILY_CODE
|
||||
assert len(state['versions']) == 1
|
||||
assert state['versions'][0]['id'] == draft['id']
|
||||
assert state['versions'][0]['status'] == 'draft'
|
||||
|
||||
|
||||
def test_context_codes_cannot_be_assets(app):
|
||||
"""断言:邮件/发件人上下文编码不得登记为订单字段资产。"""
|
||||
with app.app_context():
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
assets.create_extension(
|
||||
{
|
||||
'field_code': 'sender_email',
|
||||
'scope': 'header',
|
||||
'value_type': 'string',
|
||||
'display_name': '发件人',
|
||||
},
|
||||
actor_id=None,
|
||||
)
|
||||
assert exc.value.code == 'SHIPPING.FIELD_ASSET_CONTEXT_FORBIDDEN'
|
||||
@@ -0,0 +1,150 @@
|
||||
"""
|
||||
backend/tests/test_shipping_field_asset_service.py
|
||||
|
||||
用途:验证字段资产治理服务——标准种子、扩展 CRUD、弃用恢复与物理删除禁止。
|
||||
依赖:Flask 测试 app、field_asset_service、standard_field_registry。
|
||||
逻辑:覆盖 57 项标准资产、扩展创建门禁、标准只读/不可弃用及影响分析结构。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models.shipping_order_schema import ShippingOrderField
|
||||
from app.services.shipping_notice import field_impact_analysis
|
||||
from app.services.shipping_notice.standard_field_registry import STANDARD_FIELD_SPECS
|
||||
|
||||
|
||||
def _field_assets():
|
||||
"""延迟导入 field_asset_service,避免标准注册表循环依赖。"""
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
return field_asset_service
|
||||
|
||||
|
||||
def test_ensure_standard_assets_seeds_fifty_seven_fields(app):
|
||||
"""关键断言:注册表 57 项标准资产落库且 kind 为 system_standard。"""
|
||||
with app.app_context():
|
||||
inserted = _field_assets().ensure_standard_assets_seeded()
|
||||
assert inserted == len(STANDARD_FIELD_SPECS)
|
||||
rows = ShippingOrderField.query.filter_by(asset_kind='system_standard').all()
|
||||
assert len(rows) == 57
|
||||
assert {row.field_code for row in rows} == set(STANDARD_FIELD_SPECS.keys())
|
||||
|
||||
|
||||
def test_create_extension_field(app):
|
||||
"""扩展字段可创建且 storage 固定为 json_only。"""
|
||||
with app.app_context():
|
||||
payload = _field_assets().create_extension({
|
||||
'field_code': 'test_extension_alpha',
|
||||
'scope': 'header',
|
||||
'value_type': 'string',
|
||||
'display_name': 'Test Extension',
|
||||
'semantic_description': 'For unit tests',
|
||||
}, actor_id=1)
|
||||
assert payload['field_code'] == 'test_extension_alpha'
|
||||
assert payload['asset_kind'] == 'extension'
|
||||
assert payload['storage_mode'] == 'json_only'
|
||||
assert payload['status'] == 'active'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('code', ['sender_email', 'mail_from', 'sender_domain'])
|
||||
def test_create_extension_rejects_mail_context_codes(app, code):
|
||||
"""mail/context 类编码不得登记为订单字段资产。"""
|
||||
with app.app_context():
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
_field_assets().create_extension({
|
||||
'field_code': code,
|
||||
'scope': 'header',
|
||||
'value_type': 'string',
|
||||
'display_name': 'Forbidden',
|
||||
}, actor_id=1)
|
||||
assert exc_info.value.code == 'SHIPPING.FIELD_ASSET_CONTEXT_FORBIDDEN'
|
||||
|
||||
|
||||
def test_create_extension_rejects_standard_code_collision(app):
|
||||
"""扩展 field_code 不得与系统标准编码冲突。"""
|
||||
with app.app_context():
|
||||
_field_assets().ensure_standard_assets_seeded()
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
_field_assets().create_extension({
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'value_type': 'string',
|
||||
'display_name': 'Duplicate',
|
||||
}, actor_id=1)
|
||||
assert exc_info.value.code == 'SHIPPING.FIELD_ASSET_STANDARD_CODE'
|
||||
|
||||
|
||||
def test_cannot_retire_standard_field(app):
|
||||
"""系统标准字段不可弃用,应通过 Schema 取消采用。"""
|
||||
with app.app_context():
|
||||
_field_assets().ensure_standard_assets_seeded()
|
||||
standard = ShippingOrderField.query.filter_by(field_code='qty').one()
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
_field_assets().retire_extension(
|
||||
standard.id, reason='should fail', actor_id=1,
|
||||
)
|
||||
assert exc_info.value.code == 'SHIPPING.FIELD_ASSET_STANDARD_NO_RETIRE'
|
||||
|
||||
|
||||
def test_retire_and_restore_extension_with_reason(app):
|
||||
"""扩展字段可带原因弃用并恢复为 active。"""
|
||||
with app.app_context():
|
||||
created = _field_assets().create_extension({
|
||||
'field_code': 'retire_restore_ext',
|
||||
'scope': 'line',
|
||||
'value_type': 'string',
|
||||
'display_name': 'Retire Restore',
|
||||
}, actor_id=1)
|
||||
retired = _field_assets().retire_extension(
|
||||
created['id'], reason='no longer needed', actor_id=1,
|
||||
)
|
||||
assert retired['status'] == 'retired'
|
||||
assert retired['retired_reason'] == 'no longer needed'
|
||||
restored = _field_assets().restore_extension(
|
||||
created['id'], reason='back in use', actor_id=1,
|
||||
)
|
||||
assert restored['status'] == 'active'
|
||||
assert restored['retired_reason'] is None
|
||||
|
||||
|
||||
def test_retire_extension_requires_reason(app):
|
||||
"""弃用扩展字段时 reason 不能为空。"""
|
||||
with app.app_context():
|
||||
created = _field_assets().create_extension({
|
||||
'field_code': 'reason_required_ext',
|
||||
'scope': 'header',
|
||||
'value_type': 'string',
|
||||
'display_name': 'Reason Required',
|
||||
}, actor_id=1)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
_field_assets().retire_extension(created['id'], reason=' ', actor_id=1)
|
||||
assert exc_info.value.code == 'SHIPPING.FIELD_ASSET_RETIRE_REASON_REQUIRED'
|
||||
|
||||
|
||||
def test_physical_delete_forbidden(app):
|
||||
"""字段资产禁止物理删除。"""
|
||||
with app.app_context():
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
_field_assets().forbid_physical_delete()
|
||||
assert exc_info.value.code == 'SHIPPING.FIELD_ASSET_DELETE_FORBIDDEN'
|
||||
|
||||
|
||||
def test_analyze_field_impact_structure(app):
|
||||
"""影响分析返回 blocking_kinds、historical 与 can_unadopt/can_retire_extension 结构。"""
|
||||
with app.app_context():
|
||||
_field_assets().ensure_standard_assets_seeded()
|
||||
field = ShippingOrderField.query.filter_by(field_code='part_number').one()
|
||||
impact = field_impact_analysis.analyze_field_impact(field.id)
|
||||
assert impact['field_id'] == field.id
|
||||
assert impact['field_code'] == 'part_number'
|
||||
assert isinstance(impact['blocking_kinds'], list)
|
||||
assert impact['blocking_count'] == len(impact['blocking_kinds'])
|
||||
assert set(impact['historical']) == {
|
||||
'observation_count', 'decision_count', 'value_count',
|
||||
'immutable_schema_version_count', 'blocks_publish',
|
||||
}
|
||||
assert impact['can_unadopt'] is True
|
||||
assert impact['can_retire_extension'] is False
|
||||
@@ -0,0 +1,250 @@
|
||||
"""
|
||||
backend/tests/test_shipping_field_governance_migration.py
|
||||
|
||||
用途:验证字段资产治理重建迁移(1b2c3d4e5f6a)在 SQLite 上可升级/降级并种子默认族。
|
||||
依赖:Alembic Operations、临时内存库、standard_field_registry。
|
||||
逻辑:构造迁移前 fields(含 schema_id)、schemas、Excel 模板与导出产物对 schema_version 的 FK 依赖图 →
|
||||
upgrade → 断言无 schema_id、57 标准资产、空默认族、CHECK 约束同步;downgrade → 断言结构回退
|
||||
(schema_id 恢复、asset_kind 消失) 且种子行清空;下游 orphan 引用不阻断迁移。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
from app.services.shipping_notice.standard_field_registry import (
|
||||
DEFAULT_SCHEMA_FAMILY_CODE,
|
||||
STANDARD_FIELD_SPECS,
|
||||
)
|
||||
|
||||
|
||||
def _build_pre_migration_schema(metadata: sa.MetaData) -> None:
|
||||
"""
|
||||
构造接近真实依赖的迁移前表骨架。
|
||||
|
||||
核心逻辑:包含 shipping_export_artifacts → schema_versions / excel_templates 外键,
|
||||
用于覆盖「删版本时被下游 FK 阻断」的回归场景(SQLite 开启 foreign_keys)。
|
||||
"""
|
||||
sa.Table(
|
||||
'users', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_order_schemas', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('schema_code', sa.String(64)),
|
||||
sa.Column('display_name', sa.String(128)),
|
||||
sa.Column('description', sa.Text()),
|
||||
sa.Column('auto_creation_policy_json', sa.JSON()),
|
||||
sa.Column('status', sa.String(16)),
|
||||
sa.Column('created_at', sa.DateTime()),
|
||||
sa.Column('updated_at', sa.DateTime()),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_order_fields', metadata,
|
||||
sa.Column('id', sa.String(36), primary_key=True),
|
||||
sa.Column('schema_id', sa.Integer(), sa.ForeignKey('shipping_order_schemas.id')),
|
||||
sa.Column('field_code', sa.String(64)),
|
||||
sa.Column('scope', sa.String(16)),
|
||||
sa.Column('value_type', sa.String(16)),
|
||||
sa.Column('field_category', sa.String(32)),
|
||||
sa.Column('collection_mode', sa.String(32)),
|
||||
sa.Column('display_sequence', sa.Integer()),
|
||||
sa.Column('status', sa.String(16)),
|
||||
sa.Column('published_once', sa.Boolean()),
|
||||
sa.Column('created_at', sa.DateTime()),
|
||||
sa.Column('updated_at', sa.DateTime()),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_order_schema_versions', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('schema_id', sa.Integer(), sa.ForeignKey('shipping_order_schemas.id')),
|
||||
sa.Column('version', sa.Integer()),
|
||||
sa.Column('status', sa.String(16)),
|
||||
sa.Column('definition_json', sa.JSON()),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_order_schema_audit_events', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('schema_id', sa.Integer()),
|
||||
sa.Column('event_type', sa.String(64)),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_fulfillment_policies', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('schema_id', sa.Integer(), sa.ForeignKey('shipping_order_schemas.id')),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_excel_templates', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('template_code', sa.String(64)),
|
||||
sa.Column('display_name', sa.String(128)),
|
||||
sa.Column('version', sa.Integer()),
|
||||
sa.Column('status', sa.String(16)),
|
||||
sa.Column('storage_provider', sa.String(32)),
|
||||
sa.Column('storage_bucket', sa.String(128)),
|
||||
sa.Column('storage_key', sa.String(512)),
|
||||
sa.Column('original_filename', sa.String(255)),
|
||||
sa.Column('file_checksum', sa.String(64)),
|
||||
sa.Column('definition_json', sa.JSON()),
|
||||
sa.Column('created_at', sa.DateTime()),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_inventory_sources', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('enabled', sa.Boolean()),
|
||||
sa.Column('excel_template_id', sa.Integer(), sa.ForeignKey('shipping_excel_templates.id')),
|
||||
)
|
||||
# 导出产物:历史行保留;对 schema_version / template 的 FK 在真实 PG 上会阻断删版本。
|
||||
sa.Table(
|
||||
'shipping_export_artifacts', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('artifact_no', sa.String(64)),
|
||||
sa.Column('template_id', sa.Integer(), sa.ForeignKey('shipping_excel_templates.id')),
|
||||
sa.Column(
|
||||
'order_schema_version_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_order_schema_versions.id'),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column('file_path', sa.String(500)),
|
||||
sa.Column('created_at', sa.DateTime()),
|
||||
)
|
||||
|
||||
|
||||
def test_field_governance_rebuild_migration_seeds_global_assets(monkeypatch):
|
||||
"""关键断言:清空旧配置后种子 57 标准资产与 STANDARD_SHIPPING_NOTICE 空族,fields 无 schema_id。"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.1b2c3d4e5f6a_rebuild_shipping_field_governance',
|
||||
)
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
_build_pre_migration_schema(metadata)
|
||||
metadata.create_all(engine)
|
||||
|
||||
with engine.begin() as connection:
|
||||
connection.execute(sa.text('PRAGMA foreign_keys=ON'))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_order_schemas "
|
||||
"(id, schema_code, display_name, auto_creation_policy_json, status, created_at, updated_at) "
|
||||
"VALUES (1, 'SHIPPING_ORDER', '旧族', '{}', 'active', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
))
|
||||
connection.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 ('old-1', 1, 'legacy_po', 'header', 'string', 'order_header', 'llm_extraction', "
|
||||
"1, 'active', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_order_schema_versions "
|
||||
"(id, schema_id, version, status, definition_json) "
|
||||
"VALUES (1, 1, 1, 'published', '{}')"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_excel_templates "
|
||||
"(id, template_code, display_name, version, status, storage_provider, storage_bucket, "
|
||||
"storage_key, original_filename, file_checksum, definition_json, created_at) "
|
||||
"VALUES (10, 'tpl', '模板', 1, 'published', 'minio', 'b', 'k', 'f.xlsx', 'abc', '{}', "
|
||||
"CURRENT_TIMESTAMP)"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_inventory_sources (id, enabled, excel_template_id) "
|
||||
"VALUES (1, 1, 10)"
|
||||
))
|
||||
# 关键断言前置:存在对 schema_version 的外键引用(旧实现会在 DELETE versions 时失败)。
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_export_artifacts "
|
||||
"(id, artifact_no, template_id, order_schema_version_id, file_path, created_at) "
|
||||
"VALUES (1, 'ART-1', 10, 1, '/tmp/a.xlsx', CURRENT_TIMESTAMP)"
|
||||
))
|
||||
|
||||
monkeypatch.setattr(migration, 'op', Operations(MigrationContext.configure(connection)))
|
||||
migration.upgrade()
|
||||
|
||||
field_cols = {item['name'] for item in sa.inspect(connection).get_columns('shipping_order_fields')}
|
||||
assert 'schema_id' not in field_cols
|
||||
assert {'asset_kind', 'storage_mode', 'display_name_default'} <= field_cols
|
||||
|
||||
# SQLite recreate 路径须同步模型 CHECK(asset_kind / storage_mode / collection_mode)。
|
||||
ck_sql = ' '.join(
|
||||
str(row[0])
|
||||
for row in connection.execute(sa.text(
|
||||
"SELECT sql FROM sqlite_master WHERE type='table' AND name='shipping_order_fields'"
|
||||
)).fetchall()
|
||||
if row[0]
|
||||
)
|
||||
assert "asset_kind IN ('system_standard', 'extension')" in ck_sql
|
||||
assert "storage_mode IN ('typed_column', 'json_only')" in ck_sql
|
||||
assert "collection_mode IN ('llm_extraction')" in ck_sql
|
||||
|
||||
field_rows = connection.execute(sa.text(
|
||||
"SELECT field_code, asset_kind, status FROM shipping_order_fields"
|
||||
)).mappings().all()
|
||||
assert len(field_rows) == len(STANDARD_FIELD_SPECS) == 57
|
||||
assert all(row['asset_kind'] == 'system_standard' for row in field_rows)
|
||||
assert all(row['status'] == 'active' for row in field_rows)
|
||||
assert 'legacy_po' not in {row['field_code'] for row in field_rows}
|
||||
assert 'customer_po_number' in {row['field_code'] for row in field_rows}
|
||||
|
||||
family = connection.execute(sa.text(
|
||||
"SELECT schema_code, display_name FROM shipping_order_schemas"
|
||||
)).mappings().one()
|
||||
assert family['schema_code'] == DEFAULT_SCHEMA_FAMILY_CODE
|
||||
|
||||
versions = connection.execute(sa.text(
|
||||
"SELECT COUNT(*) AS c FROM shipping_order_schema_versions"
|
||||
)).mappings().one()
|
||||
assert int(versions['c']) == 0
|
||||
|
||||
templates = connection.execute(sa.text(
|
||||
"SELECT COUNT(*) AS c FROM shipping_excel_templates"
|
||||
)).mappings().one()
|
||||
assert int(templates['c']) == 0
|
||||
|
||||
# 历史 Artifact 行保留,schema_version_id 成为 orphan(只读)。
|
||||
artifact = connection.execute(sa.text(
|
||||
"SELECT order_schema_version_id, template_id FROM shipping_export_artifacts WHERE id = 1"
|
||||
)).mappings().one()
|
||||
assert int(artifact['order_schema_version_id']) == 1
|
||||
assert int(artifact['template_id']) == 10
|
||||
|
||||
source = connection.execute(sa.text(
|
||||
"SELECT enabled, excel_template_id FROM shipping_inventory_sources WHERE id = 1"
|
||||
)).mappings().one()
|
||||
assert int(source['enabled'] or 0) == 0
|
||||
assert source['excel_template_id'] is None
|
||||
|
||||
migration.downgrade()
|
||||
remaining_fields = connection.execute(sa.text(
|
||||
"SELECT COUNT(*) AS c FROM shipping_order_fields"
|
||||
)).mappings().one()
|
||||
assert int(remaining_fields['c']) == 0
|
||||
|
||||
# 关键断言:downgrade 结构回退 — schema_id 列恢复,资产治理列移除。
|
||||
post_downgrade_cols = {
|
||||
item['name'] for item in sa.inspect(connection).get_columns('shipping_order_fields')
|
||||
}
|
||||
assert 'schema_id' in post_downgrade_cols
|
||||
assert 'asset_kind' not in post_downgrade_cols
|
||||
assert 'storage_mode' not in post_downgrade_cols
|
||||
assert 'display_name_default' not in post_downgrade_cols
|
||||
|
||||
audit_cols = {
|
||||
item['name'] for item in sa.inspect(connection).get_columns('shipping_order_schema_audit_events')
|
||||
}
|
||||
assert 'field_id' not in audit_cols
|
||||
|
||||
post_ck_sql = ' '.join(
|
||||
str(row[0])
|
||||
for row in connection.execute(sa.text(
|
||||
"SELECT sql FROM sqlite_master WHERE type='table' AND name='shipping_order_fields'"
|
||||
)).fetchall()
|
||||
if row[0]
|
||||
)
|
||||
assert "asset_kind IN ('system_standard', 'extension')" not in post_ck_sql
|
||||
assert "field_category IN ('general_context', 'order_header', 'order_line')" in post_ck_sql
|
||||
@@ -3,7 +3,8 @@ tests/test_shipping_fulfillment_policy.py
|
||||
|
||||
用途:验证货代字段能力绑定与版本化履约策略。
|
||||
依赖:订单 Schema 服务、履约策略注册表与测试数据库。
|
||||
逻辑:策略只允许受控能力绑定稳定 field_id;发布后冻结保存版本快照,错误类型或范围必须阻断。
|
||||
逻辑:策略只允许受控能力绑定稳定 field_id;发布后冻结保存版本快照,错误类型或范围必须阻断;
|
||||
无已发布 Schema 时不得发布策略。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,7 +12,7 @@ from __future__ import annotations
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingFulfillmentPolicy, ShippingOrderField
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import create_draft, get_state, publish
|
||||
from app.services.shipping_notice.order_schema import service as schema_service
|
||||
@@ -42,8 +43,24 @@ def _field_config(field_id: str, *, display_name: str, value_type: str = 'string
|
||||
}
|
||||
|
||||
|
||||
def _publish_minimal_schema() -> None:
|
||||
"""发布含履约绑定字段的最小 Schema,供策略发布门禁使用。"""
|
||||
fields = {item.field_code: item for item in ShippingOrderField.query.filter_by(status='active').all()}
|
||||
draft = schema_service.create_draft({}, actor_id=None)
|
||||
configs = [
|
||||
_field_config(fields['reservation_id'].id, display_name='预定单号'),
|
||||
_field_config(fields['part_number'].id, display_name='料号'),
|
||||
_field_config(fields['qty'].id, display_name='数量', value_type='decimal'),
|
||||
_field_config(fields['inventory_source_hint'].id, display_name='库存源线索'),
|
||||
]
|
||||
saved = schema_service.save_draft(draft['id'], {
|
||||
'fields': configs, 'expected_lock_version': draft['lock_version'],
|
||||
}, actor_id=None)
|
||||
schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
|
||||
|
||||
def test_policy_initialization_and_publish_versions_are_isolated(app):
|
||||
"""初始化只创建待确认草稿;发布后新版本退役旧版且保留稳定字段绑定。"""
|
||||
"""初始化只创建待确认草稿;有已发布 Schema 后,发布策略会退役旧版且保留稳定字段绑定。"""
|
||||
with app.app_context():
|
||||
schema_service.initialize_schema({'display_name': '货代字段'}, actor_id=None)
|
||||
initial = ShippingFulfillmentPolicy.query.filter_by(status='draft').one()
|
||||
@@ -52,6 +69,7 @@ def test_policy_initialization_and_publish_versions_are_isolated(app):
|
||||
'fulfillment.reservation_identity', 'fulfillment.part_number', 'fulfillment.quantity',
|
||||
}
|
||||
|
||||
_publish_minimal_schema()
|
||||
initial = publish(initial.id, actor_id=None, expected_lock_version=initial.lock_version)
|
||||
assert initial['status'] == 'published'
|
||||
|
||||
@@ -63,6 +81,16 @@ def test_policy_initialization_and_publish_versions_are_isolated(app):
|
||||
assert len(get_state()['capabilities']) == 4
|
||||
|
||||
|
||||
def test_policy_publish_requires_published_schema(app):
|
||||
"""断言:同族尚无已发布 Schema 时,不得发布履约策略。"""
|
||||
with app.app_context():
|
||||
schema_service.initialize_schema({'display_name': '货代字段'}, actor_id=None)
|
||||
initial = ShippingFulfillmentPolicy.query.filter_by(status='draft').one()
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
publish(initial.id, actor_id=None, expected_lock_version=initial.lock_version)
|
||||
assert exc_info.value.code == 'SHIPPING.FULFILLMENT_POLICY_SCHEMA_REQUIRED'
|
||||
|
||||
|
||||
def test_policy_rejects_scope_or_type_drift(app):
|
||||
"""能力绑定只能选择匹配 scope/value_type 的字段,不能借字段目录绕过履约契约。"""
|
||||
with app.app_context():
|
||||
@@ -76,22 +104,20 @@ def test_policy_rejects_scope_or_type_drift(app):
|
||||
assert exc_info.value.code == 'SHIPPING.FULFILLMENT_POLICY_INVALID'
|
||||
|
||||
|
||||
def test_policy_allows_a_custom_field_to_bind_a_compatible_capability(app):
|
||||
"""自定义字段只要 scope/type 匹配,即可经策略承担履约能力而不依赖字段编码。"""
|
||||
def test_policy_rejects_extension_on_core_capability(app):
|
||||
"""核心履约能力不得绑定扩展字段;须使用系统标准表身字段。"""
|
||||
with app.app_context():
|
||||
schema_service.initialize_schema({'display_name': '货代字段'}, actor_id=None)
|
||||
custom = schema_service.save_field({
|
||||
'field_code': 'customer_reservation_reference', 'scope': 'line', 'value_type': 'string',
|
||||
'display_name': '客户预约单号',
|
||||
}, actor_id=None)
|
||||
bindings = _bindings()
|
||||
bindings[0]['field_id'] = custom['id']
|
||||
|
||||
draft = create_draft({'field_bindings': bindings, 'change_note': '客户预约单字段'}, actor_id=None)
|
||||
|
||||
reservation = next(item for item in draft['definition']['field_bindings']
|
||||
if item['capability_code'] == 'fulfillment.reservation_identity')
|
||||
assert reservation['field_id'] == custom['id']
|
||||
assert reservation['field_code'] == 'customer_reservation_reference'
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
create_draft({'field_bindings': bindings, 'change_note': '客户预约单字段'}, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.FULFILLMENT_FIELD_INVALID'
|
||||
|
||||
|
||||
def test_policy_publish_rejects_an_active_field_omitted_from_published_schema(app):
|
||||
@@ -100,22 +126,17 @@ def test_policy_publish_rejects_an_active_field_omitted_from_published_schema(ap
|
||||
schema_service.initialize_schema({'display_name': '货代字段'}, actor_id=None)
|
||||
fields = {item.field_code: item for item in ShippingOrderField.query.filter_by(status='active').all()}
|
||||
draft = schema_service.create_draft({}, actor_id=None)
|
||||
# 故意不纳入 inventory_source_hint,策略绑定仍包含该字段时应被拒绝。
|
||||
configs = [
|
||||
_field_config(fields['reservation_id'].id, display_name='预定单号'),
|
||||
_field_config(fields['part_number'].id, display_name='料号'),
|
||||
_field_config(fields['qty'].id, display_name='数量', value_type='decimal'),
|
||||
_field_config(fields['inventory_source_hint'].id, display_name='库存源线索'),
|
||||
]
|
||||
saved = schema_service.save_draft(draft['id'], {
|
||||
'fields': configs, 'expected_lock_version': draft['lock_version'],
|
||||
}, actor_id=None)
|
||||
schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
custom = schema_service.save_field({
|
||||
'field_code': 'unpublished_reservation_reference', 'scope': 'line', 'value_type': 'string',
|
||||
}, actor_id=None)
|
||||
bindings = _bindings()
|
||||
bindings[0]['field_id'] = custom['id']
|
||||
policy_draft = create_draft({'field_bindings': bindings}, actor_id=None)
|
||||
policy_draft = create_draft({'field_bindings': _bindings()}, actor_id=None)
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
publish(policy_draft['id'], actor_id=None, expected_lock_version=policy_draft['lock_version'])
|
||||
@@ -148,4 +169,7 @@ def test_schema_publish_cannot_omit_a_field_bound_by_published_policy(app):
|
||||
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
schema_service.publish(second['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_PUBLISH_DEPENDENCY_BLOCKED'
|
||||
assert getattr(exc_info.value, 'code', None) in {
|
||||
'SHIPPING.ORDER_SCHEMA_PUBLISH_DEPENDENCY_BLOCKED',
|
||||
'SHIPPING.FIELD_IMPACT_BLOCKED',
|
||||
}
|
||||
@@ -18,7 +18,8 @@ from app.models import (
|
||||
ShippingExcelTemplate, ShippingInventoryExternalMapping, ShippingInventoryFile,
|
||||
ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventorySource,
|
||||
ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
|
||||
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingTask,
|
||||
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.credential_crypto import decrypt_credential, encrypt_credential
|
||||
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
|
||||
@@ -202,13 +203,17 @@ def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, t
|
||||
source = _source(_profile(code='CRANE_PROFILE', connector_type='crane'), code='CRANE', mode='inventory_match')
|
||||
inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||||
part_field = ShippingOrderField(id='dynamic-order-part', schema=schema, field_code='part_number', scope='line', value_type='string')
|
||||
reservation_field = ShippingOrderField(id='dynamic-order-reservation', schema=schema, field_code='reservation_id', scope='line', value_type='string')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
part_field = ShippingOrderField.query.filter_by(field_code='part_number').one()
|
||||
reservation_field = ShippingOrderField.query.filter_by(field_code='reservation_id').one()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema=schema, version=1, status='published', checksum='d' * 64,
|
||||
schema_id=schema.id, version=1, status='published', checksum='d' * 64,
|
||||
definition_json={'fields': [
|
||||
{'id': part_field.id, 'field_code': part_field.field_code, 'scope': 'line', 'value_type': 'string'},
|
||||
{'id': reservation_field.id, 'field_code': reservation_field.field_code, 'scope': 'line', 'value_type': 'string'},
|
||||
{'field_id': part_field.id, 'field_code': part_field.field_code, 'scope': 'line', 'value_type': 'string'},
|
||||
{'field_id': reservation_field.id, 'field_code': reservation_field.field_code, 'scope': 'line', 'value_type': 'string'},
|
||||
]},
|
||||
)
|
||||
source.parsing_profile.definition_json = {
|
||||
@@ -224,7 +229,7 @@ def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, t
|
||||
],
|
||||
}
|
||||
db.session.add(source)
|
||||
db.session.add_all([schema, part_field, reservation_field, version])
|
||||
db.session.add_all([schema, version])
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='d' * 64, status='accepted')
|
||||
db.session.add(extraction)
|
||||
@@ -259,6 +264,19 @@ def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, t
|
||||
)
|
||||
task.inventory_source_config_version = inventory_sources_runtime_version()
|
||||
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
order_snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id,
|
||||
order_data_version=1, rule_versions_json={}, header_values_json={},
|
||||
)
|
||||
db.session.add(order_snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=order_snapshot.id, position=1, part_number='A001', reservation_id='R-1',
|
||||
field_values_json={str(part_field.id): 'A001', str(reservation_field.id): 'R-1'},
|
||||
))
|
||||
task.order_snapshot_id = order_snapshot.id
|
||||
path = tmp_path / 'dynamic.xlsx'
|
||||
path.write_bytes(b'not-parsed-in-this-test')
|
||||
snapshot = ShippingInventoryFile(
|
||||
@@ -275,7 +293,7 @@ def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, t
|
||||
},
|
||||
],
|
||||
)
|
||||
db.session.add_all([task, snapshot])
|
||||
db.session.add(snapshot)
|
||||
db.session.commit()
|
||||
link = link_snapshot_to_task(task, snapshot, reason='dynamic_test')
|
||||
assert link is not None
|
||||
|
||||
@@ -497,7 +497,9 @@ def test_order_field_display_uses_current_catalog_sequence(app):
|
||||
_ensure_order_schema()
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
sequence_by_code = {'part_number': 1, 'qty': 2, 'reservation_id': 3, 'po_number': 4}
|
||||
for field in ShippingOrderField.query.filter_by(schema_id=version.schema_id).all():
|
||||
for field in ShippingOrderField.query.filter(
|
||||
ShippingOrderField.field_code.in_(sequence_by_code),
|
||||
).all():
|
||||
field.display_sequence = sequence_by_code.get(str(field.field_code), 99)
|
||||
task = ShippingTask(
|
||||
task_no='SN-ORDER-DISPLAY-SEQUENCE', process_status='parsed', source_type='manual',
|
||||
|
||||
@@ -286,3 +286,366 @@ def test_resolve_task_from_payload_rejects_ambiguous_conversation_id(app):
|
||||
)
|
||||
assert resolved is not None
|
||||
assert resolved.task_no == "SN-CONV-MULTI-1"
|
||||
|
||||
|
||||
def test_task_can_handle_only_creator(app):
|
||||
"""仅创建者 can_handle;无主任务与非创建者均为 False。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.query_service import task_can_handle
|
||||
|
||||
owned = ShippingTask(
|
||||
task_no="SN-HANDLE-OWN",
|
||||
process_status="created",
|
||||
source_type="manual",
|
||||
user_id=42,
|
||||
)
|
||||
orphan = ShippingTask(
|
||||
task_no="SN-HANDLE-ORPHAN",
|
||||
process_status="created",
|
||||
source_type="manual",
|
||||
user_id=None,
|
||||
)
|
||||
db.session.add_all([owned, orphan])
|
||||
db.session.commit()
|
||||
|
||||
assert task_can_handle(owned, 42) is True
|
||||
assert task_can_handle(owned, 42, is_admin=True) is True
|
||||
assert task_can_handle(owned, 99) is False
|
||||
assert task_can_handle(owned, 99, is_admin=True) is False
|
||||
assert task_can_handle(orphan, 42) is False
|
||||
|
||||
|
||||
def test_get_task_for_user_rejects_null_owner(app):
|
||||
"""写路径 get_task_for_user 拒绝 user_id IS NULL;管理员只读走 visible。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_task_for_user,
|
||||
get_task_visible_to_user,
|
||||
)
|
||||
|
||||
orphan = ShippingTask(
|
||||
task_no="SN-NULL-OWNER",
|
||||
process_status="created",
|
||||
source_type="manual",
|
||||
user_id=None,
|
||||
)
|
||||
owned = ShippingTask(
|
||||
task_no="SN-OWNED",
|
||||
process_status="created",
|
||||
source_type="manual",
|
||||
user_id=7,
|
||||
)
|
||||
db.session.add_all([orphan, owned])
|
||||
db.session.commit()
|
||||
|
||||
assert get_task_for_user("SN-NULL-OWNER", 7) is None
|
||||
assert get_task_for_user("SN-OWNED", 7) is not None
|
||||
assert get_task_for_user("SN-OWNED", 8) is None
|
||||
assert get_task_visible_to_user("SN-OWNED", 8, is_admin=True) is not None
|
||||
assert get_task_visible_to_user("SN-NULL-OWNER", 7, is_admin=True) is not None
|
||||
|
||||
|
||||
def test_serialize_task_summary_enriches_todo_and_can_handle(app):
|
||||
"""SUMMARY enrich 含 todo_category / created_by / can_handle / ui_state。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.query_service import serialize_task_summary
|
||||
|
||||
task = ShippingTask(
|
||||
task_no="SN-ENRICH-1",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
user_id=11,
|
||||
export_file_name="a.xlsx",
|
||||
export_file_path="/tmp/a.xlsx",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
data = serialize_task_summary(task, viewer_user_id=11)
|
||||
assert data["todo_category"] == "review"
|
||||
assert data["created_by"] == 11
|
||||
assert data["can_handle"] is True
|
||||
assert data["ui_state"]["checkpoint"] == "parse_review"
|
||||
assert data["artifact_summary"]["export_file_name"] == "a.xlsx"
|
||||
|
||||
no_viewer = serialize_task_summary(task)
|
||||
assert "can_handle" not in no_viewer
|
||||
|
||||
|
||||
def test_list_my_todos_and_count_buckets(app):
|
||||
"""list_my_todos 按 bucket 分类;count 徽标与 pending 一致。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
|
||||
|
||||
owner = 55
|
||||
review = ShippingTask(
|
||||
task_no="SN-TODO-REVIEW",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
)
|
||||
upload = ShippingTask(
|
||||
task_no="SN-TODO-UPLOAD",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
export_file_path="/tmp/u.xlsx",
|
||||
export_file_name="u.xlsx",
|
||||
)
|
||||
done = ShippingTask(
|
||||
task_no="SN-TODO-DONE",
|
||||
process_status="uploaded",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
)
|
||||
other = ShippingTask(
|
||||
task_no="SN-TODO-OTHER",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
user_id=99,
|
||||
)
|
||||
db.session.add_all([review, upload, done, other])
|
||||
db.session.commit()
|
||||
|
||||
pending = list_my_todos(owner, bucket="pending", page=1, page_size=20)
|
||||
assert pending["total"] == 2
|
||||
assert {item["task_no"] for item in pending["items"]} == {
|
||||
"SN-TODO-REVIEW",
|
||||
"SN-TODO-UPLOAD",
|
||||
}
|
||||
assert all(item["can_handle"] is True for item in pending["items"])
|
||||
|
||||
done_page = list_my_todos(owner, bucket="done")
|
||||
assert done_page["total"] == 1
|
||||
assert done_page["items"][0]["task_no"] == "SN-TODO-DONE"
|
||||
|
||||
counts = count_my_todos(owner)
|
||||
assert counts["pending"] == 2
|
||||
assert counts["done"] == 1
|
||||
assert counts["total_pending_badge"] == 2
|
||||
|
||||
admin_pending = list_my_todos(owner, bucket="pending", is_admin=True)
|
||||
assert admin_pending["total"] >= 3
|
||||
other_item = next(
|
||||
item for item in admin_pending["items"] if item["task_no"] == "SN-TODO-OTHER"
|
||||
)
|
||||
assert other_item["can_handle"] is False
|
||||
|
||||
|
||||
def test_list_my_todos_includes_open_review_case_with_run_deep_link(app):
|
||||
"""开放 Review Case 进入 pending,并暴露 review_run_no 供人工复核深链。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='TODO-REV-DL')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {
|
||||
'orders': [{
|
||||
'header_fields': [{'field_id': 'po', 'observations': [{'value': 'PO-DL'}]}],
|
||||
'lines': [{'fields': [{'field_id': 'part', 'observations': [{'value': 'A1'}]}]}],
|
||||
'conflicts': [],
|
||||
}],
|
||||
}
|
||||
db.session.commit()
|
||||
cases = ensure_run_review_cases(run=run)
|
||||
assert cases
|
||||
case = cases[0]
|
||||
|
||||
pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50)
|
||||
review_items = [item for item in pending['items'] if item.get('item_kind') == 'review_case']
|
||||
assert review_items, 'pending 应包含建单前复核 Case'
|
||||
hit = next(item for item in review_items if item.get('review_case_no') == case.case_no)
|
||||
assert hit['todo_category'] == 'review'
|
||||
assert hit['review_run_no'] == run.run_no
|
||||
assert hit['owner_agent_id'] == agent.id
|
||||
assert hit['conversation_id'] == session.session_id
|
||||
assert hit['can_handle'] is True
|
||||
assert hit['ui_state']['summary']['entry_surface'] == 'review_workbench'
|
||||
|
||||
counts = count_my_todos(user.id)
|
||||
assert counts['pending'] >= 1
|
||||
assert counts['total_pending_badge'] == counts['pending']
|
||||
|
||||
|
||||
def test_list_my_todos_filters_review_case_by_customer_filename(app):
|
||||
"""Review Case 客户过滤按来源文件名/Case 号匹配,不能只筛 Task。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.query_service import list_my_todos
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='TODO-REV-CUST')
|
||||
document.filename = 'ACME-PO-450099.pdf'
|
||||
db.session.flush()
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {
|
||||
'orders': [{
|
||||
'header_fields': [{'field_id': 'po', 'observations': [{'value': 'PO-CUST'}]}],
|
||||
'lines': [{'fields': [{'field_id': 'part', 'observations': [{'value': 'B1'}]}]}],
|
||||
'conflicts': [],
|
||||
}],
|
||||
}
|
||||
db.session.commit()
|
||||
cases = ensure_run_review_cases(run=run)
|
||||
assert cases
|
||||
|
||||
hit = list_my_todos(user.id, bucket='pending', page=1, page_size=50, customer='ACME')
|
||||
review_hits = [item for item in hit['items'] if item.get('item_kind') == 'review_case']
|
||||
assert review_hits, '按文件名关键字应命中 Review Case'
|
||||
|
||||
miss = list_my_todos(user.id, bucket='pending', page=1, page_size=50, customer='NO-SUCH-CUSTOMER')
|
||||
assert not any(item.get('item_kind') == 'review_case' for item in miss['items'])
|
||||
|
||||
|
||||
def test_list_my_todos_total_and_high_page_are_not_capped(app):
|
||||
"""total 必须是完整匹配数;超过旧 500 截断后高页码仍可访问。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.query_service import list_my_todos
|
||||
|
||||
owner = 77
|
||||
# 520 > 旧 limit(500),用于证明截断不再作为 total 来源。
|
||||
total_tasks = 520
|
||||
tasks = [
|
||||
ShippingTask(
|
||||
task_no=f"SN-TODO-PAGE-{index:04d}",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
)
|
||||
for index in range(total_tasks)
|
||||
]
|
||||
db.session.add_all(tasks)
|
||||
db.session.commit()
|
||||
|
||||
page1 = list_my_todos(owner, bucket="pending", page=1, page_size=20)
|
||||
assert page1["total"] == total_tasks
|
||||
assert len(page1["items"]) == 20
|
||||
|
||||
# 第 26 页:offset=500,恰好是旧截断边界之后;必须仍能返回数据。
|
||||
page26 = list_my_todos(owner, bucket="pending", page=26, page_size=20)
|
||||
assert page26["total"] == total_tasks
|
||||
assert len(page26["items"]) == 20
|
||||
|
||||
page27 = list_my_todos(owner, bucket="pending", page=27, page_size=20)
|
||||
assert page27["total"] == total_tasks
|
||||
assert len(page27["items"]) == 0
|
||||
|
||||
far = list_my_todos(owner, bucket="pending", page=30, page_size=20)
|
||||
assert far["total"] == total_tasks
|
||||
assert far["items"] == []
|
||||
|
||||
|
||||
def test_todo_category_lightweight_matches_orm_and_count(app):
|
||||
"""
|
||||
轻量行分类 / SQL CASE 与 ORM task_todo_category 一致;count 徽标与 list total 同源。
|
||||
|
||||
断言意图:UNION 分页下推的 SQL 分类不得漂移口径。
|
||||
"""
|
||||
with app.app_context():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.query_service import (
|
||||
_task_todo_category_sql_expr,
|
||||
_todo_category_from_task_row,
|
||||
count_my_todos,
|
||||
list_my_todos,
|
||||
task_todo_category,
|
||||
)
|
||||
|
||||
owner = 88
|
||||
fixtures = [
|
||||
ShippingTask(
|
||||
task_no="SN-LW-REVIEW",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
),
|
||||
ShippingTask(
|
||||
task_no="SN-LW-UPLOAD",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
export_file_path="/tmp/lw.xlsx",
|
||||
export_file_name="lw.xlsx",
|
||||
),
|
||||
ShippingTask(
|
||||
task_no="SN-LW-SHORTAGE",
|
||||
# 不可用 matched:状态机会先落到 ready_export,遮住 shortage 人审分支。
|
||||
process_status="parsed",
|
||||
review_status="shortage_review",
|
||||
pending_human_reason="shortage",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
),
|
||||
ShippingTask(
|
||||
task_no="SN-LW-DONE",
|
||||
process_status="uploaded",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
),
|
||||
ShippingTask(
|
||||
task_no="SN-LW-PROGRESS",
|
||||
process_status="parsed",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
),
|
||||
]
|
||||
db.session.add_all(fixtures)
|
||||
db.session.commit()
|
||||
|
||||
category_expr = _task_todo_category_sql_expr()
|
||||
for task in fixtures:
|
||||
row = SimpleNamespace(
|
||||
process_status=task.process_status,
|
||||
review_status=task.review_status,
|
||||
pending_human_reason=task.pending_human_reason,
|
||||
shipping_case_id=task.shipping_case_id,
|
||||
customer_resolution_status=task.customer_resolution_status,
|
||||
order_snapshot_id=task.order_snapshot_id,
|
||||
current_order_extraction_id=task.current_order_extraction_id,
|
||||
inventory_lines_json=task.inventory_lines_json,
|
||||
match_status=task.match_status,
|
||||
export_file_path=task.export_file_path,
|
||||
)
|
||||
expected = task_todo_category(task)
|
||||
# 轻量路径与 ORM 路径同分类。
|
||||
assert _todo_category_from_task_row(row, extractions_with_lines=set()) == expected
|
||||
# SQL CASE 与 ORM 路径同分类,保证 UNION 过滤不漂移。
|
||||
sql_category = (
|
||||
db.session.query(category_expr)
|
||||
.filter(ShippingTask.id == task.id)
|
||||
.scalar()
|
||||
)
|
||||
assert sql_category == expected
|
||||
|
||||
pending = list_my_todos(owner, bucket="pending", page=1, page_size=50)
|
||||
assert pending["total"] == 3
|
||||
counts = count_my_todos(owner)
|
||||
assert counts["pending"] == 3
|
||||
assert counts["done"] == 1
|
||||
assert counts["processing"] == 1
|
||||
assert counts["total_pending_badge"] == 3
|
||||
@@ -0,0 +1,99 @@
|
||||
"""
|
||||
tests/test_shipping_notice_state_machine.py
|
||||
|
||||
用途:校验发货通知状态机注册表完整性与 STP checkpoint_kind 映射。
|
||||
依赖:pytest、state_machine、constants、ShippingTask。
|
||||
逻辑:validate_registry 无错误;关键检查点 kind 正确;resolve_task_ui_state 对简单任务属性可解析。
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_READY,
|
||||
CP_PARSE_REVIEW,
|
||||
CP_UPLOADED,
|
||||
PH_LOW_CONF,
|
||||
RS_PARSE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
CheckpointKind,
|
||||
checkpoint_kind_for,
|
||||
resolve_task_ui_state,
|
||||
validate_registry,
|
||||
)
|
||||
|
||||
|
||||
def test_validate_registry_has_no_errors() -> None:
|
||||
"""CHECKPOINT_REGISTRY 与 KIND / ACTION_SPECS 应完全对齐。"""
|
||||
assert validate_registry() == []
|
||||
|
||||
|
||||
def test_checkpoint_kinds_for_stp_stop_points() -> None:
|
||||
"""STP 关键检查点 kind:导出待上传 / 解析复核 / 已上传终态。"""
|
||||
assert checkpoint_kind_for(CP_EXPORT_READY) == CheckpointKind.WAIT_MANUAL_UPLOAD
|
||||
assert checkpoint_kind_for(CP_PARSE_REVIEW) == CheckpointKind.MUST_HUMAN
|
||||
assert checkpoint_kind_for(CP_UPLOADED) == CheckpointKind.COMPLETE
|
||||
|
||||
|
||||
def test_resolve_task_ui_state_parse_review(app) -> None:
|
||||
"""pending_review + parse_review 应映射为 must_human / parse_review。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-SM-PARSE",
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
)
|
||||
ui = resolve_task_ui_state(task)
|
||||
assert ui.checkpoint == CP_PARSE_REVIEW
|
||||
assert ui.checkpoint_kind == CheckpointKind.MUST_HUMAN
|
||||
|
||||
|
||||
def test_resolve_task_ui_state_export_ready(app) -> None:
|
||||
"""matched 且已有 export_file_path 应为 wait_manual_upload。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-SM-EXPORT",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/shipping-export.xlsx",
|
||||
export_file_name="shipping-export.xlsx",
|
||||
)
|
||||
ui = resolve_task_ui_state(task)
|
||||
assert ui.checkpoint == CP_EXPORT_READY
|
||||
assert ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD
|
||||
|
||||
|
||||
def test_resolve_task_ui_state_uploaded_complete(app) -> None:
|
||||
"""process_status=uploaded 应为 complete。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-SM-UPLOADED",
|
||||
process_status="uploaded",
|
||||
source_type="manual",
|
||||
)
|
||||
ui = resolve_task_ui_state(task)
|
||||
assert ui.checkpoint == CP_UPLOADED
|
||||
assert ui.checkpoint_kind == CheckpointKind.COMPLETE
|
||||
|
||||
|
||||
def test_resolve_with_mocked_simple_namespace_attributes() -> None:
|
||||
"""无 DB 会话时可用简易命名空间验证 uploaded 终态分支。"""
|
||||
task = SimpleNamespace(
|
||||
process_status="uploaded",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
shipping_case_id=None,
|
||||
customer_resolution_status=None,
|
||||
order_snapshot_id=None,
|
||||
inventory_lines_json=None,
|
||||
match_status=None,
|
||||
export_file_path=None,
|
||||
current_order_extraction_id=None,
|
||||
step_payload_json=None,
|
||||
)
|
||||
ui = resolve_task_ui_state(task) # type: ignore[arg-type]
|
||||
assert ui.checkpoint_kind == CheckpointKind.COMPLETE
|
||||
assert ui.checkpoint == CP_UPLOADED
|
||||
@@ -0,0 +1,183 @@
|
||||
"""
|
||||
tests/test_shipping_notice_stp_acceptance.py
|
||||
|
||||
用途:STP + 例外工作台九条工程验收场景中可自动化部分的契约锁。
|
||||
依赖:progress_workflow、fulfillment_workflow、query_service、ui_state、state_machine。
|
||||
逻辑:覆盖早停、禁 RPA 自动上传、待办分类/权限、入口面;人工 UI 实测与构建另见文档勾选。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ShippingTask, User
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_READY,
|
||||
CP_PARSE_REVIEW,
|
||||
PH_LOW_CONF,
|
||||
RS_PARSE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import try_auto_chain_after_match
|
||||
from app.services.shipping_notice.progress_workflow import auto_progress
|
||||
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
|
||||
from app.services.shipping_notice.state_machine import CheckpointKind, checkpoint_kind_for
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
|
||||
def test_stp_checkpoint_kind_matrix_covers_nine_scenario_stops() -> None:
|
||||
"""九条场景依赖的停点 kind 不得漂移。"""
|
||||
assert checkpoint_kind_for(CP_PARSE_REVIEW) == CheckpointKind.MUST_HUMAN
|
||||
assert checkpoint_kind_for(CP_EXPORT_READY) == CheckpointKind.WAIT_MANUAL_UPLOAD
|
||||
|
||||
|
||||
def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app) -> None:
|
||||
"""场景:Excel 已生成 → auto_progress 早停且禁止 upload_to_freight。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||||
task = ShippingTask(
|
||||
task_no="SN-STP-WAIT-UPLOAD",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/stp-export.xlsx",
|
||||
export_file_name="stp-export.xlsx",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
result = auto_progress({"task_id": task.task_no, "source": "system"})
|
||||
assert result["status"] == "ok"
|
||||
assert result.get("checkpoint") == CP_EXPORT_READY
|
||||
assert "upload_to_freight" in (result.get("forbidden_next_tools") or [])
|
||||
assert result.get("stop_agent_turn") is True
|
||||
|
||||
|
||||
def test_auto_progress_stops_at_must_human_parse_review(app) -> None:
|
||||
"""场景:解析复核 → auto_progress needs_human,不推进履约。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||||
task = ShippingTask(
|
||||
task_no="SN-STP-MUST-HUMAN",
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
result = auto_progress({"task_id": task.task_no, "source": "system"})
|
||||
assert result["status"] == "needs_human"
|
||||
assert result.get("checkpoint") == CP_PARSE_REVIEW
|
||||
|
||||
|
||||
def test_try_auto_chain_never_calls_upload_even_when_auto_upload_enabled(app, monkeypatch) -> None:
|
||||
"""场景:禁 RPA 上传 — 即便 AUTO_UPLOAD=true,匹配后串联也不得调用 upload_to_freight。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED"] = True
|
||||
|
||||
task = ShippingTask(
|
||||
task_no="SN-STP-NO-RPA",
|
||||
process_status="matched",
|
||||
match_status="fulfillable",
|
||||
source_type="manual",
|
||||
line_results_json=[{"line_status": "ok"}],
|
||||
export_file_path="/tmp/already.xlsx",
|
||||
export_file_name="already.xlsx",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
upload_calls: list[dict] = []
|
||||
|
||||
def _fake_upload(payload):
|
||||
upload_calls.append(dict(payload or {}))
|
||||
return {"status": "running", "message": "should-not-run"}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow.upload_to_freight",
|
||||
_fake_upload,
|
||||
)
|
||||
|
||||
result = try_auto_chain_after_match(
|
||||
task,
|
||||
{"status": "ok", "message": "matched"},
|
||||
payload={"task_id": task.task_no},
|
||||
)
|
||||
assert upload_calls == []
|
||||
assert result["status"] == "ok"
|
||||
assert "upload_to_freight" in (result.get("forbidden_next_tools") or [])
|
||||
|
||||
|
||||
def test_export_ready_ui_state_entry_is_task_workbench(app) -> None:
|
||||
"""场景:待人工上传待办深链入口为任务处理工作台。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-STP-ENTRY",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/x.xlsx",
|
||||
export_file_name="x.xlsx",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["checkpoint_kind"] == "wait_manual_upload"
|
||||
assert state["summary"]["entry_surface"] == "task_workbench"
|
||||
|
||||
|
||||
def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
|
||||
"""场景:跨会话待办 + 权限 — 创建者 can_handle,管理员看他人任务只读。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
owner = User(
|
||||
username="stp_owner",
|
||||
email="stp-owner@example.com",
|
||||
password_hash="x",
|
||||
role="user",
|
||||
status="approved",
|
||||
)
|
||||
admin = User(
|
||||
username="stp_admin",
|
||||
email="stp-admin@example.com",
|
||||
password_hash="x",
|
||||
role="admin",
|
||||
status="approved",
|
||||
)
|
||||
db.session.add_all([owner, admin])
|
||||
db.session.flush()
|
||||
|
||||
mine = ShippingTask(
|
||||
task_no="SN-STP-OWN",
|
||||
user_id=owner.id,
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/own.xlsx",
|
||||
export_file_name="own.xlsx",
|
||||
)
|
||||
other = ShippingTask(
|
||||
task_no="SN-STP-OTHER",
|
||||
user_id=admin.id,
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
)
|
||||
db.session.add_all([mine, other])
|
||||
db.session.commit()
|
||||
|
||||
pending = list_my_todos(owner.id, bucket="pending", page=1, page_size=50)
|
||||
own_item = next(item for item in pending["items"] if item["task_no"] == "SN-STP-OWN")
|
||||
assert own_item["can_handle"] is True
|
||||
assert own_item.get("todo_category")
|
||||
|
||||
admin_page = list_my_todos(admin.id, bucket="pending", page=1, page_size=50, is_admin=True)
|
||||
foreign = next(item for item in admin_page["items"] if item["task_no"] == "SN-STP-OWN")
|
||||
assert foreign["can_handle"] is False
|
||||
|
||||
counts = count_my_todos(owner.id)
|
||||
assert counts["total_pending_badge"] == counts["pending"]
|
||||
assert counts["pending"] >= 1
|
||||
@@ -0,0 +1,77 @@
|
||||
"""
|
||||
tests/test_shipping_notice_ui_state.py
|
||||
|
||||
用途:校验发货通知 UI State 摘要字段与 entry_surface 映射。
|
||||
依赖:pytest、ShippingTask、ui_state、state_machine constants。
|
||||
逻辑:build_task_ui_state.summary 含 STP 可解释字段;复核 vs 待上传入口面正确。
|
||||
"""
|
||||
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_READY,
|
||||
CP_PARSE_REVIEW,
|
||||
PH_LOW_CONF,
|
||||
RS_PARSE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
|
||||
_REQUIRED_SUMMARY_KEYS = {
|
||||
"title",
|
||||
"message",
|
||||
"issues",
|
||||
"stage",
|
||||
"checkpoint_kind",
|
||||
"current_todo",
|
||||
"pause_reason",
|
||||
"next_auto_step",
|
||||
"event_at",
|
||||
"entry_surface",
|
||||
"allowed_actions",
|
||||
}
|
||||
|
||||
|
||||
def test_build_task_ui_state_summary_has_required_keys(app) -> None:
|
||||
"""summary 必须包含 STP 可解释字段全集。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-UI-SUMMARY",
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert set(_REQUIRED_SUMMARY_KEYS).issubset(state["summary"].keys())
|
||||
assert state["checkpoint"] == CP_PARSE_REVIEW
|
||||
assert state["checkpoint_kind"] == "must_human"
|
||||
|
||||
|
||||
def test_entry_surface_parse_review_is_review_workbench(app) -> None:
|
||||
"""解析复核应进入人工复核工作台。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-UI-REVIEW",
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["summary"]["entry_surface"] == "review_workbench"
|
||||
|
||||
|
||||
def test_entry_surface_export_ready_is_task_workbench(app) -> None:
|
||||
"""Excel 待人工上传应进入任务处理工作台。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-UI-EXPORT",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/shipping-export.xlsx",
|
||||
export_file_name="shipping-export.xlsx",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["checkpoint"] == CP_EXPORT_READY
|
||||
assert state["checkpoint_kind"] == "wait_manual_upload"
|
||||
assert state["summary"]["entry_surface"] == "task_workbench"
|
||||
@@ -1006,7 +1006,7 @@ def test_profile_sample_api_supports_secure_preview_create_and_version_update(ap
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-PROFILE-SAMPLE', asset_id=asset.id, user_id=user.id,
|
||||
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6',
|
||||
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v7',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
@@ -1029,6 +1029,9 @@ def test_profile_sample_api_supports_secure_preview_create_and_version_update(ap
|
||||
db.session.commit()
|
||||
document_id = document.id
|
||||
schema_id = schema.id
|
||||
asset_id = asset.id
|
||||
user_id = user.id
|
||||
layout_version_id = document.current_layout_version_id
|
||||
|
||||
client = app.test_client()
|
||||
user_headers = {'X-Username': 'sample-user', 'X-Role': 'user'}
|
||||
@@ -1046,6 +1049,28 @@ def test_profile_sample_api_supports_secure_preview_create_and_version_update(ap
|
||||
assert samples[0]['document_id'] == document_id
|
||||
assert samples[0]['purpose'] == 'order_document_profile_sample'
|
||||
|
||||
with app.app_context():
|
||||
duplicate_intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-PROFILE-SAMPLE-DUPLICATE', asset_id=asset_id, user_id=user_id,
|
||||
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6',
|
||||
)
|
||||
db.session.add(duplicate_intake)
|
||||
db.session.flush()
|
||||
duplicate = ShippingNoticeDocument(
|
||||
intake_id=duplicate_intake.id, asset_id=asset_id, document_type='attachment',
|
||||
attachment_key='duplicate.pdf', filename='duplicate.pdf', content_hash='c' * 64,
|
||||
classification='order_notice', parse_status='parsed', current_layout_version_id=layout_version_id,
|
||||
)
|
||||
db.session.add(duplicate)
|
||||
db.session.commit()
|
||||
duplicate_id = duplicate.id
|
||||
|
||||
deduplicated = parse_api_data(client.get(
|
||||
'/api/admin/shipping-notice/order-document-profile-samples', headers=admin_headers,
|
||||
).get_json())
|
||||
assert len(deduplicated) == 1
|
||||
assert deduplicated[0]['document_id'] == duplicate_id
|
||||
|
||||
preview_response = client.get(
|
||||
f'/api/admin/shipping-notice/order-document-profile-samples/{document_id}/tables',
|
||||
headers=admin_headers,
|
||||
|
||||
@@ -235,6 +235,10 @@ def test_create_run_freezes_lightweight_input_without_sync_materialization(app):
|
||||
assert run.current_job_id is not None
|
||||
assert intake.order_extraction_status == 'extracting'
|
||||
assert run.input_snapshot_json['schema']['checksum'] == 'a' * 64
|
||||
# 阶段 5:冻结快照须带族编码,历史 Run 可在资产解耦后按契约回放。
|
||||
assert run.input_snapshot_json['schema']['schema_code']
|
||||
assert run.input_snapshot_json['schema']['family_code'] == run.input_snapshot_json['schema']['schema_code']
|
||||
assert run.input_snapshot_json['schema']['version'] is not None
|
||||
assert run.input_snapshot_json['schema']['extraction_contract']['fields'][0]['field_id'] == 'qty-id'
|
||||
assert run.input_snapshot_json['intakes'][0]['documents'] == []
|
||||
# 请求锚点在入队后保持轻量快照,Worker 物化执行证据不能改变其幂等与审计含义。
|
||||
@@ -1483,6 +1487,52 @@ def test_run_documents_and_summary_keep_partial_success_isolated_per_pdf(app, cl
|
||||
}
|
||||
|
||||
|
||||
def test_serialize_workspace_run_documents_projects_open_existing(app):
|
||||
"""open_existing 候选须投影 existing_task_no 与 open_existing 操作,不能落到人工复核入口。"""
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import (
|
||||
serialize_workspace_run_documents,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='OPEN-EXIST-PROJ')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
ensure_order_extraction_plan(run)
|
||||
db.session.commit()
|
||||
unit = run.extraction_plan.units[0]
|
||||
transition_order_extraction_unit(unit, target_status='routing')
|
||||
transition_order_extraction_unit(
|
||||
unit, target_status='review_required', error_code='required_field_missing',
|
||||
)
|
||||
db.session.add(ShippingNoticeCandidate(
|
||||
candidate_no='SNC-OPEN-EXIST-PROJ',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='open-existing-proj',
|
||||
order_extraction_run_id=run.id,
|
||||
selected=True,
|
||||
candidate_status='provisional',
|
||||
is_current_version=True,
|
||||
validation_status='ready',
|
||||
duplicate_status='same_active_task',
|
||||
duplicate_resolution='open_existing',
|
||||
duplicate_target_task_no='SN-EXISTING-001',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
items = serialize_workspace_run_documents(run)
|
||||
assert len(items) == 1
|
||||
item = items[0]
|
||||
assert item['duplicate_resolution'] == 'open_existing'
|
||||
assert item['existing_task_no'] == 'SN-EXISTING-001'
|
||||
assert item['duplicate_status'] == 'same_active_task'
|
||||
assert item['reason_code'] == 'required_field_missing'
|
||||
assert item['available_actions'] == ['open_existing', 'view_evidence']
|
||||
assert 'manual_review' not in item['available_actions']
|
||||
|
||||
|
||||
def test_run_progress_events_api_returns_only_generic_stages(app, client):
|
||||
"""用户进度明细只返回通用阶段、状态和时间,且继续执行 Run 所有权隔离。"""
|
||||
from app.models import ShippingOrderExtractionProgressEvent
|
||||
|
||||
@@ -10,6 +10,8 @@ from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
@@ -24,6 +26,8 @@ from app.services.shipping_notice.order_review_projection import serialize_revie
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run
|
||||
from app.services.shipping_notice.order_review_service import (
|
||||
ensure_run_review_cases,
|
||||
get_review_case_visible_to_user,
|
||||
get_review_run_visible_to_user,
|
||||
get_user_review_case,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
@@ -182,6 +186,36 @@ def test_review_read_api_returns_safe_owner_scoped_projection(app):
|
||||
assert 'storage_key' not in str(body)
|
||||
|
||||
|
||||
def test_review_visible_helpers_allow_admin_readonly_but_write_stays_owner_only(app):
|
||||
"""管理员可通过 visible 只读他人 Case;写路径仍拒绝非 owner。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-ADMIN-VIS')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
admin = User(
|
||||
username='review-admin',
|
||||
email='review-admin@example.com',
|
||||
password_hash='x',
|
||||
status='active',
|
||||
role='admin',
|
||||
)
|
||||
other = User(username='review-other-vis', email='review-other-vis@example.com', password_hash='x', status='active')
|
||||
db.session.add_all([admin, other])
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:管理员只读可见他人 Run/Case。
|
||||
assert get_review_run_visible_to_user(run.run_no, admin.id, is_admin=True).id == run.id
|
||||
assert get_review_case_visible_to_user(case.case_no, admin.id, is_admin=True).id == case.id
|
||||
|
||||
# 关键断言:非 owner 普通用户仍不可见。
|
||||
with pytest.raises(NotFoundError):
|
||||
get_review_case_visible_to_user(case.case_no, other.id, is_admin=False)
|
||||
|
||||
# 关键断言:写路径 get_user_review_case 仍仅 owner。
|
||||
with pytest.raises(NotFoundError):
|
||||
get_user_review_case(user_id=admin.id, case_no=case.case_no)
|
||||
|
||||
|
||||
def test_review_draft_edits_are_versioned_audited_and_preserve_machine_values(app):
|
||||
"""单字段人工编辑不覆盖机器快照;旧版本写入被拒绝且每次变更都有独立审计。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -274,7 +274,7 @@ def test_order_schema_admin_api_permissions_and_validation(app, client):
|
||||
json={'display_name': '发货订单字段'},
|
||||
)
|
||||
assert created.status_code == 201
|
||||
assert parse_api_data(created.get_json())['schema']['schema_code'] == 'SHIPPING_ORDER'
|
||||
assert parse_api_data(created.get_json())['schema']['schema_code'] == 'STANDARD_SHIPPING_NOTICE'
|
||||
|
||||
invalid = client.post(
|
||||
'/api/admin/shipping-order-schema/fields',
|
||||
|
||||
@@ -72,7 +72,10 @@ def _save_and_publish(draft: dict, fields: list[dict]) -> dict:
|
||||
|
||||
|
||||
def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app):
|
||||
"""自动建单开关独立于版本;每个关键字段只保存自身的最低置信度。"""
|
||||
"""自动建单开关写入草稿 definition;发布后才生效,并写入审计摘要。"""
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingOrderSchemaAuditEvent
|
||||
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
@@ -84,13 +87,41 @@ def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app):
|
||||
qty_config.update({'auto_create_key_field': True, 'minimum_confidence': 0.90})
|
||||
|
||||
saved = service.save_draft(draft['id'], {
|
||||
'fields': [part_config, qty_config], 'expected_lock_version': draft['lock_version'],
|
||||
'fields': [part_config, qty_config],
|
||||
'auto_creation_policy': {'enabled': True},
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
})
|
||||
by_code = {item['field_code']: item for item in saved['definition']['fields']}
|
||||
assert by_code['part_number']['minimum_confidence'] == 0.95
|
||||
assert by_code['qty']['minimum_confidence'] == 0.90
|
||||
assert saved['definition']['auto_creation_policy'] == {'enabled': True}
|
||||
# 草稿未发布前,运行时仍读已发布策略(无发布版本时默认关闭)。
|
||||
assert service.get_auto_creation_policy() == {'enabled': False}
|
||||
assert service.save_auto_creation_policy({'enabled': True}, actor_id=None) == {'enabled': True}
|
||||
with pytest.raises(ConflictError) as immediate:
|
||||
service.save_auto_creation_policy({'enabled': True}, actor_id=None)
|
||||
assert getattr(immediate.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_AUTO_CREATION_VIA_DRAFT'
|
||||
|
||||
published = service.publish(
|
||||
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], request_id='req-auto-create',
|
||||
)
|
||||
assert published['definition']['auto_creation_policy'] == {'enabled': True}
|
||||
assert service.get_auto_creation_policy() == {'enabled': True}
|
||||
|
||||
draft_saved = ShippingOrderSchemaAuditEvent.query.filter_by(event_type='draft_saved').order_by(
|
||||
ShippingOrderSchemaAuditEvent.id.desc(),
|
||||
).first()
|
||||
assert draft_saved is not None
|
||||
assert draft_saved.change_summary_json.get('auto_creation_policy_changed') is True
|
||||
assert draft_saved.change_summary_json.get('auto_creation_policy') == {
|
||||
'before': {'enabled': False}, 'after': {'enabled': True},
|
||||
}
|
||||
published_event = ShippingOrderSchemaAuditEvent.query.filter_by(event_type='published').order_by(
|
||||
ShippingOrderSchemaAuditEvent.id.desc(),
|
||||
).first()
|
||||
assert published_event is not None
|
||||
assert published_event.request_id == 'req-auto-create'
|
||||
assert published_event.change_summary_json.get('auto_creation_policy_changed') is True
|
||||
assert published_event.after_snapshot_json.get('auto_creation_policy') == {'enabled': True}
|
||||
|
||||
|
||||
def test_schema_save_rejects_normalized_table_alias_collision(app):
|
||||
|
||||
@@ -40,12 +40,12 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Parsed projection')
|
||||
db.session.add_all([user, schema])
|
||||
db.session.flush()
|
||||
fields = {}
|
||||
for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal'), ('inventory_source_hint', 'string')):
|
||||
field = ShippingOrderField(schema_id=schema.id, field_code=code, scope='line', value_type=value_type)
|
||||
fields[code] = field
|
||||
db.session.add(field)
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
fields = {
|
||||
code: ShippingOrderField.query.filter_by(field_code=code).one()
|
||||
for code in ('part_number', 'reservation_id', 'qty', 'inventory_source_hint')
|
||||
}
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id,
|
||||
version=1,
|
||||
|
||||
Reference in new issue
Block a user