From 61ac6403c40f23e86d254c2c6f5415fd069c6ea9 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Tue, 28 Jul 2026 20:25:48 +0800 Subject: [PATCH] =?UTF-8?q?refactor(agent,=20shipping):=20=E7=AE=80?= =?UTF-8?q?=E5=8C=96=E4=BB=A3=E7=90=86=E6=A8=A1=E5=9E=8B=E5=B9=B6=E5=AE=8C?= =?UTF-8?q?=E5=96=84=E8=AE=A2=E5=8D=95=E6=8A=BD=E5=8F=96=E4=B8=9A=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 移除 Agent 的 exposure_mode 与 internal_executor 相关逻辑,清理关联的过滤、序列化代码 - 删除废弃的 AgentRuntimeBinding 模型及其依赖 - 新增订单抽取上传批次、请求快照等数据库迁移与业务逻辑 - 修复附件完整性检测、订单抽取状态映射问题 - 更新多语言错误文案与前端单元测试配置 - 清理平台配置中不再使用的暴露模式配置 --- backend/app/api/admin/agents.py | 37 +- .../admin/shipping_order_document_profiles.py | 17 + backend/app/api/agents.py | 16 +- backend/app/api/chat.py | 8 +- backend/app/api/user.py | 37 +- backend/app/api/workspace/shipping_notice.py | 34 +- backend/app/core/config/settings.py | 23 + backend/app/core/decorators.py | 12 +- .../handlers/shipping_order_extraction.py | 678 +++++++- backend/app/models/__init__.py | 2 - backend/app/models/agent.py | 7 +- backend/app/models/agent_runtime_binding.py | 45 - backend/app/models/shipping.py | 4 + .../shipping_document_profile_auto_freeze.py | 9 +- .../models/shipping_order_extraction_run.py | 49 +- backend/app/services/admin/agent_service.py | 78 +- .../app/services/admin/dashboard_service.py | 15 +- backend/app/services/admin/faq_service.py | 11 - .../app/services/admin/permission_service.py | 12 +- backend/app/services/admin/report_service.py | 1 - backend/app/services/admin/user_service.py | 7 +- .../app/services/admin/wecom_admin_service.py | 8 +- .../app/services/agent_registry/__init__.py | 2 - .../services/agent_registry/admin_payload.py | 25 +- .../services/agent_registry/admin_schema.py | 2 - .../agent_registry/data/catalog_manifest.yaml | 3 - .../app/services/agent_registry/resolver.py | 17 - .../services/agent_registry/serialization.py | 3 - .../services/agent_runtime_binding_service.py | 219 --- backend/app/services/agent_user_access.py | 106 -- .../shipping_notice/attachment_integrity.py | 6 + .../shipping_notice/attachment_selection.py | 279 +++ .../document_candidate_persist.py | 23 +- .../coordinate_table_reconstruction.py | 22 +- .../document_layout/opencv_table.py | 7 +- .../document_layout/order_profile_matcher.py | 7 +- .../document_profile_quality_service.py | 97 +- .../email_allocation_table_parser.py | 63 + .../app/services/shipping_notice/eml_parse.py | 326 +++- .../freeze_readiness_service.py | 39 +- .../shipping_notice/intake_parse_workflow.py | 181 +- .../shipping_notice/intake_service.py | 22 +- .../services/shipping_notice/notice_upload.py | 33 +- .../order_auto_freeze_execution.py | 309 ++++ .../order_auto_freeze_policy.py | 255 +++ .../order_document_profile_service.py | 13 +- .../shipping_notice/order_extraction.py | 114 +- .../order_extraction_materialization.py | 312 ++++ .../shipping_notice/order_extraction_plan.py | 263 ++- .../order_extraction_progress.py | 350 ++-- .../order_extraction_run_service.py | 687 ++++++-- .../order_extraction_runtime_snapshot.py | 81 + .../order_extraction_snapshot_selection.py | 67 + .../order_extraction_workflow.py | 156 +- .../order_extraction_workspace_projection.py | 403 +++++ .../shipping_notice/order_freeze_service.py | 19 +- .../shipping_notice/preview_grant_store.py | 70 + .../services/shipping_notice/queue_service.py | 19 +- ...rebuild_order_extraction_progress_facts.py | 228 +++ ...move_internal_executor_runtime_bindings.py | 54 + ...1_align_order_route_decision_constraint.py | 55 + ...o_freeze_scope_to_profile_qualification.py | 48 + ...9b0c12_add_shipping_notice_upload_batch.py | 38 + ...add_order_extraction_unit_plan_metadata.py | 63 + ...c_add_order_extraction_request_snapshot.py | 33 + .../services/admin/test_agent_service.py | 83 +- .../services/admin/test_permission_service.py | 49 - .../tests/services/admin/test_user_service.py | 20 - .../admin/test_wecom_admin_service.py | 25 - .../test_shipping_order_snapshot.py | 43 + .../test_agent_registry_catalog_validation.py | 68 - backend/tests/test_agent_registry_resolver.py | 8 - .../test_agent_registry_serialization.py | 4 - .../test_agent_runtime_binding_migration.py | 67 - backend/tests/test_agent_runtime_bindings.py | 1531 ----------------- backend/tests/test_email_supplement_merge.py | 26 +- .../test_internal_executor_user_isolation.py | 65 - ..._internal_executor_user_links_migration.py | 104 -- .../test_order_extraction_pdf_po_split.py | 13 +- ...der_extraction_progress_facts_migration.py | 102 ++ ...r_extraction_request_snapshot_migration.py | 47 + ...est_profile_auto_freeze_scope_migration.py | 42 + .../test_shipping_attachment_selection.py | 641 +++++++ .../test_shipping_document_profile_quality.py | 47 +- backend/tests/test_shipping_notice_extract.py | 66 + backend/tests/test_shipping_notice_intakes.py | 355 +++- ..._shipping_notice_upload_batch_migration.py | 46 + .../test_shipping_order_auto_freeze_policy.py | 381 ++++ ...shipping_order_document_profile_service.py | 15 +- ...test_shipping_order_extraction_progress.py | 149 +- ..._shipping_order_extraction_quality_gate.py | 365 +--- ...ping_order_extraction_quality_migration.py | 17 +- ..._order_extraction_run_quality_migration.py | 39 - .../test_shipping_order_extraction_runs.py | 1044 +++++++++-- .../test_shipping_order_extraction_stage0.py | 59 +- .../test_shipping_order_extraction_worker.py | 368 ++++ ...er_extraction_workspace_projection_unit.py | 42 + .../test_shipping_order_profile_matcher.py | 19 + docs/convention/error_handling.md | 21 + docs/demand.md | 31 +- docs/features/shipping-notice/technical.md | 229 ++- docs/funclist.md | 5 +- docs/platform/agent_application_management.md | 37 - ...t_application_management_implementation.md | 39 +- docs/tec.md | 34 +- docs/test_plan_matrix.md | 49 +- frontend/package-lock.json | 1205 +++++++++++++ frontend/package.json | 2 + frontend/src/features/admin/api/admin.api.ts | 53 +- .../admin/modules/agents/AgentsPage.vue | 100 +- .../agents/components/AgentFormModal.vue | 58 +- .../agents/composables/useAgentsAdmin.ts | 31 +- .../composables/useAgentsAdminRegistry.ts | 11 - .../composables/usePermissionsAdmin.ts | 2 +- .../platform-apps/PlatformAppsPage.vue | 2 +- .../composables/useHotFaqCandidates.ts | 2 +- .../composables/useQuestionsAdmin.ts | 2 +- .../ShippingOrderExtractionRunsPage.vue | 42 +- .../users/composables/useUsersAdmin.ts | 2 +- .../src/features/admin/types/agent.types.ts | 36 - .../shipping-order-document-profile.types.ts | 6 + frontend/src/features/chat/api/chat.api.ts | 2 +- .../src/features/chat/api/shipping.api.ts | 10 + .../features/chat/components/ChatInputBar.vue | 48 +- .../components/messages/ChatMessageBubble.vue | 255 +-- .../ShippingOrderDocumentResultItem.vue | 185 ++ .../ShippingOrderExtractionCard.spec.ts | 422 +++++ .../shipping/ShippingOrderExtractionCard.vue | 302 ++++ .../ShippingOrderExtractionDetailsDrawer.vue | 251 +++ .../features/chat/composables/useChat.spec.ts | 110 +- .../src/features/chat/composables/useChat.ts | 124 +- .../chat/page/useChatPageMarkdown.spec.ts | 25 +- .../shipping/orderExtractionTimeline.spec.ts | 46 + .../chat/shipping/orderExtractionTimeline.ts | 74 + .../shippingNoticeAttachmentIntegrity.ts | 10 + .../useChatShippingSendHandler.spec.ts | 314 ++-- .../shipping/useChatShippingSendHandler.ts | 34 +- .../shipping/useShippingNoticeIntakes.spec.ts | 25 +- .../chat/shipping/useShippingNoticeIntakes.ts | 64 +- .../useShippingOrderExtractionRuns.spec.ts | 193 ++- .../useShippingOrderExtractionRuns.ts | 127 +- .../src/features/chat/types/chat.types.ts | 84 +- .../features/chat/types/shipping.api.types.ts | 127 +- .../src/features/chat/types/shipping.types.ts | 17 +- .../chat/utils/attachmentCard.utils.spec.ts | 30 +- .../chat/utils/attachmentCard.utils.ts | 13 +- frontend/src/locales/en/admin.json | 33 +- frontend/src/locales/en/chat.json | 188 +- frontend/src/locales/en/errors.json | 2 + frontend/src/locales/th/admin.json | 33 +- frontend/src/locales/th/chat.json | 188 +- frontend/src/locales/th/errors.json | 2 + frontend/src/locales/zh-CN/admin.json | 33 +- frontend/src/locales/zh-CN/chat.json | 192 ++- frontend/src/locales/zh-CN/errors.json | 2 + frontend/src/locales/zh-TW/admin.json | 33 +- frontend/src/locales/zh-TW/chat.json | 186 +- frontend/src/locales/zh-TW/errors.json | 2 + frontend/vitest.config.ts | 18 + 159 files changed, 12883 insertions(+), 5099 deletions(-) delete mode 100644 backend/app/models/agent_runtime_binding.py delete mode 100644 backend/app/services/agent_runtime_binding_service.py delete mode 100644 backend/app/services/agent_user_access.py create mode 100644 backend/app/services/shipping_notice/attachment_selection.py create mode 100644 backend/app/services/shipping_notice/order_auto_freeze_execution.py create mode 100644 backend/app/services/shipping_notice/order_auto_freeze_policy.py create mode 100644 backend/app/services/shipping_notice/order_extraction_materialization.py create mode 100644 backend/app/services/shipping_notice/order_extraction_runtime_snapshot.py create mode 100644 backend/app/services/shipping_notice/order_extraction_snapshot_selection.py create mode 100644 backend/app/services/shipping_notice/order_extraction_workspace_projection.py create mode 100644 backend/app/services/shipping_notice/preview_grant_store.py create mode 100644 backend/migrations/versions/0ab45c6d7e8f_rebuild_order_extraction_progress_facts.py create mode 100644 backend/migrations/versions/0ac56d7e8f90_remove_internal_executor_runtime_bindings.py create mode 100644 backend/migrations/versions/0bd56e7f8a91_align_order_route_decision_constraint.py create mode 100644 backend/migrations/versions/0ce67f8a9b01_add_auto_freeze_scope_to_profile_qualification.py create mode 100644 backend/migrations/versions/0cf78a9b0c12_add_shipping_notice_upload_batch.py create mode 100644 backend/migrations/versions/1c2d3e4f5a6b_add_order_extraction_unit_plan_metadata.py create mode 100644 backend/migrations/versions/2d3e4f5a6b7c_add_order_extraction_request_snapshot.py delete mode 100644 backend/tests/test_agent_runtime_binding_migration.py delete mode 100644 backend/tests/test_agent_runtime_bindings.py delete mode 100644 backend/tests/test_internal_executor_user_isolation.py delete mode 100644 backend/tests/test_internal_executor_user_links_migration.py create mode 100644 backend/tests/test_order_extraction_progress_facts_migration.py create mode 100644 backend/tests/test_order_extraction_request_snapshot_migration.py create mode 100644 backend/tests/test_profile_auto_freeze_scope_migration.py create mode 100644 backend/tests/test_shipping_attachment_selection.py create mode 100644 backend/tests/test_shipping_notice_upload_batch_migration.py create mode 100644 backend/tests/test_shipping_order_auto_freeze_policy.py create mode 100644 backend/tests/test_shipping_order_extraction_worker.py create mode 100644 backend/tests/test_shipping_order_extraction_workspace_projection_unit.py create mode 100644 frontend/src/features/chat/components/shipping/ShippingOrderDocumentResultItem.vue create mode 100644 frontend/src/features/chat/components/shipping/ShippingOrderExtractionCard.spec.ts create mode 100644 frontend/src/features/chat/components/shipping/ShippingOrderExtractionCard.vue create mode 100644 frontend/src/features/chat/components/shipping/ShippingOrderExtractionDetailsDrawer.vue create mode 100644 frontend/src/features/chat/shipping/orderExtractionTimeline.spec.ts create mode 100644 frontend/src/features/chat/shipping/orderExtractionTimeline.ts create mode 100644 frontend/vitest.config.ts diff --git a/backend/app/api/admin/agents.py b/backend/app/api/admin/agents.py index 2a577bb2..9e717307 100644 --- a/backend/app/api/admin/agents.py +++ b/backend/app/api/admin/agents.py @@ -9,7 +9,6 @@ from flask import g, request from app.api.admin.blueprint import admin_bp from app.core.decorators import require_admin -from app.core.errors import ValidationError from app.core.response import ok from app.services.admin import agent_service @@ -69,8 +68,8 @@ def list_agent_intent_routes(): @admin_bp.route('/agents', methods=['GET']) @require_admin def list_agents(): - """按管理页签返回应用或内部执行器;缺省 scope 保持旧版全部列表兼容。""" - return ok(agent_service.list_agents(scope=request.args.get('scope')), request_id=_request_id()) + """列出全部应用。""" + return ok(agent_service.list_agents(), request_id=_request_id()) @admin_bp.route('/agents', methods=['POST']) @@ -107,38 +106,6 @@ def test_agent(id: int): return ok(payload, request_id=_request_id()) -@admin_bp.route('/agents//runtime-bindings', methods=['GET']) -@require_admin -def list_agent_runtime_bindings(id: int): - """列出入口 Agent 的显式运行能力绑定。""" - from app.services.agent_runtime_binding_service import list_runtime_bindings - - return ok(list_runtime_bindings(id), request_id=_request_id()) - - -@admin_bp.route('/agents//runtime-bindings/', methods=['PUT']) -@require_admin -def save_agent_runtime_binding(id: int, capability_code: str): - """保存单个能力 Provider;API Key 仍由 Provider Agent 自身配置管理。""" - body = request.get_json(silent=True) - if not isinstance(body, dict): - raise ValidationError('JSON body must be an object') - try: - provider_agent_id = int(body.get('provider_agent_id')) - except (TypeError, ValueError) as exc: - raise ValidationError('provider_agent_id is required') from exc - from app.services.agent_runtime_binding_service import save_runtime_binding, serialize_runtime_binding - - binding = save_runtime_binding( - owner_agent_id=id, - capability_code=capability_code, - provider_agent_id=provider_agent_id, - enabled=body.get('enabled') is not False, - config=body.get('config'), - ) - return ok(serialize_runtime_binding(binding), request_id=_request_id()) - - @admin_bp.route('/agents//permissions', methods=['POST']) @require_admin def update_agent_permissions(id: int): diff --git a/backend/app/api/admin/shipping_order_document_profiles.py b/backend/app/api/admin/shipping_order_document_profiles.py index a210a1c1..d8aedffe 100644 --- a/backend/app/api/admin/shipping_order_document_profiles.py +++ b/backend/app/api/admin/shipping_order_document_profiles.py @@ -223,6 +223,23 @@ def suspend_order_document_profile_auto_freeze_qualification(profile_id: int): return _ok(quality.serialize_qualification(qualification)) +@admin_bp.route('/shipping-notice/order-document-profiles//auto-freeze-qualification/scope', methods=['POST']) +@require_admin +def configure_order_document_profile_auto_freeze_scope(profile_id: int): + """配置模板版本的客户/业务场景自动冻结范围;空列表表示清空授权范围。""" + from app.services.shipping_notice import document_profile_quality_service as quality + + data = request.get_json(silent=True) or {} + qualification = quality.configure_auto_freeze_qualification_scope( + profile_id=profile_id, + actor_id=int(_actor_id() or 0), + customer_ids=data.get('customer_ids'), + business_scenarios=data.get('business_scenarios'), + requires_customer_confirmation=bool(data.get('requires_customer_confirmation', True)), + ) + return _ok(quality.serialize_qualification(qualification)) + + @admin_bp.route('/shipping-notice/order-document-profiles/', methods=['DELETE']) @require_admin def delete_order_document_profile(profile_id: int): diff --git a/backend/app/api/agents.py b/backend/app/api/agents.py index b66967eb..97d39778 100644 --- a/backend/app/api/agents.py +++ b/backend/app/api/agents.py @@ -15,7 +15,6 @@ from app.core.auth.jwt import get_current_user from app.core.errors import UnauthorizedError from app.models import Agent, User, AgentGuide from app.services.agent_category import serialize_agent_list_item, sort_agent_rows -from app.services.agent_user_access import require_user_application_access from app.services.minio_service import minio_service # 定义 Blueprint,将在应用工厂中注册为 /api/agents @@ -41,11 +40,11 @@ def _list_active_agents_for_user(user: User) -> list[Agent]: if user.role == 'admin': return ( db.session.query(Agent) - .filter(Agent.is_active.is_(True), Agent.exposure_mode == 'workspace') + .filter(Agent.is_active.is_(True)) .order_by(Agent.id.asc()) .all() ) - return [agent for agent in user.agents if agent.is_active and agent.exposure_mode == 'workspace'] + return [agent for agent in user.agents if agent.is_active] @agents_bp.route('', methods=['GET']) @@ -68,14 +67,12 @@ def list_agent_guides(agent_id): 获取指定应用的新手指南列表 (需登录) 用途:客户端 Chat 界面点击新手指南 """ - user = get_current_user() - if not user: - raise UnauthorizedError() + get_current_user() # Ensure user is logged in. if agent_id == 0: generic_agent = ( db.session.query(Agent) - .filter_by(agent_code='generic', is_active=True, exposure_mode='workspace') + .filter_by(agent_code='generic', is_active=True) .order_by(Agent.sort_order.asc(), Agent.id.asc()) .first() ) @@ -84,9 +81,6 @@ def list_agent_guides(agent_id): else: return jsonify([]) - agent = db.session.get(Agent, agent_id) - require_user_application_access(agent, user) - guides = ( db.session.query(AgentGuide) .filter_by(agent_id=agent_id, status=1) @@ -116,7 +110,7 @@ def list_public_agents(): """ agents = ( db.session.query(Agent) - .filter(Agent.is_active.is_(True), Agent.exposure_mode == 'workspace') + .filter(Agent.is_active.is_(True)) .order_by(Agent.id.asc()) .all() ) diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index 1053864f..d12d6bfa 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -229,7 +229,13 @@ def _order_extraction_attention_by_conversation( if not conversation_ids: return {} severity_rank = {'info': 1, 'warning': 2, 'error': 3} - status_severity = {'completed': 'info', 'needs_review': 'warning', 'failed': 'error', 'cancelled': 'error'} + status_severity = { + 'completed': 'info', + 'partially_completed': 'warning', + 'review_required': 'warning', + 'failed': 'error', + 'cancelled': 'error', + } rows = db.session.query( ShippingOrderExtractionRun.conversation_id, ShippingOrderExtractionRun.status, diff --git a/backend/app/api/user.py b/backend/app/api/user.py index 7bb3e060..064947d4 100644 --- a/backend/app/api/user.py +++ b/backend/app/api/user.py @@ -11,11 +11,6 @@ from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaul from app.services.feedback_notify import send_feedback_group_notification from app.services.agent_category import serialize_agent_list_item, sort_agent_rows from app.services.agent_registry.serialization import serialize_registry_fields -from app.services.agent_user_access import ( - require_user_application_access, - visible_agent_ids, - visible_default_agent_id, -) from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field from app.core.auth.jwt import get_current_user as _auth_current_user @@ -446,7 +441,7 @@ def _build_login_payload(user: User, source: str='password', bind_status: str=No 'id': user.id, 'username': user.username, 'role': user.role, - 'default_agent_id': visible_default_agent_id(user), + 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': source, 'access_token': issue_local_access_token(user), @@ -775,7 +770,7 @@ def casdoor_password_login(): _write_login_audit('casdoor', 'success', user=user) db.session.commit() api_bearer_token = id_token or access_token - return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': visible_default_agent_id(user), 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in}) + return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in}) except WeComLoginError: db.session.rollback() raise @@ -905,7 +900,7 @@ def casdoor_login(): _write_login_audit('casdoor', 'success', user=user) db.session.commit() api_bearer_token = id_token or access_token - return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': visible_default_agent_id(user), 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in}) + return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in}) except WeComLoginError: db.session.rollback() current_app.logger.warning('[casdoor_login] business_reject') @@ -1346,32 +1341,26 @@ def home(): raise UnauthorizedError('Unauthorized') def _load_home_payload(): - allowed_agent_ids = visible_agent_ids(user) if user.role == 'admin': - agent_rows = Agent.query.filter( - Agent.is_active.is_(True), Agent.exposure_mode == 'workspace', - ).all() + agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all() else: - agent_rows = [ - agent for agent in user.agents - if agent.is_active and agent.exposure_mode == 'workspace' - ] + agent_rows = [agent for agent in user.agents if agent.is_active] agent_rows = sort_agent_rows(agent_rows) favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all() - favorite_ids = [f.agent_id for f in favorites if f.agent_id in allowed_agent_ids] + favorite_ids = [f.agent_id for f in favorites] qqs = db.session.query(QuickQuestion).filter( or_( QuickQuestion.user_id == user.id, and_(QuickQuestion.user_id.is_(None), QuickQuestion.is_enabled.is_(True)), ) - ).filter(QuickQuestion.agent_id.in_(allowed_agent_ids)).all() if allowed_agent_ids else [] + ).all() layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first() layout = layout_config.layout if layout_config else {} embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all() embedded_agents = [] for rel in embedded_rel: agent = db.session.get(Agent, rel.agent_id) - if agent and agent.id in allowed_agent_ids: + if agent: registry = serialize_registry_fields(agent) embedded_agents.append({ 'id': agent.id, @@ -1380,7 +1369,7 @@ def home(): 'runtime_provider': registry.get('runtime_provider'), 'conversation_mode': registry.get('conversation_mode'), }) - return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': visible_default_agent_id(user), 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout}) + return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout}) try: return _run_db_with_retry(_load_home_payload, label='user.home') except (OperationalError, DatabaseError) as exc: @@ -1392,7 +1381,6 @@ def toggle_favorite(agent_id: int): user = _get_current_user() if not user: raise UnauthorizedError('Unauthorized') - require_user_application_access(db.session.get(Agent, agent_id), user) if request.method == 'POST': exists = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).first() if not exists: @@ -1411,7 +1399,6 @@ def add_quick_question(): data = request.get_json() or {} if not data.get('title') or not data.get('question') or (not data.get('agent_id')): raise ValidationError('Missing fields') - require_user_application_access(db.session.get(Agent, data['agent_id']), user) qq = QuickQuestion(user_id=user.id, title=data['title'], question=data['question'], agent_id=data['agent_id']) db.session.add(qq) db.session.commit() @@ -1435,7 +1422,6 @@ def update_quick_question(qq_id: int): if 'question' in data: qq.question = data['question'] if 'agent_id' in data: - require_user_application_access(db.session.get(Agent, data['agent_id']), user) qq.agent_id = data['agent_id'] db.session.commit() return jsonify({'status': 'ok'}) @@ -1829,7 +1815,10 @@ def get_agent_details(id): if not user: raise UnauthorizedError('Unauthorized') agent = db.session.get(Agent, id) - require_user_application_access(agent, user) + if not agent: + raise NotFoundError('Not found') + if user.role != 'admin' and agent not in user.agents: + raise ForbiddenError('Access denied') from app.services.agent_registry.resolver import resolve_runtime_provider from app.services.agent_registry.serialization import serialize_agent_for_user_detail diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index bffe6aaf..bd2e4ff1 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -971,6 +971,17 @@ def workspace_create_shipping_order_extraction_run(): code='SHIPPING_NOTICE.ORDER_EXTRACTION_AGENT_INVALID', ) from exc conversation_id = str(body.get('conversation_id') or '').strip() + upload_batch_id = str(body.get('upload_batch_id') or '').strip() + if not upload_batch_id: + raise ValidationError( + 'upload_batch_id is required', + code='SHIPPING_NOTICE.UPLOAD_BATCH_REQUIRED', + ) + if len(upload_batch_id) > 36: + raise ValidationError( + 'upload_batch_id is too long', + code='SHIPPING_NOTICE.UPLOAD_BATCH_INVALID', + ) intake_nos = body.get('intake_nos') if not isinstance(intake_nos, list): raise ValidationError( @@ -987,6 +998,7 @@ def workspace_create_shipping_order_extraction_run(): agent_id=agent_id, conversation_id=conversation_id, intake_nos=intake_nos, + upload_batch_id=upload_batch_id, ) db.session.commit() return ok( @@ -1017,6 +1029,15 @@ def workspace_list_shipping_order_extraction_progress_events(run_no: str): return _ok({'items': list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no)}) +@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs//documents', methods=['GET']) +def workspace_list_shipping_order_extraction_documents(run_no: str): + """返回当前用户一次订单抽取的按 PDF 归并详情。""" + user = _require_user() + from app.services.shipping_notice.order_extraction_run_service import list_user_order_extraction_documents + + return _ok({'items': list_user_order_extraction_documents(user_id=user.id, run_no=run_no)}) + + @workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs//seen', methods=['POST']) def workspace_mark_shipping_order_extraction_run_seen(run_no: str): """确认当前用户已加载终态订单识别卡片;仅用于会话待查看提醒,不改变业务结果。""" @@ -1103,12 +1124,23 @@ def workspace_create_shipping_notice_intake(): if not asset_no: raise ValidationError('asset_no is required') conversation_id = str(body.get('conversation_id') or '').strip() or None + upload_batch_id = str(body.get('upload_batch_id') or '').strip() + if not upload_batch_id: + raise ValidationError( + 'upload_batch_id is required', + code='SHIPPING_NOTICE.UPLOAD_BATCH_REQUIRED', + ) + if len(upload_batch_id) > 36: + raise ValidationError( + 'upload_batch_id is too long', + code='SHIPPING_NOTICE.UPLOAD_BATCH_INVALID', + ) from app.services.shipping_notice.intake_service import create_shipping_notice_intake - data = create_shipping_notice_intake( user_id=user.id, asset_no=asset_no, conversation_id=conversation_id, + upload_batch_id=upload_batch_id, ) return ok(data, request_id=getattr(g, 'request_id', None), status=202) diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 92d22dc6..b474f46f 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -171,6 +171,8 @@ class Config: DIFY_CHAT_READ_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_READ_TIMEOUT_SECONDS', '30')) # Redis 连接配置,默认使用本地 Redis + 密码 REDIS_URL = os.getenv('REDIS_URL') + # 订单文档模板预览默认要求 Redis;仅开发单进程 run.py 可显式放开进程内一次性令牌兜底。 + ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK = False FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true' HR_WORKFLOW_IFRAME_URL = os.getenv('HR_WORKFLOW_IFRAME_URL') HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE') @@ -461,6 +463,19 @@ class Config: SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS = int( os.getenv('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', '300') ) + # 订单抽取发送后选择计划预算:首轮只挑最相关附件,后续批次按固定预算待扩展。 + SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_ATTACHMENTS = int( + os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_ATTACHMENTS', '2') + ) + SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_CONCURRENCY = int( + os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_CONCURRENCY', '2') + ) + SHIPPING_NOTICE_ORDER_EXTRACTION_EXPANSION_BATCH_SIZE = int( + os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_EXPANSION_BATCH_SIZE', '2') + ) + SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS = int( + os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS', '6') + ) SHIPPING_NOTICE_PARSER_VERSION = os.getenv('SHIPPING_NOTICE_PARSER_VERSION', 'v6') SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED = os.getenv( 'SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED', 'false' @@ -510,11 +525,19 @@ class Config: SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS = int( os.getenv('SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS', str(500_000)) ) + # 订单抽取 Worker 的全 Run 资源门槛;超出时停止扩批并进入可复核终态。 + SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_BYTES = int( + os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_BYTES', str(30 * 1024 * 1024)) + ) + SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_RUNTIME_SECONDS = int( + os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_RUNTIME_SECONDS', '300') + ) class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL') + ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK = True # 本机常无 Redis:不强制 Redis,允许进程内存兜底心跳(单进程 run.py 可用) SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True diff --git a/backend/app/core/decorators.py b/backend/app/core/decorators.py index a0b4b228..3c2838b7 100644 --- a/backend/app/core/decorators.py +++ b/backend/app/core/decorators.py @@ -13,9 +13,8 @@ from functools import wraps from flask import current_app, g, request from app.core.auth.jwt import get_current_user as _auth_current_user -from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError +from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError from app.models import Agent, User -from app.services.agent_user_access import require_user_application_access def _get_current_user() -> User: @@ -48,7 +47,7 @@ def _resolve_request_agent_id() -> str | None: def require_agent_permission(f): """ 装饰器:校验当前用户是否拥有指定 Agent 访问权限。 - 核心逻辑:从 body/query/form 读 agent_id → 阻断内部执行器 → admin 放行 workspace 或检查用户授权。 + 核心逻辑:从 body/query/form 读 agent_id → 获取用户 → admin 放行或检查 user.agents。 Args: f: 被装饰的视图函数。 Returns: @@ -64,8 +63,13 @@ def require_agent_permission(f): if not user: raise UnauthorizedError('Unauthorized') agent = Agent.query.get(agent_id) - require_user_application_access(agent, user) + if not agent: + raise NotFoundError('Agent not found') g.current_agent = agent + if user.role == 'admin': + return f(*args, **kwargs) + if agent not in user.agents: + raise ForbiddenError('Permission denied for this agent') return f(*args, **kwargs) return decorated_function diff --git a/backend/app/jobs/handlers/shipping_order_extraction.py b/backend/app/jobs/handlers/shipping_order_extraction.py index 78ecf77b..f3772ca0 100644 --- a/backend/app/jobs/handlers/shipping_order_extraction.py +++ b/backend/app/jobs/handlers/shipping_order_extraction.py @@ -9,7 +9,10 @@ backend/app/jobs/handlers/shipping_order_extraction.py from __future__ import annotations import time +from datetime import date, datetime +from decimal import Decimal from datetime import datetime +from typing import Any from app import db from app.core.errors import AppError @@ -22,6 +25,7 @@ from app.models import ( ShippingOrderExtractionPlan, ShippingOrderExtractionRouteDecision, ShippingOrderExtractionRun, + ShippingNoticeIntake, ShippingOrderExtractionUnit, ) from app.services.shipping_notice.audit_service import append_shipping_audit_event @@ -29,16 +33,52 @@ from app.services.shipping_notice.order_extraction import submit_order_extractio from app.services.shipping_notice.order_extraction_merge import merge_unit_orders from app.services.shipping_notice.order_extraction_run_service import ( mark_order_extraction_persistence_started, + materialize_order_extraction_run_inputs, transition_order_extraction_run, ) +from app.services.shipping_notice.order_extraction_progress import ( + record_run_progress, + record_unit_progress, +) from app.services.shipping_notice.order_extraction_workflow import ( route_deterministic_unit, validate_unit_orders, ) +MAX_UNIT_TECHNICAL_ATTEMPTS = 3 +EXPANDABLE_UNIT_REVIEW_REASON_CODES = { + 'required_anchor_missing', + 'required_field_missing', + 'business_table_not_found', + 'multiple_business_tables', + 'po_missing', + 'multiple_po_detected', + 'row_needs_review', +} + + +def _json_safe_order_payload(value: Any) -> Any: + """将坐标解析的 Decimal/date 递归转为 JSON 标量后写入 Unit 快照。 + + 模板解析保留 Decimal 以便规则校验;Unit 的 result_json 是 JSON 列,落库前必须 + 转为字符串,避免候选已生成却在持久化边界失败。 + """ + if isinstance(value, Decimal): + return format(value.normalize(), 'f') + if isinstance(value, (date, datetime)): + return value.isoformat() + if isinstance(value, list): + return [_json_safe_order_payload(item) for item in value] + if isinstance(value, dict): + return {str(key): _json_safe_order_payload(item) for key, item in value.items()} + return value +EXPANDABLE_ORDER_CONFLICT_REASONS = { + 'supplement_relation_ambiguous', +} + def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) -> None: - """追加 Unit 脱敏路由投影及统一审计,禁止保存订单值、正文或布局载荷。""" + """追加 Unit 脱敏路由投影及统一审计,尝试号必须区分同一 Job 内的单元重试。""" decision = route_result.decision if isinstance(route_result.decision, dict) else {} candidates = decision.get('candidate_summary') if isinstance(decision.get('candidate_summary'), list) else [] safe_candidates = [{ @@ -86,13 +126,358 @@ def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) -> def _result_requires_review(*, units: list[ShippingOrderExtractionUnit], result: dict) -> bool: - """汇总人工复核、未接受候选和技术局部失败,确保不把不完整订单标记完成。""" + """汇总人工复核、未接受候选、技术失败和自动冻结阻断,避免不完整 Run 被标记完成。""" return bool( result.get('pending_count') - or any(unit.status in {'skipped', 'failed'} for unit in units) + or result.get('auto_freeze', {}).get('blocked_tasks') + or any(unit.status in {'review_required', 'failed'} for unit in units) ) +def _selection_progress_summary(run: ShippingOrderExtractionRun) -> dict[str, int]: + """从冻结选择计划提取首轮预算摘要,供 Run 级事件和卡片文案直接使用。""" + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {} + items = selection.get('items') if isinstance(selection.get('items'), list) else [] + budget_limited_count = sum( + 1 for item in items if isinstance(item, dict) + and {'budget_initial_limit', 'budget_total_limit'} & {str(code) for code in (item.get('skip_reason_codes') or [])} + ) + return { + 'total_attachment_count': int(selection.get('total_attachment_count') or 0), + 'selected_attachment_count': int(selection.get('selected_attachment_count') or 0), + 'planned_attachment_count': int(selection.get('planned_attachment_count') or 0), + 'pending_expansion_attachment_count': int(selection.get('pending_expansion_attachment_count') or 0), + 'group_count': int(selection.get('group_count') or 0), + 'max_initial_attachments': int(selection.get('max_initial_attachments') or 0), + 'max_initial_concurrency': int(selection.get('max_initial_concurrency') or 0), + 'budget_limited_attachment_count': budget_limited_count, + } + + +def _units_for_batch(plan: ShippingOrderExtractionPlan, *, selection_batch: int) -> list[ShippingOrderExtractionUnit]: + """按批次读取计划单元;未标批次的普通文件视为首轮。""" + normalized_batch = int(selection_batch or 1) + return [ + unit for unit in plan.units + if int(unit.selection_batch or 1) == normalized_batch + ] + + +def _next_existing_batch(plan: ShippingOrderExtractionPlan, *, after_batch: int) -> int | None: + """返回计划中已存在但尚未轮到的下一批。""" + candidates = sorted({ + int(unit.selection_batch or 1) + for unit in plan.units + if int(unit.selection_batch or 1) > int(after_batch or 0) + }) + return candidates[0] if candidates else None + + +def _pending_snapshot_batches(run: ShippingOrderExtractionRun, plan: ShippingOrderExtractionPlan) -> list[int]: + """从冻结选择计划中找出尚未激活为执行单元的后续批次。""" + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {} + planned_batches = sorted({ + int(item.get('planned_selection_batch') or 0) + for item in selection.get('items') or [] + if isinstance(item, dict) and int(item.get('planned_selection_batch') or 0) > 1 + }) + existing_batches = { + int(unit.selection_batch or 1) + for unit in plan.units + if int(unit.selection_batch or 1) > 1 + } + return [batch for batch in planned_batches if batch not in existing_batches] + + +def _should_expand_after_wave(*, wave_units: list[ShippingOrderExtractionUnit], wave_orders: list[dict]) -> bool: + """仅在可通过更多附件补证的业务缺口出现时才扩下一轮。""" + return bool(_expansion_trigger_reason_codes(wave_units=wave_units, wave_orders=wave_orders)) + + +def _expansion_trigger_reason_codes( + *, + wave_units: list[ShippingOrderExtractionUnit], + wave_orders: list[dict], +) -> list[str]: + """汇总当前批次触发扩批的业务原因码,供事件与工作台共享。""" + if not wave_units: + return [] + reason_codes = { + str(unit.reason_code or '').strip() + for unit in wave_units + if unit.status == 'review_required' + and str(unit.reason_code or '').strip() in EXPANDABLE_UNIT_REVIEW_REASON_CODES + } + for order in wave_orders: + if not isinstance(order, dict): + continue + if order.get('_hxops_expand_for_missing_reservation'): + reason_codes.add('missing_reservation_id') + for conflict in order.get('conflicts') or []: + if not isinstance(conflict, dict): + continue + code = str(conflict.get('reason') or '').strip() + if code in EXPANDABLE_ORDER_CONFLICT_REASONS: + reason_codes.add(code) + return sorted(code for code in reason_codes if code) + + +def _schema_field_ids_by_code(run: ShippingOrderExtractionRun) -> dict[str, set[str]]: + """读取冻结 Schema 中稳定 field_code -> field_id 集合,供业务缺口判定复用。""" + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {} + definition = schema.get('definition') if isinstance(schema.get('definition'), dict) else {} + mapping: dict[str, set[str]] = {} + for item in definition.get('fields') or []: + if not isinstance(item, dict): + continue + field_code = str(item.get('field_code') or '').strip() + field_id = str(item.get('field_id') or '').strip() + if not field_code or not field_id: + continue + mapping.setdefault(field_code, set()).add(field_id) + return mapping + + +def _field_has_value(fields: list[dict] | None, *, field_ids: set[str]) -> bool: + """判断指定字段是否存在非空 Observation。""" + for field in fields or []: + if not isinstance(field, dict) or str(field.get('field_id') or '') not in field_ids: + continue + for observation in field.get('observations') or []: + if isinstance(observation, dict) and str(observation.get('value') or '').strip(): + return True + return False + + +def _order_requires_expansion(order: dict[str, Any]) -> bool: + """识别当前订单是否仍缺少可由其他附件补证的业务字段或存在冲突。""" + conflicts = [ + item for item in (order.get('conflicts') or []) + if isinstance(item, dict) + ] + if any(str(item.get('reason') or '').strip() in EXPANDABLE_ORDER_CONFLICT_REASONS for item in conflicts): + return True + return bool(order.get('_hxops_expand_for_missing_reservation')) + + +def _mark_expandable_business_gaps( + run: ShippingOrderExtractionRun, + *, + orders: list[dict[str, Any]], +) -> list[dict[str, Any]]: + """把可由后续附件补证的业务缺口标记到订单上,供扩批决策复用。""" + field_ids_by_code = _schema_field_ids_by_code(run) + reservation_field_ids = field_ids_by_code.get('reservation_id', set()) + if not reservation_field_ids: + return orders + for order in orders: + if not isinstance(order, dict): + continue + lines = order.get('lines') if isinstance(order.get('lines'), list) else [] + order['_hxops_expand_for_missing_reservation'] = any( + isinstance(line, dict) + and not _field_has_value(line.get('fields'), field_ids=reservation_field_ids) + for line in lines + ) + return orders + + +def _wave_orders_for_expansion( + run: ShippingOrderExtractionRun, + *, + orders: list[dict[str, Any]], +) -> list[dict[str, Any]]: + """为当前批次生成扩批判定所需的业务事实视图。""" + if not orders: + return [] + schema_snapshot = run.input_snapshot_json.get('schema') if isinstance(run.input_snapshot_json, dict) else {} + merged = merge_unit_orders( + orders=orders, + schema_definition=schema_snapshot.get('definition') or {}, + ) + from app.services.shipping_notice.order_supplement_merge import merge_email_supplements + supplements_by_intake = { + int(intake.get('intake_id') or 0): supplement + for intake in run.input_snapshot_json.get('intakes') or [] if isinstance(intake, dict) + for supplement in intake.get('email_supplements') or [] if isinstance(supplement, dict) + } + merged = merge_email_supplements( + orders=merged, + supplements_by_intake=supplements_by_intake, + schema_definition=schema_snapshot.get('definition') or {}, + ) + return _mark_expandable_business_gaps(run, orders=merged) + + +def _activate_expansion_batch( + *, + run: ShippingOrderExtractionRun, + plan: ShippingOrderExtractionPlan, + selection_batch: int, +) -> list[ShippingOrderExtractionUnit]: + """按冻结批次计划补物化附件并追加执行单元;重复触发保持幂等。""" + from app.services.shipping_notice.order_extraction_materialization import ensure_order_extraction_input_documents + from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan_batch + + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {} + schema_definition = (snapshot.get('schema') or {}).get('definition') if isinstance(snapshot.get('schema'), dict) else {} + intake_ids = [ + int(item.get('intake_id')) + for item in (snapshot.get('intakes') or []) + if isinstance(item, dict) and item.get('intake_id') is not None + ] + intakes = ( + ShippingNoticeIntake.query + .filter(ShippingNoticeIntake.id.in_(intake_ids)) + .order_by(ShippingNoticeIntake.id.asc()) + .all() + ) if intake_ids else [] + ensure_order_extraction_input_documents( + intakes=intakes, + attachment_selection=selection, + schema_definition=schema_definition if isinstance(schema_definition, dict) else {}, + selection_batches={int(selection_batch)}, + ) + return ensure_order_extraction_plan_batch(run, selection_batch=int(selection_batch)) + + +def _reload_run_and_unit(*, run_id: int, unit_id: int) -> tuple[ShippingOrderExtractionRun, ShippingOrderExtractionUnit]: + """在单元异常回滚后重新加载实体,避免继续使用失效会话对象。""" + run = ShippingOrderExtractionRun.query.filter_by(id=run_id).with_for_update().first() + unit = db.session.get(ShippingOrderExtractionUnit, int(unit_id)) + if run is None or unit is None: + raise RuntimeError('order extraction run or unit disappeared during retry handling') + return run, unit + + +def _record_unit_technical_failure(*, run, unit, job, exc: Exception, retryable: bool) -> None: + """将单元异常收敛为稳定技术失败事实,并在可重试时回到 pending。""" + from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit + + error_code = str(getattr(exc, 'code', None) or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED') + transition_order_extraction_unit( + unit, + target_status='failed', + error_code=error_code, + error_message=str(exc), + ) + record_unit_progress( + run=run, + unit=unit, + event_code='technical_failed', + reason_code=error_code, + summary={ + 'retryable': bool(retryable), + 'attempt_count': int(unit.attempt_count or 0), + }, + job_id=job.id, + ) + if retryable and int(unit.attempt_count or 0) < MAX_UNIT_TECHNICAL_ATTEMPTS: + record_unit_progress( + run=run, + unit=unit, + event_code='technical_retrying', + reason_code=error_code, + summary={ + 'next_attempt_count': int(unit.attempt_count or 0) + 1, + 'max_attempt_count': MAX_UNIT_TECHNICAL_ATTEMPTS, + }, + job_id=job.id, + ) + transition_order_extraction_unit(unit, target_status='pending') + + +def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[dict] | None: + """ + 独立处理一个附件单元;技术失败最多自动重试 2 次,不影响其他单元继续执行。 + + Returns: + `list[dict]`: 当前单元产出的订单数组(确定性成功)。 + `None`: 当前单元进入 review_required 或最终技术失败。 + """ + from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit + + while True: + if unit.status == 'failed': + transition_order_extraction_unit(unit, target_status='pending') + if unit.status in {'review_required', 'candidate_ready'}: + return None + transition_order_extraction_unit(unit, target_status='routing') + record_unit_progress(run=run, unit=unit, event_code='document_queued', job_id=job.id) + transition_order_extraction_unit(unit, target_status='matching_profile') + record_unit_progress(run=run, unit=unit, event_code='profile_matching', job_id=job.id) + db.session.commit() + try: + route_result = route_deterministic_unit(run, unit=unit) + _append_route_decision( + run=run, + unit=unit, + job=job, + # 同一 Job 可在单元内多次路由;审计唯一键要求使用单元执行代次。 + attempt_no=int(unit.attempt_count or 1), + route_result=route_result, + ) + if route_result.execution_mode == 'deterministic': + record_unit_progress( + run=run, + unit=unit, + event_code='profile_matched', + summary={ + 'profile_code': route_result.decision.get('selected_profile_code'), + 'profile_version': route_result.decision.get('selected_profile_version'), + }, + job_id=job.id, + ) + db.session.commit() + if route_result.execution_mode != 'deterministic': + transition_order_extraction_unit( + unit, target_status='review_required', + error_code=(route_result.decision.get('fallback_reason_codes') or ['review_required'])[0], + error_message='订单模板路由要求人工处理', + result={ + 'fallback_reason_codes': route_result.decision.get('fallback_reason_codes') or [], + 'review_details': route_result.decision.get('review_details') or [], + }, + ) + record_unit_progress( + run=run, + unit=unit, + event_code='review_required', + reason_code=(route_result.decision.get('fallback_reason_codes') or ['review_required'])[0], + summary={'fallback_reason_codes': route_result.decision.get('fallback_reason_codes') or []}, + job_id=job.id, + ) + db.session.commit() + return None + transition_order_extraction_unit(unit, target_status='extracting') + record_unit_progress(run=run, unit=unit, event_code='table_reconstructed', job_id=job.id) + unit_orders = validate_unit_orders(run, unit=unit, orders=route_result.orders) + record_unit_progress(run=run, unit=unit, event_code='order_fields_extracted', job_id=job.id) + for order in unit_orders: + order['_hxops_intake_id'] = int(unit.intake_id) + unit_orders = _json_safe_order_payload(unit_orders) + transition_order_extraction_unit( + unit, + target_status='merging_supplement', + result={'orders': unit_orders, 'execution': {'mode': 'deterministic'}}, + ) + db.session.commit() + return unit_orders + except Exception as exc: + db.session.rollback() + retryable = not isinstance(exc, AppError) or bool(getattr(exc, 'retryable', False)) + run, unit = _reload_run_and_unit(run_id=int(run.id), unit_id=int(unit.id)) + _record_unit_technical_failure(run=run, unit=unit, job=job, exc=exc, retryable=retryable) + db.session.commit() + if retryable and int(unit.attempt_count or 0) < MAX_UNIT_TECHNICAL_ATTEMPTS: + continue + return None + + @register_handler(JobType.SHIPPING_ORDER_EXTRACTION) def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: """ @@ -114,84 +499,215 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: if run is None: fail_job(job.id, error='order extraction run not found', retryable=False, owned_attempt=owned_attempt) return - if run.status in {'completed', 'needs_review'}: + if run.status in {'completed', 'partially_completed', 'review_required'}: finish_job(job.id, result={'run_no': run.run_no, 'status': run.status, 'idempotent_replay': True}, owned_attempt=owned_attempt) return - if run.status == 'result_persisted': - target = 'needs_review' if (run.result_json or {}).get('requires_review') else 'completed' - transition_order_extraction_run(run, target_status=target) - db.session.commit() - finish_job(job.id, result={'run_no': run.run_no, 'status': run.status}, owned_attempt=owned_attempt) - return - if run.status not in {'queued', 'running'}: + if run.status not in {'queued', 'processing'}: fail_job(job.id, error=f'run status is not executable: {run.status}', retryable=False, owned_attempt=owned_attempt) return started = time.perf_counter() try: if run.status == 'queued': - transition_order_extraction_run(run, target_status='running', phase='deterministic_parsing') - from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan, transition_order_extraction_unit + transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing') + from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit - plan = ensure_order_extraction_plan(run) + plan = materialize_order_extraction_run_inputs(run) + selection = (run.input_snapshot_json or {}).get('attachment_selection') or {} + max_runtime_seconds = max(0, int(selection.get('max_runtime_seconds') or 0)) + runtime_budget_stopped = False run.current_job_id = job.id run.attempt_count = owned_attempt + record_run_progress( + run=run, + event_code='initial_wave_started', + summary={ + **_selection_progress_summary(run), + 'unit_count': int(getattr(plan, 'unit_count', 0) or 0), + 'job_attempt': owned_attempt, + }, + job_id=job.id, + commit=False, + ) db.session.commit() - units = ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id).order_by(ShippingOrderExtractionUnit.position.asc()).all() - orders: list[dict] = [] + unit_orders_by_id: dict[int, list[dict]] = {} + persisted_orders: list[dict] = [] + pending_merge_unit_ids: list[int] = [] + current_batch = 1 + expansion_events_emitted: set[int] = set() - # [STEP 1] 每个文档独立路由,单个歧义不得阻断其他 PDF/PO 的确定性结果。 - for unit in units: - if unit.status == 'succeeded' and isinstance(unit.result_json, dict): - saved_orders = unit.result_json.get('orders') - if isinstance(saved_orders, list): - orders.extend(item for item in saved_orders if isinstance(item, dict)) - continue - if unit.status == 'failed': - transition_order_extraction_unit(unit, target_status='pending') - if unit.status == 'skipped': - continue - transition_order_extraction_unit(unit, target_status='running') - db.session.commit() - route_result = route_deterministic_unit(run, unit=unit) - _append_route_decision(run=run, unit=unit, job=job, attempt_no=owned_attempt, route_result=route_result) - db.session.commit() - if route_result.execution_mode != 'deterministic': - transition_order_extraction_unit( - unit, target_status='skipped', - error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED', - error_message='订单模板路由要求人工处理', + # [STEP 1] 每个文档独立路由;当前批次未完整收敛时,再按冻结计划激活下一批附件。 + while True: + if max_runtime_seconds and time.perf_counter() - started >= max_runtime_seconds: + runtime_budget_stopped = True + record_run_progress( + run=run, event_code='budget_stopped', reason_code='budget_runtime_limit', + summary={'max_runtime_seconds': max_runtime_seconds}, job_id=job.id, ) - db.session.commit() + break + units = _units_for_batch(plan, selection_batch=current_batch) + wave_orders: list[dict] = [] + for unit in units: + # 总时限不能中断正在进行的外部解析,但禁止在到期后启动新的 Unit。 + if max_runtime_seconds and time.perf_counter() - started >= max_runtime_seconds: + runtime_budget_stopped = True + record_run_progress( + run=run, event_code='budget_stopped', reason_code='budget_runtime_limit', + summary={'max_runtime_seconds': max_runtime_seconds}, job_id=job.id, + ) + break + if unit.status == 'candidate_ready' and isinstance(unit.result_json, dict): + saved_orders = unit.result_json.get('orders') + if isinstance(saved_orders, list): + 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)]) + continue + if unit.status == 'review_required': + continue + unit_orders = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=owned_attempt) + db.session.expire_all() + unit = db.session.get(ShippingOrderExtractionUnit, int(unit.id)) + if unit is None or not unit_orders or unit.status != 'merging_supplement': + continue + unit_orders_by_id[int(unit.id)] = unit_orders + pending_merge_unit_ids.append(int(unit.id)) + wave_orders.extend(unit_orders) + if runtime_budget_stopped: + break + wave_orders = _wave_orders_for_expansion(run, orders=wave_orders) + expansion_reason_codes = _expansion_trigger_reason_codes(wave_units=units, wave_orders=wave_orders) + + next_existing_batch = _next_existing_batch(plan, after_batch=current_batch) + if expansion_reason_codes and next_existing_batch is not None: + source_batch = current_batch + current_batch = next_existing_batch + if current_batch not in expansion_events_emitted: + record_run_progress( + run=run, + event_code='expansion_wave_started', + summary={ + **_selection_progress_summary(run), + 'selection_batch': current_batch, + 'unit_count': len(_units_for_batch(plan, selection_batch=current_batch)), + 'triggered_by_batch': source_batch, + 'reason_codes': expansion_reason_codes, + }, + job_id=job.id, + commit=False, + ) + expansion_events_emitted.add(current_batch) + db.session.commit() continue - unit_orders = validate_unit_orders(run, unit=unit, orders=route_result.orders) - for order in unit_orders: - order['_hxops_intake_id'] = int(unit.intake_id) - transition_order_extraction_unit( - unit, target_status='succeeded', - result={'orders': unit_orders, 'execution': {'mode': 'deterministic'}}, - ) - db.session.commit() - orders.extend(unit_orders) + + pending_batches = _pending_snapshot_batches(run, plan) + if expansion_reason_codes and pending_batches: + next_batch = pending_batches[0] + created_units = _activate_expansion_batch(run=run, plan=plan, selection_batch=next_batch) + db.session.flush() + plan = ShippingOrderExtractionPlan.query.filter_by(id=plan.id).first() or plan + if created_units or _units_for_batch(plan, selection_batch=next_batch): + record_run_progress( + run=run, + event_code='expansion_wave_started', + summary={ + **_selection_progress_summary(run), + 'selection_batch': next_batch, + 'unit_count': len(_units_for_batch(plan, selection_batch=next_batch)), + 'triggered_by_batch': current_batch, + 'reason_codes': expansion_reason_codes, + }, + job_id=job.id, + commit=False, + ) + expansion_events_emitted.add(next_batch) + db.session.commit() + current_batch = next_batch + continue + break + + units = ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id).order_by(ShippingOrderExtractionUnit.position.asc()).all() schema_snapshot = run.input_snapshot_json.get('schema') or {} - orders = merge_unit_orders(orders=orders, schema_definition=schema_snapshot.get('definition') or {}) + orders_to_merge = [ + order + for unit_id in pending_merge_unit_ids + for order in unit_orders_by_id.get(unit_id, []) + if isinstance(order, dict) + ] + orders_to_merge = merge_unit_orders(orders=orders_to_merge, schema_definition=schema_snapshot.get('definition') or {}) from app.services.shipping_notice.order_supplement_merge import merge_email_supplements supplements_by_intake = { int(intake.get('intake_id') or 0): supplement for intake in run.input_snapshot_json.get('intakes') or [] if isinstance(intake, dict) for supplement in intake.get('email_supplements') or [] if isinstance(supplement, dict) } - orders = merge_email_supplements( - orders=orders, + merged_orders = merge_email_supplements( + orders=orders_to_merge, supplements_by_intake=supplements_by_intake, schema_definition=schema_snapshot.get('definition') or {}, ) + offset = 0 + for unit in units: + unit_orders = unit_orders_by_id.get(int(unit.id), []) + if unit.status != 'merging_supplement': + continue + count = len(unit_orders) + merged_unit_orders = merged_orders[offset:offset + count] + offset += count + relation_codes = sorted({ + str(order.get('_hxops_email_supplement_relation') or '').strip() + for order in merged_unit_orders + if isinstance(order, dict) and str(order.get('_hxops_email_supplement_relation') or '').strip() + }) + conflict_count = sum( + 1 + for order in merged_unit_orders if isinstance(order, dict) + for conflict in order.get('conflicts') or [] if isinstance(conflict, dict) + if str(conflict.get('reason') or '').strip() == 'supplement_relation_ambiguous' + ) + supplement_status = ( + 'conflict' + if conflict_count > 0 + else 'merged' + if relation_codes + else 'none' + ) + record_unit_progress( + run=run, + unit=unit, + event_code='email_supplement_merged', + summary={ + 'status': supplement_status, + 'relation_codes': relation_codes, + 'conflict_count': conflict_count, + }, + reason_code='email_supplement_ambiguous' if conflict_count > 0 else None, + job_id=job.id, + ) + transition_order_extraction_unit( + unit, + target_status='candidate_ready', + result={'orders': merged_unit_orders, 'execution': {'mode': 'deterministic'}}, + ) + record_unit_progress( + run=run, + unit=unit, + event_code='candidate_ready', + summary={ + 'order_count': len(merged_unit_orders), + 'email_supplement_status': supplement_status, + 'email_supplement_relation_codes': relation_codes, + 'email_supplement_conflict_count': conflict_count, + }, + job_id=job.id, + ) + orders = persisted_orders + merged_orders execution = { 'mode': 'deterministic', 'unit_count': len(units), - 'deterministic_unit_count': sum(1 for unit in units if unit.status == 'succeeded'), - 'review_required_unit_count': sum(1 for unit in units if unit.status == 'skipped'), + 'deterministic_unit_count': sum(1 for unit in units if unit.status == 'candidate_ready'), + 'review_required_unit_count': sum(1 for unit in units if unit.status == 'review_required'), 'failed_unit_count': sum(1 for unit in units if unit.status == 'failed'), 'duration_ms': int((time.perf_counter() - started) * 1000), } @@ -202,7 +718,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: # [STEP 2] Candidate 写入与解析执行分离;落库失败可重试,已完成 Unit 不重复解析。 mark_order_extraction_persistence_started(run) result = submit_order_extraction_run_result(run=run, orders=orders) - requires_review = _result_requires_review(units=units, result=result) + requires_review = runtime_budget_stopped or _result_requires_review(units=units, result=result) summary = { 'run_no': run.run_no, 'batch_no': result.get('batch_no'), 'created_count': int(result.get('created_count') or 0), @@ -211,20 +727,45 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: 'non_shipping_count': int(result.get('non_shipping_count') or 0), 'execution': execution, 'requires_review': requires_review, } - transition_order_extraction_run(run, target_status='result_persisted', phase='result_persisted', result=summary) - db.session.commit() - final_status = 'needs_review' if requires_review else 'completed' + final_status = ( + 'failed' + if execution['deterministic_unit_count'] == 0 and execution['failed_unit_count'] > 0 and execution['review_required_unit_count'] == 0 + else 'review_required' + if execution['deterministic_unit_count'] == 0 and execution['review_required_unit_count'] > 0 and execution['failed_unit_count'] == 0 + else 'partially_completed' + if requires_review + else 'completed' + ) + selection_summary = _selection_progress_summary(run) + if selection_summary['budget_limited_attachment_count'] > 0 and final_status != 'completed': + budget_stop_reason_codes = _expansion_trigger_reason_codes( + wave_units=units, + wave_orders=_mark_expandable_business_gaps(run, orders=merged_orders), + ) + record_run_progress( + run=run, + event_code='budget_stopped', + summary={ + **selection_summary, + 'execution': execution, + 'requires_review': requires_review, + 'reason_codes': budget_stop_reason_codes, + }, + reason_code='budget_initial_limit', + job_id=job.id, + ) transition_order_extraction_run(run, target_status=final_status, result=summary) + record_run_progress(run=run, event_code='run_completed', summary=summary, job_id=job.id) db.session.commit() finish_job(job.id, result=summary, message='订单抽取完成', owned_attempt=owned_attempt) except Exception as exc: db.session.rollback() run = ShippingOrderExtractionRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first() retryable = not isinstance(exc, AppError) or bool(getattr(exc, 'retryable', False)) - if run is not None and run.status in {'queued', 'running', 'failed'}: + if run is not None and run.status in {'queued', 'processing', 'failed'}: running_unit = ShippingOrderExtractionUnit.query.join(ShippingOrderExtractionPlan).filter( ShippingOrderExtractionPlan.run_id == run.id, - ShippingOrderExtractionUnit.status == 'running', + ShippingOrderExtractionUnit.status.in_(['routing', 'matching_profile', 'extracting', 'merging_supplement']), ).first() if running_unit is not None: from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit @@ -234,12 +775,27 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: error_code=str(getattr(exc, 'code', None) or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED'), error_message=str(exc), ) + record_unit_progress( + run=run, + unit=running_unit, + event_code='technical_failed', + reason_code=str(getattr(exc, 'code', None) or 'technical_failure'), + job_id=job.id, + ) if retryable and owned_attempt < int(job.max_attempts or 1): - if run.status == 'running': + if run.status == 'processing': + if running_unit is not None: + record_unit_progress( + run=run, + unit=running_unit, + event_code='technical_retrying', + reason_code=str(getattr(exc, 'code', None) or 'technical_failure'), + job_id=job.id, + ) transition_order_extraction_run(run, target_status='queued', phase='retry_queued') - elif run.status in {'queued', 'running'}: + elif run.status in {'queued', 'processing'}: if run.status == 'queued': - transition_order_extraction_run(run, target_status='running', phase='failing') + transition_order_extraction_run(run, target_status='processing', phase='failing') transition_order_extraction_run( run, target_status='failed', error_code=str(getattr(exc, 'code', None) or 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED'), diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index bec4c648..25981e58 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -7,7 +7,6 @@ backend/app/models/__init__.py """ from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest -from app.models.agent_runtime_binding import AgentRuntimeBinding from app.models.base import Base, user_agent_permissions from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage @@ -132,7 +131,6 @@ __all__ = [ 'UserDefaultAgent', 'User', 'Agent', - 'AgentRuntimeBinding', 'ChatSession', 'ChatLog', 'ChatToolRun', diff --git a/backend/app/models/agent.py b/backend/app/models/agent.py index 33815da7..9010ba89 100644 --- a/backend/app/models/agent.py +++ b/backend/app/models/agent.py @@ -11,7 +11,7 @@ from __future__ import annotations from datetime import datetime from typing import List, Optional -from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Integer, Index, JSON, String, Text, UniqueConstraint, text +from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, Index, JSON, String, Text, UniqueConstraint, text from sqlalchemy.orm import Mapped, mapped_column, relationship from app.models.base import Base, user_agent_permissions @@ -26,10 +26,6 @@ class Agent(Base): __tablename__ = 'agents' __table_args__ = ( - CheckConstraint( - "exposure_mode IN ('workspace', 'internal')", - name='ck_agents_exposure_mode', - ), Index('uq_agents_one_active_shipping_notice', 'agent_code', unique=True, postgresql_where=text("agent_code = 'shipping_notice' AND is_active = true"), sqlite_where=text("agent_code = 'shipping_notice' AND is_active = 1")), @@ -53,7 +49,6 @@ class Agent(Base): runtime_provider: Mapped[str] = mapped_column(String(32), default='dify', nullable=False) conversation_mode: Mapped[str] = mapped_column(String(32), default='chat', nullable=False) dify_app_type: Mapped[str] = mapped_column(String(20), default='chatflow', nullable=False) - exposure_mode: Mapped[str] = mapped_column(String(20), default='workspace', nullable=False) iframe_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) category: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) sub_category: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) diff --git a/backend/app/models/agent_runtime_binding.py b/backend/app/models/agent_runtime_binding.py deleted file mode 100644 index d8b772c4..00000000 --- a/backend/app/models/agent_runtime_binding.py +++ /dev/null @@ -1,45 +0,0 @@ -""" -backend/app/models/agent_runtime_binding.py - -用途:定义用户入口 Agent 到内部运行能力 Provider 的显式绑定。 -依赖:agents 表。 -逻辑:业务代码按 owner_agent_id + capability_code 解析 Provider;执行策略仅保存通用超时与重试参数。 -""" - -from __future__ import annotations - -from datetime import datetime -from typing import Any, Optional - -from sqlalchemy import Boolean, ForeignKey, JSON, String, UniqueConstraint -from sqlalchemy.orm import Mapped, mapped_column, relationship - -from app.models.base import Base - - -class AgentRuntimeBinding(Base): - """一个 Agent 的命名运行能力绑定;同一能力只允许一个当前 Provider。""" - - __tablename__ = 'agent_runtime_bindings' - __table_args__ = ( - UniqueConstraint('owner_agent_id', 'capability_code', name='uq_agent_runtime_binding_capability'), - ) - - id: Mapped[int] = mapped_column(primary_key=True) - owner_agent_id: Mapped[int] = mapped_column( - ForeignKey('agents.id', ondelete='CASCADE'), nullable=False, index=True, - ) - capability_code: Mapped[str] = mapped_column(String(100), nullable=False, index=True) - provider_agent_id: Mapped[int] = mapped_column( - ForeignKey('agents.id'), nullable=False, index=True, - ) - enabled: Mapped[bool] = mapped_column(Boolean, default=True, server_default='1', nullable=False) - quality_batch_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_order_extraction_quality_batches.id'), nullable=True, index=True, - ) - config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) - created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False) - updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) - - owner_agent: Mapped['Agent'] = relationship('Agent', foreign_keys=[owner_agent_id]) - provider_agent: Mapped['Agent'] = relationship('Agent', foreign_keys=[provider_agent_id]) diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index 5a8aa3a2..1fe80855 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -14,6 +14,7 @@ backend/app/models/shipping.py from __future__ import annotations +import uuid from datetime import datetime from typing import List, Optional @@ -434,6 +435,7 @@ class ShippingNoticeIntake(Base): name='uq_shipping_notice_intakes_asset_purpose_parser', ), Index('ix_shipping_notice_intakes_user_conversation_created', 'user_id', 'conversation_id', 'created_at'), + Index('ix_shipping_notice_intakes_user_upload_batch_created', 'user_id', 'upload_batch_id', 'created_at'), Index('ix_shipping_notice_intakes_parse_status_created', 'parse_status', 'created_at'), Index('ix_shipping_notice_intakes_expires', 'expires_at'), Index('ix_shipping_notice_intakes_user_business_fingerprint', 'user_id', 'business_fingerprint'), @@ -447,6 +449,8 @@ class ShippingNoticeIntake(Base): asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=False) user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True, nullable=False) conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) + # 同一输入框一次选取的上传批次;发送端只能冻结同一批次的 Intake。 + upload_batch_id: Mapped[str] = mapped_column(String(36), nullable=False, default=lambda: str(uuid.uuid4())) purpose: Mapped[str] = mapped_column(String(32), default='shipping_notice', nullable=False) parse_status: Mapped[str] = mapped_column(String(32), default='created', nullable=False, index=True) order_extraction_status: Mapped[str] = mapped_column( diff --git a/backend/app/models/shipping_document_profile_auto_freeze.py b/backend/app/models/shipping_document_profile_auto_freeze.py index a7a24a18..305f543f 100644 --- a/backend/app/models/shipping_document_profile_auto_freeze.py +++ b/backend/app/models/shipping_document_profile_auto_freeze.py @@ -11,7 +11,7 @@ from __future__ import annotations from datetime import datetime from typing import Optional -from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint +from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, text, UniqueConstraint from sqlalchemy.orm import Mapped, mapped_column from app.models.base import Base @@ -45,6 +45,13 @@ class ShippingDocumentProfileAutoFreezeQualification(Base): quality_suite_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_document_profile_test_suites.id'), nullable=True, ) + customer_ids_json: Mapped[Optional[list[int]]] = mapped_column(JSON, nullable=True) + business_scenarios_json: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True) + requires_customer_confirmation: Mapped[bool] = mapped_column( + Boolean, nullable=False, default=True, server_default=text('true'), + ) + scope_updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + scope_updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) status: Mapped[str] = mapped_column( String(32), nullable=False, default='manual_confirmation', server_default='manual_confirmation', ) diff --git a/backend/app/models/shipping_order_extraction_run.py b/backend/app/models/shipping_order_extraction_run.py index 4419c92b..97763ced 100644 --- a/backend/app/models/shipping_order_extraction_run.py +++ b/backend/app/models/shipping_order_extraction_run.py @@ -37,8 +37,8 @@ class ShippingOrderExtractionRun(Base): UniqueConstraint('run_no', name='uq_shipping_order_extraction_runs_no'), UniqueConstraint('idempotency_key', name='uq_shipping_order_extraction_runs_idempotency'), CheckConstraint( - "status IN ('queued', 'running', 'result_persisted', 'completed', " - "'needs_review', 'failed', 'cancelled')", + "status IN ('queued', 'processing', 'completed', " + "'partially_completed', 'review_required', 'failed', 'cancelled')", name='ck_shipping_order_extraction_runs_status', ), Index('ix_shipping_order_extraction_runs_user_created', 'user_id', 'created_at'), @@ -50,8 +50,8 @@ class ShippingOrderExtractionRun(Base): 'owner_agent_id', 'conversation_id', unique=True, - postgresql_where=text("status IN ('queued', 'running', 'result_persisted')"), - sqlite_where=text("status IN ('queued', 'running', 'result_persisted')"), + postgresql_where=text("status IN ('queued', 'processing')"), + sqlite_where=text("status IN ('queued', 'processing')"), ), ) @@ -76,6 +76,9 @@ class ShippingOrderExtractionRun(Base): schema_version_id: Mapped[int] = mapped_column( ForeignKey('shipping_order_schema_versions.id'), nullable=False, ) + # 请求快照是发送时的审计与幂等锚点;Worker 后续可物化 input_snapshot_* 作为执行快照。 + request_snapshot_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + request_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False) input_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False) idempotency_key: Mapped[str] = mapped_column(String(64), nullable=False) @@ -189,7 +192,7 @@ class ShippingOrderExtractionPlan(Base): class ShippingOrderExtractionUnit(Base): - """计划内单个冻结文档抽取单元;状态、结果和错误相互隔离。""" + """计划内单个冻结附件抽取单元;状态、选择事实和错误相互隔离。""" __tablename__ = 'shipping_order_extraction_units' __table_args__ = ( @@ -200,7 +203,8 @@ class ShippingOrderExtractionUnit(Base): name='ck_shipping_order_extraction_units_type', ), CheckConstraint( - "status IN ('pending', 'running', 'succeeded', 'failed', 'skipped')", + "status IN ('pending', 'routing', 'matching_profile', 'extracting', " + "'merging_supplement', 'candidate_ready', 'review_required', 'failed', 'cancelled')", name='ck_shipping_order_extraction_units_status', ), ForeignKeyConstraint( @@ -222,11 +226,20 @@ class ShippingOrderExtractionUnit(Base): unit_type: Mapped[str] = mapped_column(String(32), nullable=False) document_type: Mapped[str] = mapped_column(String(32), nullable=False) content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + selection_batch: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + selection_reason_codes_json: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True) + group_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + budget_cost_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + retry_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + technical_failure_reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending') attempt_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0') + reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + last_activity_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) @@ -286,29 +299,31 @@ class ShippingOrderExtractionRouteDecision(Base): class ShippingOrderExtractionProgressEvent(Base): - """订单抽取的脱敏进度明细;事件幂等键抵御 SSE 断线重放。""" + """订单抽取的可恢复业务事件;用户态与管理员态通过 visibility 隔离。""" __tablename__ = 'shipping_order_extraction_progress_events' __table_args__ = ( UniqueConstraint('idempotency_key', name='uq_shipping_order_extraction_progress_event_key'), - Index('ix_shipping_order_extraction_progress_events_run_created', 'run_id', 'created_at'), + UniqueConstraint('run_id', 'sequence_no', name='uq_shipping_order_extraction_progress_event_sequence'), + Index('ix_shipping_order_extraction_progress_events_run_sequence', 'run_id', 'sequence_no'), Index('ix_shipping_order_extraction_progress_events_expires_id', 'expires_at', 'id'), - Index('ix_shipping_order_extraction_progress_events_workflow_node', 'workflow_run_id', 'node_execution_id'), + Index('ix_shipping_order_extraction_progress_events_run_visibility', 'run_id', 'visibility', 'sequence_no'), ) id: Mapped[int] = mapped_column(primary_key=True) run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'), nullable=False) + unit_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_extraction_units.id', ondelete='CASCADE'), nullable=True) + document_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True) attempt_count: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) - workflow_run_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) - node_execution_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) - event_type: Mapped[str] = mapped_column(String(64), nullable=False) - node_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - stage_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - event_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - provider_occurred_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + sequence_no: Mapped[int] = mapped_column(Integer, nullable=False) + visibility: Mapped[str] = mapped_column(String(32), nullable=False, default='workspace', server_default='workspace') + event_code: Mapped[str] = mapped_column(String(64), nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='completed', server_default='completed') + occurred_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) received_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) - details_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False) mapping_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) diff --git a/backend/app/services/admin/agent_service.py b/backend/app/services/admin/agent_service.py index 3a796568..94984ecc 100644 --- a/backend/app/services/admin/agent_service.py +++ b/backend/app/services/admin/agent_service.py @@ -14,8 +14,8 @@ import requests from app import db from app.core.config.settings import Config -from app.core.errors import ConflictError, NotFoundError, ValidationError -from app.models import Agent, AgentRuntimeBinding, ShippingOrderExtractionRun, User +from app.core.errors import NotFoundError, ValidationError +from app.models import Agent, User from app.services.agent_directory import normalize_directory_member_ids, replace_directory_members from app.services.admin.training_exam_pdf_service import parse_training_question_bank_from_guide from app.services.agent_registry.admin_payload import apply_agent_payload, validate_agent_payload @@ -29,20 +29,9 @@ def serialize_agent(agent: Agent) -> dict: return serialize_agent_for_admin(agent) -def list_agents(*, scope: str | None = None) -> list[dict]: - """按管理域返回 Agent;scope=applications/executors,缺省返回全部兼容旧客户端。""" - query = db.session.query(Agent) - if scope == 'applications': - query = query.filter(Agent.exposure_mode == 'workspace') - elif scope == 'executors': - query = query.filter(Agent.exposure_mode == 'internal') - elif scope not in (None, ''): - raise ValidationError( - 'Invalid agent management scope', - code='AGENT.ADMIN_SCOPE_INVALID', - details={'scope': scope}, - ) - agents = query.order_by(Agent.id.asc()).all() +def list_agents() -> list[dict]: + """返回全部 Agent(按 id 升序)。""" + agents = db.session.query(Agent).order_by(Agent.id.asc()).all() return [serialize_agent(a) for a in agents] @@ -71,24 +60,6 @@ def create_agent(data: dict[str, Any]) -> dict: db.session.flush() member_ids = data.get('directory_member_ids') if agent.is_aggregate else [] replace_directory_members(agent, normalize_directory_member_ids(member_ids, directory_agent_id=agent.id)) - runtime_binding = data.get('order_extraction_runtime_binding') - if runtime_binding is not None: - if not isinstance(runtime_binding, dict): - raise ValidationError('order_extraction_runtime_binding 必须为 JSON 对象') - try: - provider_agent_id = int(runtime_binding.get('provider_agent_id')) - except (TypeError, ValueError) as exc: - raise ValidationError('provider_agent_id is required') from exc - from app.services.agent_runtime_binding_service import save_runtime_binding - - save_runtime_binding( - owner_agent_id=agent.id, - capability_code='shipping.order_extraction', - provider_agent_id=provider_agent_id, - enabled=runtime_binding.get('enabled') is not False, - config=runtime_binding.get('config'), - commit=False, - ) db.session.commit() return {'id': agent.id} @@ -115,7 +86,6 @@ def update_agent(agent_id: int, data: dict[str, Any]) -> None: 'runtime_provider': data.get('runtime_provider', agent.runtime_provider), 'conversation_mode': data.get('conversation_mode', agent.conversation_mode), 'dify_app_type': data.get('dify_app_type', agent.dify_app_type), - 'exposure_mode': data.get('exposure_mode', agent.exposure_mode), 'iframe_url': data.get('iframe_url', agent.iframe_url), 'category': data.get('category', agent.category), 'sub_category': data.get('sub_category', agent.sub_category), @@ -138,44 +108,13 @@ def update_agent(agent_id: int, data: dict[str, Any]) -> None: if 'directory_member_ids' in data or 'is_aggregate' in data: member_ids = data.get('directory_member_ids') if agent.is_aggregate else [] replace_directory_members(agent, normalize_directory_member_ids(member_ids, directory_agent_id=agent.id)) - runtime_binding = data.get('order_extraction_runtime_binding') - if runtime_binding is not None: - if not isinstance(runtime_binding, dict): - raise ValidationError('order_extraction_runtime_binding 必须为 JSON 对象') - try: - provider_agent_id = int(runtime_binding.get('provider_agent_id')) - except (TypeError, ValueError) as exc: - raise ValidationError('provider_agent_id is required') from exc - from app.services.agent_runtime_binding_service import save_runtime_binding - - save_runtime_binding( - owner_agent_id=agent.id, - capability_code='shipping.order_extraction', - provider_agent_id=provider_agent_id, - enabled=runtime_binding.get('enabled') is not False, - config=runtime_binding.get('config'), - commit=False, - ) db.session.commit() def delete_agent(agent_id: int) -> None: - """删除 Agent;被能力绑定或历史订单抽取 Run 引用时明确阻断。""" + """删除 Agent(不存在时静默成功)。""" agent = db.session.get(Agent, agent_id) if agent: - binding_count = AgentRuntimeBinding.query.filter( - (AgentRuntimeBinding.owner_agent_id == agent.id) - | (AgentRuntimeBinding.provider_agent_id == agent.id) - ).count() - run_count = ShippingOrderExtractionRun.query.filter( - (ShippingOrderExtractionRun.owner_agent_id == agent.id) - ).count() - if binding_count or run_count: - raise ConflictError( - 'Agent is referenced by runtime capability history', - code='AGENT.RUNTIME_PROVIDER_DELETE_BLOCKED', - details={'binding_count': binding_count, 'run_count': run_count}, - ) db.session.delete(agent) db.session.commit() @@ -356,11 +295,6 @@ def update_agent_permissions(agent_id: int, user_ids: list[int]) -> None: agent = db.session.get(Agent, agent_id) if not agent: raise NotFoundError('Not found') - if agent.exposure_mode == 'internal' and user_ids: - raise ValidationError( - '内部执行器不可授予用户权限', - code='AGENT.INTERNAL_EXECUTOR_PERMISSION_FORBIDDEN', - ) current_users = db.session.query(User).filter(User.agents.contains(agent)).all() current_user_ids = {u.id for u in current_users} new_user_ids = set(user_ids) diff --git a/backend/app/services/admin/dashboard_service.py b/backend/app/services/admin/dashboard_service.py index 52e71657..1066c310 100644 --- a/backend/app/services/admin/dashboard_service.py +++ b/backend/app/services/admin/dashboard_service.py @@ -20,12 +20,7 @@ def compute_dashboard_summary() -> dict: agent_count、user_count、total_conversations、avg_score。 """ total_users = db.session.query(func.count(User.id)).scalar() or 0 - active_agents = ( - db.session.query(func.count(Agent.id)) - .filter(Agent.is_active.is_(True), Agent.exposure_mode == 'workspace') - .scalar() - or 0 - ) + active_agents = db.session.query(func.count(Agent.id)).filter_by(is_active=True).scalar() or 0 total_conversations = db.session.query(func.count(ChatLog.id)).scalar() or 0 avg_score = db.session.query(func.avg(Feedback.score)).scalar() avg_score = round(float(avg_score), 1) if avg_score else 0.0 @@ -44,13 +39,7 @@ def compute_dashboard_badges() -> dict: pending_approvals、pending_requests。 """ pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar() or 0 - pending_requests = ( - db.session.query(func.count(PermissionRequest.id)) - .join(Agent, Agent.id == PermissionRequest.agent_id) - .filter(PermissionRequest.status == 'pending', Agent.exposure_mode == 'workspace') - .scalar() - or 0 - ) + pending_requests = db.session.query(func.count(PermissionRequest.id)).filter_by(status='pending').scalar() or 0 return { 'pending_approvals': pending_approvals, 'pending_requests': pending_requests, diff --git a/backend/app/services/admin/faq_service.py b/backend/app/services/admin/faq_service.py index 766e5538..d6f243de 100644 --- a/backend/app/services/admin/faq_service.py +++ b/backend/app/services/admin/faq_service.py @@ -13,7 +13,6 @@ from typing import Any from app import db from app.core.errors import NotFoundError, ValidationError from app.models import Agent, KbDocument, QuickQuestion -from app.services.agent_user_access import is_user_application, require_user_application def parse_aliases(raw_aliases) -> list[str]: @@ -83,7 +82,6 @@ def apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answe if 'question' in data: qq.question = str(data['question']).strip() if 'agent_id' in data: - require_user_application(db.session.get(Agent, data['agent_id'])) qq.agent_id = data['agent_id'] if 'sort_order' in data: qq.sort_order = data.get('sort_order', 0) @@ -124,8 +122,6 @@ def list_quick_questions(*, stale_only: bool = False) -> list[dict]: rows = [] for q in query.all(): agent = db.session.get(Agent, q.agent_id) - if not is_user_application(agent): - continue stale_doc = db.session.get(KbDocument, q.stale_kb_document_id) if q.stale_kb_document_id else None rows.append(serialize_quick_question(q, agent.name if agent else 'Unknown', stale_doc)) return rows @@ -168,8 +164,6 @@ def list_faq_candidates(*, agent_id: int | None = None) -> dict: from app.services.hot_faq_aggregator import HotFaqAggregator from app.services.hot_faq_candidate_store import HotFaqCandidateStore - if agent_id is not None: - require_user_application(db.session.get(Agent, agent_id)) items = HotFaqCandidateStore.list_candidates(agent_id) return { 'items': items, @@ -182,8 +176,6 @@ def refresh_faq_candidates(*, agent_id: int | None, dry_run: bool) -> dict: """手动触发离线热点聚合。""" from app.services.hot_faq_aggregator import HotFaqAggregator - if agent_id is not None: - require_user_application(db.session.get(Agent, agent_id)) return HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run) @@ -197,8 +189,6 @@ def promote_faq_candidate(data: dict[str, Any]) -> dict: q_norm = normalize_faq_query(str(data.get('q_norm') or '')) if not agent_id or not q_norm: raise ValidationError('agent_id and q_norm are required') - require_user_application(db.session.get(Agent, agent_id)) - candidate = HotFaqCandidateStore.get_candidate(int(agent_id), q_norm) if not candidate: raise NotFoundError('FAQ candidate not found') @@ -242,6 +232,5 @@ def dismiss_faq_candidate(*, agent_id: int, q_norm: str) -> dict: normalized = normalize_faq_query(q_norm) if not agent_id or not normalized: raise ValidationError('agent_id and q_norm are required') - require_user_application(db.session.get(Agent, agent_id)) HotFaqCandidateStore.dismiss(int(agent_id), normalized) return {'status': 'ok'} diff --git a/backend/app/services/admin/permission_service.py b/backend/app/services/admin/permission_service.py index e82afb94..37daaf24 100644 --- a/backend/app/services/admin/permission_service.py +++ b/backend/app/services/admin/permission_service.py @@ -13,7 +13,6 @@ from typing import Any from app import db from app.core.errors import NotFoundError, ValidationError from app.models import Agent, PermissionRequest, User -from app.services.agent_user_access import load_grantable_agents, require_user_application from app.services.wecom_notify import send_wecom_event_message _BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'} @@ -33,7 +32,7 @@ def serialize_permission_request(req: PermissionRequest) -> dict: def _load_users_and_agents(user_ids: list[Any], agent_ids: list[Any]) -> tuple[list[User], list[Agent]]: users = db.session.query(User).filter(User.id.in_(user_ids)).all() - agents = load_grantable_agents(agent_ids) + agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all() return users, agents @@ -105,18 +104,16 @@ def update_user_permissions(user_id: int, data: dict[str, Any]) -> dict: if not user: raise NotFoundError('Not found') agent_ids = data.get('agent_ids', []) - agents = load_grantable_agents(agent_ids) + agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all() user.agents = agents db.session.commit() return {'status': 'ok'} def list_permission_requests() -> list[dict]: - """返回 workspace 应用的权限申请;内部执行器申请仅保留数据库审计。""" + """返回全部权限申请(按 created_at 降序)。""" reqs = ( db.session.query(PermissionRequest) - .join(Agent, Agent.id == PermissionRequest.agent_id) - .filter(Agent.exposure_mode == 'workspace') .order_by(PermissionRequest.created_at.desc()) .all() ) @@ -135,9 +132,6 @@ def approve_permission_request(request_id: int) -> dict: user = db.session.get(User, req.user_id) agent = db.session.get(Agent, req.agent_id) - if not user: - raise NotFoundError('User not found') - require_user_application(agent) req.status = 'approved' req.reviewed_at = datetime.utcnow() if user and agent and (agent not in user.agents): diff --git a/backend/app/services/admin/report_service.py b/backend/app/services/admin/report_service.py index 5521c296..67d4083e 100644 --- a/backend/app/services/admin/report_service.py +++ b/backend/app/services/admin/report_service.py @@ -286,7 +286,6 @@ def build_application_report( .outerjoin(auth_stats, auth_stats.c.agent_id == Agent.id) .outerjoin(pending_stats, pending_stats.c.agent_id == Agent.id) .outerjoin(feedback_stats, feedback_stats.c.agent_id == Agent.id) - .filter(Agent.exposure_mode == 'workspace') ) if status_key == 'active': query = query.filter(Agent.is_active.is_(True)) diff --git a/backend/app/services/admin/user_service.py b/backend/app/services/admin/user_service.py index 42e0b723..adf76008 100644 --- a/backend/app/services/admin/user_service.py +++ b/backend/app/services/admin/user_service.py @@ -16,7 +16,6 @@ from sqlalchemy.orm import joinedload from app import db from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError from app.models import Agent, User -from app.services.agent_user_access import is_user_application, load_grantable_agents from app.services.auth import casdoor_service from app.services.user_admin import delete_admin_users @@ -81,7 +80,7 @@ def serialize_admin_user(user: User) -> dict: 'employee_id': user.employee_id, 'phone_number': user.phone_number, 'feature_permissions': user.get_feature_permissions(), - 'agent_ids': [agent.id for agent in user.agents if is_user_application(agent)], + 'agent_ids': [agent.id for agent in user.agents], } @@ -210,7 +209,7 @@ def create_user(data: dict[str, Any]) -> dict: db.session.add(user) try: if data.get('agent_ids'): - agents = load_grantable_agents(data['agent_ids']) + agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all() user.agents = agents casdoor_service.sync_create_user( username=user.username, @@ -262,7 +261,7 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict: if new_password: user.set_password(new_password) if 'agent_ids' in data: - agents = load_grantable_agents(data['agent_ids']) + agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all() user.agents = agents if new_password: casdoor_service.sync_update_user(user, new_password=new_password) diff --git a/backend/app/services/admin/wecom_admin_service.py b/backend/app/services/admin/wecom_admin_service.py index 1f1f8b09..0a0d701b 100644 --- a/backend/app/services/admin/wecom_admin_service.py +++ b/backend/app/services/admin/wecom_admin_service.py @@ -20,7 +20,6 @@ from app import db from app.core.config.env_persistence import persist_env_settings from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError from app.models import Agent, LoginAudit, User, WecomNotifyAudit -from app.services.agent_user_access import load_grantable_agents from app.services.auth import wecom_auth_service from app.services.oa_wecom_sync import sync_wecom_userids_from_oa @@ -314,11 +313,10 @@ def provision_user(data: dict[str, Any]) -> tuple[dict, int]: except (TypeError, ValueError): db.session.rollback() raise ValidationError('agent_ids must be integer array') - try: - agents = load_grantable_agents(unique_ids) - except ValidationError: + agents = db.session.query(Agent).filter(Agent.id.in_(unique_ids)).all() + if len(agents) != len(unique_ids): db.session.rollback() - raise + raise ValidationError('Some agent_ids are invalid') user.agents = agents else: user.agents = [] diff --git a/backend/app/services/agent_registry/__init__.py b/backend/app/services/agent_registry/__init__.py index 6e33705f..5a9abc17 100644 --- a/backend/app/services/agent_registry/__init__.py +++ b/backend/app/services/agent_registry/__init__.py @@ -17,7 +17,6 @@ from app.services.agent_registry.resolver import ( normalize_capabilities, resolve_agent_code, resolve_conversation_mode, - resolve_effective_role, resolve_capabilities, resolve_handler, resolve_handler_for_agent_code, @@ -34,7 +33,6 @@ __all__ = [ 'normalize_capabilities', 'resolve_agent_code', 'resolve_conversation_mode', - 'resolve_effective_role', 'resolve_capabilities', 'resolve_handler', 'resolve_handler_for_agent_code', diff --git a/backend/app/services/agent_registry/admin_payload.py b/backend/app/services/agent_registry/admin_payload.py index 48525403..45ee1a4d 100644 --- a/backend/app/services/agent_registry/admin_payload.py +++ b/backend/app/services/agent_registry/admin_payload.py @@ -35,7 +35,6 @@ MIGRATED_EXTRA_REGISTRY_KEYS = frozenset({ 'runtime_provider', 'conversation_mode', 'dify_app_type', - 'exposure_mode', 'iframe_url', 'category', 'sub_category', @@ -151,7 +150,6 @@ def validate_agent_payload( valid_runtime_providers = get_platform_enum_set('runtime_providers') valid_conversation_modes = get_platform_enum_set('conversation_modes') valid_dify_app_types = get_platform_enum_set('dify_app_types') - valid_exposure_modes = get_platform_enum_set('exposure_modes') valid_suggested_styles = get_platform_enum_set('suggested_questions_styles') dify_required_providers = get_dify_required_providers() @@ -177,26 +175,6 @@ def validate_agent_payload( if dify_app_type not in valid_dify_app_types: dify_app_type = 'chatflow' - exposure_mode = _strip(data.get('exposure_mode')) or ( - getattr(agent, 'exposure_mode', None) if agent else 'workspace' - ) or 'workspace' - if exposure_mode not in valid_exposure_modes: - raise ValidationError(f'无效的 exposure_mode: {exposure_mode}') - - existing_exposure = _strip(getattr(agent, 'exposure_mode', None) if agent else '') - if agent is not None and existing_exposure and exposure_mode != existing_exposure: - raise ValidationError( - '应用与内部执行器不可互相转换', - code='AGENT.EXPOSURE_ROLE_IMMUTABLE', - ) - # 新建内部执行器统一使用 Dify Workflow;历史内部记录保留原组合以兼容旧数据。 - if exposure_mode == 'internal' and agent is None: - if runtime_provider != 'dify' or dify_app_type != 'workflow': - raise ValidationError( - '新建内部执行器必须使用 runtime_provider=dify 与 dify_app_type=workflow', - code='AGENT.INTERNAL_EXECUTOR_CONFIG_INVALID', - ) - dify_app_id = _strip(data.get('dify_app_id')) or (agent.dify_app_id if agent else '') if runtime_provider in dify_required_providers and not dify_app_id: raise ValidationError('runtime_provider 含 dify 时 dify_app_id 必填') @@ -282,7 +260,6 @@ def validate_agent_payload( 'runtime_provider': runtime_provider, 'conversation_mode': conversation_mode, 'dify_app_type': dify_app_type, - 'exposure_mode': exposure_mode, 'iframe_url': iframe_url or None, 'category': _strip(data.get('category')) or None, 'sub_category': _strip(data.get('sub_category')) or None, @@ -308,7 +285,7 @@ def apply_agent_payload(agent: Agent, normalized: dict[str, Any]) -> None: """ column_fields = ( 'name', 'description', 'icon_url', 'is_active', 'is_aggregate', 'dify_app_id', 'api_base_url', 'type', - 'agent_code', 'runtime_provider', 'conversation_mode', 'dify_app_type', 'exposure_mode', 'iframe_url', + 'agent_code', 'runtime_provider', 'conversation_mode', 'dify_app_type', 'iframe_url', 'category', 'sub_category', 'sort_order', 'welcome_message', 'suggested_questions_style', 'suggested_questions', 'capabilities', 'file_upload_policy', 'bound_schedule_task_id', 'handler_config', diff --git a/backend/app/services/agent_registry/admin_schema.py b/backend/app/services/agent_registry/admin_schema.py index c8964fc6..90c1722d 100644 --- a/backend/app/services/agent_registry/admin_schema.py +++ b/backend/app/services/agent_registry/admin_schema.py @@ -46,7 +46,6 @@ def build_agent_registry_schema() -> dict[str, Any]: 'forced_capabilities': dict(entry.get('forced_capabilities') or {}), 'progress_contract': deepcopy_schema(entry.get('progress_contract')), 'default_intent_routes': list(entry.get('default_intent_routes') or []), - 'required_runtime_capabilities': deepcopy_schema(entry.get('required_runtime_capabilities')), }) return { @@ -54,7 +53,6 @@ def build_agent_registry_schema() -> dict[str, Any]: 'runtime_providers': list(platform.get('runtime_providers') or []), 'conversation_modes': list(platform.get('conversation_modes') or []), 'dify_app_types': list(platform.get('dify_app_types') or []), - 'exposure_modes': list(platform.get('exposure_modes') or []), 'suggested_questions_styles': list(platform.get('suggested_questions_styles') or []), 'default_capabilities': get_default_capabilities(), 'tool_run_progress_defaults': get_tool_run_progress_defaults(), diff --git a/backend/app/services/agent_registry/data/catalog_manifest.yaml b/backend/app/services/agent_registry/data/catalog_manifest.yaml index e4b18de0..5456ef89 100644 --- a/backend/app/services/agent_registry/data/catalog_manifest.yaml +++ b/backend/app/services/agent_registry/data/catalog_manifest.yaml @@ -14,9 +14,6 @@ platform: dify_app_types: - chatflow - workflow - exposure_modes: - - workspace - - internal suggested_questions_styles: - plain - styled diff --git a/backend/app/services/agent_registry/resolver.py b/backend/app/services/agent_registry/resolver.py index a61d772a..1ddd1d60 100644 --- a/backend/app/services/agent_registry/resolver.py +++ b/backend/app/services/agent_registry/resolver.py @@ -152,23 +152,6 @@ def resolve_conversation_mode(agent) -> str: return _read_string_column(agent, 'conversation_mode', default=_COLUMN_DEFAULTS['conversation_mode']) -def resolve_effective_role(agent) -> str: - """ - 解析 Agent 的运行时角色,不新增数据库字段。 - - 核心逻辑:internal Provider 统一视为内部执行器,其余注册项继续视为用户入口; - 历史 conversation_mode 保留用于兼容,但内部执行器运行时不参与聊天呈现。 - - Args: - agent: Agent ORM 或具备 exposure_mode 属性的代理对象。 - - Returns: - user_agent 或 internal_executor。 - """ - exposure_mode = _read_string_column(agent, 'exposure_mode', default='workspace') - return 'internal_executor' if exposure_mode == 'internal' else 'user_agent' - - def resolve_capabilities(agent) -> dict[str, bool]: """ 解析 Agent 平台能力声明。 diff --git a/backend/app/services/agent_registry/serialization.py b/backend/app/services/agent_registry/serialization.py index fef344ff..c2d542af 100644 --- a/backend/app/services/agent_registry/serialization.py +++ b/backend/app/services/agent_registry/serialization.py @@ -15,7 +15,6 @@ from app.services.agent_registry.resolver import ( resolve_agent_code, resolve_capabilities, resolve_conversation_mode, - resolve_effective_role, resolve_progress_contract, resolve_runtime_provider, ) @@ -49,9 +48,7 @@ def serialize_registry_fields(agent: Agent | Any) -> dict[str, Any]: 'agent_code': resolve_agent_code(agent), 'runtime_provider': resolve_runtime_provider(agent), 'conversation_mode': resolve_conversation_mode(agent), - 'effective_role': resolve_effective_role(agent), 'dify_app_type': getattr(agent, 'dify_app_type', None) or 'chatflow', - 'exposure_mode': getattr(agent, 'exposure_mode', None) or 'workspace', 'iframe_url': getattr(agent, 'iframe_url', None), 'category': getattr(agent, 'category', None) or None, 'sub_category': getattr(agent, 'sub_category', None) or None, diff --git a/backend/app/services/agent_runtime_binding_service.py b/backend/app/services/agent_runtime_binding_service.py deleted file mode 100644 index 7fa0a583..00000000 --- a/backend/app/services/agent_runtime_binding_service.py +++ /dev/null @@ -1,219 +0,0 @@ -""" -backend/app/services/agent_runtime_binding_service.py - -用途:解析、校验和管理 Agent 的命名运行能力 Provider 绑定。 -依赖:Agent/AgentRuntimeBinding、Agent Catalog、统一 AppError。 -逻辑:Catalog 声明 owner 需要的能力和 Provider 约束;管理员只保存 Agent 外键,运行时禁止名称或环境变量回退。 -""" - -from __future__ import annotations - -from typing import Any - -from app import db -from app.core.errors import ConflictError, NotFoundError, ValidationError -from app.models import Agent, AgentRuntimeBinding -from app.services.agent_registry.catalog import get_catalog_entry -from app.services.agent_registry.resolver import resolve_effective_role - - -_EXECUTOR_GOVERNANCE_DEFAULTS = { - 'provider_max_concurrency': 4, - 'circuit_failure_threshold': 5, - 'circuit_cooldown_seconds': 60, -} - - -def _capability_definition(owner: Agent, capability_code: str) -> dict[str, Any]: - """读取 owner Agent Catalog 中声明的能力定义;未声明能力不可由管理员任意绑定。""" - entry = get_catalog_entry(owner.agent_code) or {} - definitions = entry.get('required_runtime_capabilities') - definitions = definitions if isinstance(definitions, dict) else {} - definition = definitions.get(capability_code) - if not isinstance(definition, dict): - raise ValidationError( - 'Runtime capability is not declared by the Agent Catalog', - code='AGENT.RUNTIME_CAPABILITY_NOT_DECLARED', - ) - return definition - - -def _normalize_config(raw: Any) -> dict[str, Any]: - """限制通用超时/重试配置,避免任意 JSON 成为隐式业务配置后门。""" - if raw is None: - raw = {} - if not isinstance(raw, dict): - raise ValidationError('config must be an object', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID') - unknown = set(raw) - {'timeout_seconds', 'max_attempts', 'auto_create_enabled'} - if unknown: - raise ValidationError( - 'Unsupported runtime binding config keys', - code='AGENT.RUNTIME_BINDING_CONFIG_INVALID', - details={'keys': sorted(unknown)}, - ) - try: - timeout_seconds = int(raw.get('timeout_seconds', 900)) - max_attempts = int(raw.get('max_attempts', 3)) - except (TypeError, ValueError) as exc: - raise ValidationError( - 'Runtime binding execution settings must be integers', - code='AGENT.RUNTIME_BINDING_CONFIG_INVALID', - ) from exc - if not 30 <= timeout_seconds <= 3600 or not 1 <= max_attempts <= 10: - raise ValidationError( - 'Runtime binding config is outside allowed limits', - code='AGENT.RUNTIME_BINDING_CONFIG_INVALID', - ) - result = { - 'timeout_seconds': timeout_seconds, - 'max_attempts': max_attempts, - } - if 'auto_create_enabled' in raw: - if not isinstance(raw['auto_create_enabled'], bool): - raise ValidationError('auto_create_enabled must be boolean', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID') - result['auto_create_enabled'] = raw['auto_create_enabled'] - return result - - -def resolve_executor_governance(provider: Agent) -> dict[str, int]: - """读取内部执行器全局治理,供新 Run 冻结并避免入口应用绕过 Provider 保护。""" - raw_extra = provider.extra_config if isinstance(provider.extra_config, dict) else {} - raw = raw_extra.get('order_extraction_governance') if isinstance(raw_extra.get('order_extraction_governance'), dict) else {} - try: - config = { - 'provider_max_concurrency': int(raw.get('provider_max_concurrency', _EXECUTOR_GOVERNANCE_DEFAULTS['provider_max_concurrency'])), - 'circuit_failure_threshold': int(raw.get('circuit_failure_threshold', _EXECUTOR_GOVERNANCE_DEFAULTS['circuit_failure_threshold'])), - 'circuit_cooldown_seconds': int(raw.get('circuit_cooldown_seconds', _EXECUTOR_GOVERNANCE_DEFAULTS['circuit_cooldown_seconds'])), - } - except (TypeError, ValueError) as exc: - raise ValidationError('Internal executor governance settings must be integers', code='AGENT.EXECUTOR_GOVERNANCE_INVALID') from exc - if not 1 <= config['provider_max_concurrency'] <= 20: - raise ValidationError('Internal executor concurrency is outside allowed limits', code='AGENT.EXECUTOR_GOVERNANCE_INVALID') - if not 2 <= config['circuit_failure_threshold'] <= 20 or not 10 <= config['circuit_cooldown_seconds'] <= 600: - raise ValidationError('Internal executor circuit settings are outside allowed limits', code='AGENT.EXECUTOR_GOVERNANCE_INVALID') - return config - - -def _validate_provider(provider: Agent, definition: dict[str, Any]) -> None: - """按 Catalog 校验 Provider 类型、可见性和 Dify 配置完整性。""" - allowed_providers = set(definition.get('allowed_runtime_providers') or []) - allowed_app_types = set(definition.get('allowed_dify_app_types') or []) - allowed_exposure = set(definition.get('allowed_exposure_modes') or []) - allowed_roles = set(definition.get('allowed_effective_roles') or []) - if not provider.is_active: - raise ConflictError('Runtime provider is disabled', code='AGENT.RUNTIME_PROVIDER_DISABLED') - if allowed_providers and provider.runtime_provider not in allowed_providers: - raise ValidationError('Runtime provider type is invalid', code='AGENT.RUNTIME_PROVIDER_INVALID') - if allowed_app_types and provider.dify_app_type not in allowed_app_types: - raise ValidationError('Dify application type is invalid', code='AGENT.RUNTIME_PROVIDER_INVALID') - if allowed_exposure and provider.exposure_mode not in allowed_exposure: - raise ValidationError('Runtime provider exposure mode is invalid', code='AGENT.RUNTIME_PROVIDER_INVALID') - if allowed_roles and resolve_effective_role(provider) not in allowed_roles: - raise ValidationError('Runtime provider role is invalid', code='AGENT.RUNTIME_PROVIDER_INVALID') - if provider.runtime_provider in {'dify', 'hybrid'} and ( - not str(provider.dify_app_id or '').strip() - or not str(provider.dify_api_key or '').strip() - or not str(provider.api_base_url or '').strip() - ): - raise ConflictError( - 'Runtime provider Dify configuration is incomplete', - code='AGENT.RUNTIME_PROVIDER_CONFIG_INCOMPLETE', - ) - - -def serialize_runtime_binding(binding: AgentRuntimeBinding) -> dict[str, Any]: - """输出管理端安全视图;不返回 Provider API Key。""" - provider = binding.provider_agent - return { - 'id': binding.id, - 'owner_agent_id': binding.owner_agent_id, - 'capability_code': binding.capability_code, - 'provider_agent_id': binding.provider_agent_id, - 'provider': { - 'id': provider.id, - 'name': provider.name, - 'runtime_provider': provider.runtime_provider, - 'dify_app_type': provider.dify_app_type, - 'exposure_mode': provider.exposure_mode, - 'is_active': provider.is_active, - } if provider else None, - 'enabled': bool(binding.enabled), - 'quality_batch_id': binding.quality_batch_id, - 'config': dict(binding.config_json or {}), - } - - -def list_runtime_bindings(owner_agent_id: int) -> list[dict[str, Any]]: - """列出指定 owner Agent 的全部显式运行能力绑定。""" - owner = db.session.get(Agent, owner_agent_id) - if owner is None: - raise NotFoundError('Agent not found') - rows = AgentRuntimeBinding.query.filter_by(owner_agent_id=owner.id).order_by( - AgentRuntimeBinding.capability_code.asc(), - ).all() - return [serialize_runtime_binding(row) for row in rows] - - -def save_runtime_binding( - *, - owner_agent_id: int, - capability_code: str, - provider_agent_id: int, - enabled: bool, - quality_batch_id: int | None = None, - config: Any, - commit: bool = True, -) -> AgentRuntimeBinding: - """创建或更新能力绑定;开启自动建单时必须引用已批准质量批次。""" - owner = db.session.get(Agent, owner_agent_id) - provider = db.session.get(Agent, provider_agent_id) - if owner is None or provider is None: - raise NotFoundError('Agent not found') - code = str(capability_code or '').strip() - if owner.id == provider.id: - raise ValidationError('Owner and provider must be different Agents', code='AGENT.RUNTIME_PROVIDER_INVALID') - definition = _capability_definition(owner, code) - if enabled: - _validate_provider(provider, definition) - normalized_config = _normalize_config(config) - if code == 'shipping.order_extraction' and normalized_config.get('auto_create_enabled'): - from app.services.shipping_notice.order_extraction_quality_service import require_approved_quality_batch - from app.services.shipping_notice.order_schema.runtime import published_version - - require_approved_quality_batch( - batch_id=quality_batch_id, - owner_agent_id=owner.id, - schema_version_id=int(published_version().id), - ) - binding = AgentRuntimeBinding.query.filter_by( - owner_agent_id=owner.id, capability_code=code, - ).first() - if binding is None: - binding = AgentRuntimeBinding(owner_agent_id=owner.id, capability_code=code) - db.session.add(binding) - binding.provider_agent_id = provider.id - binding.enabled = bool(enabled) - binding.quality_batch_id = int(quality_batch_id) if quality_batch_id is not None else None - binding.config_json = normalized_config - if commit: - db.session.commit() - else: - db.session.flush() - return binding - - -def resolve_runtime_binding(*, owner_agent_id: int, capability_code: str) -> AgentRuntimeBinding: - """运行时解析启用绑定并复检 Provider;未配置时明确阻断,禁止任何隐式回退。""" - binding = AgentRuntimeBinding.query.filter_by( - owner_agent_id=owner_agent_id, - capability_code=capability_code, - enabled=True, - ).first() - if binding is None: - raise ConflictError( - 'Runtime capability provider is not configured', - code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_NOT_CONFIGURED', - ) - definition = _capability_definition(binding.owner_agent, capability_code) - _validate_provider(binding.provider_agent, definition) - return binding diff --git a/backend/app/services/agent_user_access.py b/backend/app/services/agent_user_access.py deleted file mode 100644 index 2a16642e..00000000 --- a/backend/app/services/agent_user_access.py +++ /dev/null @@ -1,106 +0,0 @@ -""" -backend/app/services/agent_user_access.py - -用途:统一约束哪些 Agent 可以进入用户授权、工作台和普通对话链路。 -依赖:SQLAlchemy Session、Agent/User 模型、统一业务异常。 -逻辑:内部执行器只允许 Runtime Binding 后台调用;所有用户入口仅接受 workspace 应用。 -""" - -from __future__ import annotations - -from collections.abc import Iterable - -from app import db -from app.core.errors import ForbiddenError, NotFoundError, ValidationError -from app.models import Agent, User - - -USER_ACCESS_FORBIDDEN_CODE = 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN' - - -def is_user_application(agent: Agent | None, *, require_active: bool = False) -> bool: - """判断 Agent 是否可进入用户侧;可选同时要求启用状态。""" - if agent is None or agent.exposure_mode != 'workspace': - return False - return bool(agent.is_active) if require_active else True - - -def load_grantable_agents(agent_ids: Iterable[object] | None) -> list[Agent]: - """ - 加载可授予用户的应用并保持输入顺序。 - - 参数约束:所有 ID 必须存在且属于 workspace;内部执行器不得被授权给任何用户。 - """ - if agent_ids is not None and not isinstance(agent_ids, (list, tuple, set)): - raise ValidationError('agent_ids must be an array') - raw_ids = list(agent_ids or []) - try: - normalized_ids = list(dict.fromkeys(int(agent_id) for agent_id in raw_ids)) - except (TypeError, ValueError) as exc: - raise ValidationError('agent_ids must be an integer array') from exc - if not normalized_ids: - return [] - - agents = db.session.query(Agent).filter(Agent.id.in_(normalized_ids)).all() - by_id = {agent.id: agent for agent in agents} - missing_ids = [agent_id for agent_id in normalized_ids if agent_id not in by_id] - if missing_ids: - raise ValidationError('Some agent_ids are invalid', details={'agent_ids': missing_ids}) - internal_ids = [agent_id for agent_id in normalized_ids if not is_user_application(by_id[agent_id])] - if internal_ids: - raise ValidationError( - 'Internal executors cannot be assigned to users', - code=USER_ACCESS_FORBIDDEN_CODE, - details={'agent_ids': internal_ids}, - ) - return [by_id[agent_id] for agent_id in normalized_ids] - - -def require_user_application(agent: Agent | None, *, require_active: bool = False) -> Agent: - """要求目标是 workspace 应用;用户入口可额外要求启用状态。""" - if agent is None or (require_active and not agent.is_active): - raise NotFoundError('Agent not found') - if not is_user_application(agent): - raise ForbiddenError( - 'Internal executors are unavailable from user-facing APIs', - code=USER_ACCESS_FORBIDDEN_CODE, - ) - return agent - - -def require_user_application_access(agent: Agent | None, user: User) -> Agent: - """ - 校验普通用户入口的 Agent 访问。 - - 核心逻辑:先阻断停用项和内部执行器,再处理管理员全 workspace 可见、普通用户按授权可见。 - """ - agent = require_user_application(agent, require_active=True) - if user.role != 'admin' and agent not in user.agents: - raise ForbiddenError('Permission denied for this agent') - return agent - - -def visible_default_agent_id(user: User) -> int | None: - """返回可用于用户入口的默认应用 ID;历史内部执行器引用按未配置处理。""" - if user.default_agent_id is None: - return None - agent = db.session.get(Agent, user.default_agent_id) - if not is_user_application(agent, require_active=True): - return None - if user.role != 'admin' and agent not in user.agents: - return None - return int(agent.id) - - -def visible_agent_ids(user: User, *, active_only: bool = True) -> set[int]: - """返回当前用户在用户侧实际可见的应用 ID 集合。""" - if user.role == 'admin': - query = db.session.query(Agent.id).filter(Agent.exposure_mode == 'workspace') - if active_only: - query = query.filter(Agent.is_active.is_(True)) - return {int(row[0]) for row in query.all()} - return { - int(agent.id) - for agent in user.agents - if is_user_application(agent, require_active=active_only) - } diff --git a/backend/app/services/shipping_notice/attachment_integrity.py b/backend/app/services/shipping_notice/attachment_integrity.py index fc014d61..9fb6f345 100644 --- a/backend/app/services/shipping_notice/attachment_integrity.py +++ b/backend/app/services/shipping_notice/attachment_integrity.py @@ -57,6 +57,12 @@ def is_attachment_parse_incomplete(structured: dict[str, Any] | None) -> bool: if not isinstance(structured, dict): return False + preview_status = str(structured.get('preview_status') or '').strip().lower() + if preview_status == 'directory_incomplete': + return True + if structured.get('attachment_directory_complete') is False: + return True + warnings = structured.get('warnings') or [] for item in warnings: if is_blocking_warning(str(item or '')): diff --git a/backend/app/services/shipping_notice/attachment_selection.py b/backend/app/services/shipping_notice/attachment_selection.py new file mode 100644 index 00000000..1dc31f59 --- /dev/null +++ b/backend/app/services/shipping_notice/attachment_selection.py @@ -0,0 +1,279 @@ +""" +services/shipping_notice/attachment_selection.py + +用途:基于 Intake 快览事实生成可审计的附件选择计划。 +依赖:ShippingNoticeIntake、标准库正则与哈希;只读取 structured_result_json,不回读 Document/布局结果。 +逻辑:发送阶段调用本文件,把当前批次附件目录转换为“为何选择/为何跳过”的稳定计划; + 后续深度解析、预算扩展与审计都应复用这份快照,而不是重新猜测附件优先级。 +""" + +from __future__ import annotations + +import re +from collections import defaultdict +from typing import Any + +from app.models import ShippingNoticeIntake + +_PO_HINT_RE = re.compile(r'\b(?:PO[-_ ]*)?([A-Z]{0,4}\d{5,})\b', re.IGNORECASE) +_TOKEN_RE = re.compile(r'[A-Z0-9]{4,}', re.IGNORECASE) +_IMAGE_MIME_PREFIX = 'image/' +_READY_REASON = 'ready_for_extraction' +_EXCLUDED_CATALOG_REASONS = { + 'archive', + 'executable', + 'macro_enabled', + 'unknown_binary', + 'inline_resource', + 'signature_or_logo', +} +_TYPE_WEIGHTS: tuple[tuple[tuple[str, ...], int, str], ...] = ( + (('application/pdf',), 160, 'type_pdf'), + (( + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'application/msword', + ), 80, 'type_word'), + (( + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'application/vnd.ms-excel', + 'text/csv', + ), 90, 'type_spreadsheet'), + (('message/rfc822',), 70, 'type_nested_eml'), +) +_NAME_HINTS: tuple[tuple[str, int, str], ...] = ( + ('po', 60, 'filename_po_hint'), + ('order', 45, 'filename_order_hint'), + ('reservation', 40, 'filename_reservation_hint'), + ('booking', 35, 'filename_booking_hint'), + ('shipping', 20, 'filename_shipping_hint'), +) +_NEGATIVE_NAME_HINTS: tuple[tuple[str, int, str], ...] = ( + ('copy', -40, 'filename_copy_hint'), + ('duplicate', -80, 'filename_duplicate_hint'), + ('signature', -180, 'filename_signature_hint'), + ('sign', -120, 'filename_sign_hint'), + ('logo', -180, 'filename_logo_hint'), + ('stamp', -100, 'filename_stamp_hint'), +) + + +def _structured(intake: ShippingNoticeIntake) -> dict[str, Any]: + """读取 Intake 快览摘要;缺失时返回空对象,调用方决定是否视为不可选。""" + return intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {} + + +def _mail_text(structured: dict[str, Any]) -> str: + """合并主题与正文白名单快照,供命名线索打分和分组使用。""" + email_meta = structured.get('email') if isinstance(structured.get('email'), dict) else {} + body_text = str(email_meta.get('body_text') or '').strip() + subject = str(email_meta.get('subject') or '').strip() + html_tables = ' '.join( + str(item).strip() for item in (email_meta.get('body_html_tables') or []) if str(item).strip() + ) + return ' '.join(part for part in (subject, body_text, html_tables) if part).strip() + + +def _po_hints(*values: str) -> list[str]: + """提取稳定的订单号线索;用于分组与评分,不输出正文原文。""" + found: list[str] = [] + for value in values: + for item in _PO_HINT_RE.findall(str(value or '')): + normalized = str(item or '').strip().upper() + if normalized and normalized not in found: + found.append(normalized) + return found + + +def _mail_tokens(text: str) -> set[str]: + """把邮件主题/正文压缩成稳定 token 集合,供附件名做轻量交叉评分。""" + return {token.upper() for token in _TOKEN_RE.findall(text or '') if len(token) >= 4} + + +def _score_attachment(*, filename: str, mime_type: str, size: int, mail_text: str) -> tuple[int, list[str], str]: + """只基于快览可见事实为单个附件评分,并返回稳定原因码和分组键。""" + score = 0 + reasons: list[str] = [] + normalized_name = filename.lower() + normalized_mime = mime_type.lower() + tokens = _mail_tokens(mail_text) + name_tokens = {token.upper() for token in _TOKEN_RE.findall(filename or '') if len(token) >= 4} + + for mime_prefixes, weight, reason in _TYPE_WEIGHTS: + if any(normalized_mime.startswith(prefix) for prefix in mime_prefixes): + score += weight + reasons.append(reason) + break + if size >= 1024 * 20: + score += 15 + reasons.append('size_non_trivial') + if size >= 1024 * 1024: + score += 10 + reasons.append('size_large_attachment') + if 0 < size <= 1024 * 8: + score -= 15 + reasons.append('size_too_small') + for needle, weight, reason in _NAME_HINTS: + if needle in normalized_name: + score += weight + reasons.append(reason) + for needle, weight, reason in _NEGATIVE_NAME_HINTS: + if needle in normalized_name: + score += weight + reasons.append(reason) + po_hints = _po_hints(filename, mail_text) + if po_hints: + score += 80 + reasons.append('po_hint_detected') + overlap = sorted(tokens & name_tokens) + if overlap: + score += min(30, len(overlap) * 10) + reasons.append('mail_filename_token_overlap') + group_key = po_hints[0] if po_hints else (overlap[0] if overlap else normalized_name[:48] or 'ungrouped') + return score, reasons, group_key + + +def build_attachment_selection_snapshot( + *, + intakes: list[ShippingNoticeIntake], + max_initial_attachments: int = 2, + max_initial_concurrency: int = 2, + expansion_batch_size: int = 2, + max_total_attachments: int = 6, + max_total_bytes: int | None = None, + max_runtime_seconds: int | None = None, +) -> dict[str, Any]: + """ + 基于当前批次 Intake 快览事实生成可解释的附件选择计划。 + + AI 触发时机:点击发送后,需要把“当前输入框这批附件”冻结成一份稳定计划时使用。 + 该函数只能读取快览字段,禁止依赖附件正文、布局坐标、Document、Candidate 或 Provider 输出。 + + Args: + intakes: 当前发送批次的 Intake;必须已经通过上传快览。 + max_initial_attachments: 首轮自动选择上限。 + max_initial_concurrency: 首轮并发上限。 + expansion_batch_size: 后续每轮扩展的附件上限。 + max_total_attachments: 单次邮件深度解析总附件预算上限。 + + Returns: + 可写入 Run 快照的脱敏计划摘要,包含每个附件的 selected / skipped 结论与原因码。 + """ + rows: list[dict[str, Any]] = [] + duplicate_content_hashes: dict[str, int] = defaultdict(int) + for intake in intakes: + structured = _structured(intake) + mail_text = _mail_text(structured) + attachments = structured.get('attachments') if isinstance(structured.get('attachments'), list) else [] + for item in attachments: + if not isinstance(item, dict): + continue + filename = str(item.get('filename') or '').strip() + mime_type = str(item.get('mime_type') or 'application/octet-stream').strip().lower() + content_hash = str(item.get('content_hash') or '').strip().lower() + catalog_reason = str(item.get('catalog_reason') or '').strip().lower() or _READY_REASON + ready_for_extraction = bool(item.get('ready_for_extraction')) + is_inline = bool(item.get('is_inline_resource')) or mime_type.startswith(_IMAGE_MIME_PREFIX) + size = max(0, int(item.get('size') or 0)) + if is_inline: + # 邮件签名和正文内嵌资源不是用户上传的业务附件,不纳入识别范围或数量统计。 + continue + score, score_reasons, group_key = _score_attachment( + filename=filename, + mime_type=mime_type, + size=size, + mail_text=mail_text, + ) + if content_hash: + duplicate_content_hashes[content_hash] += 1 + rows.append({ + 'intake_no': intake.intake_no, + 'attachment_key': str(item.get('attachment_key') or '').strip(), + 'filename': filename, + 'mime_type': mime_type, + 'size': size, + 'content_hash': content_hash or None, + 'catalog_reason': catalog_reason, + 'ready_for_extraction': ready_for_extraction, + 'score': score, + 'score_reasons': score_reasons, + 'group_key': group_key, + 'selected': False, + 'selection_batch': None, + 'planned_selection_batch': None, + 'skip_reason_codes': [], + }) + + eligible: list[dict[str, Any]] = [] + seen_hashes: set[str] = set() + for row in rows: + skip_reasons: list[str] = [] + catalog_reason = str(row.get('catalog_reason') or _READY_REASON) + content_hash = str(row.get('content_hash') or '') + if not bool(row.get('ready_for_extraction')): + skip_reasons.append(f'catalog_reason:{catalog_reason}') + elif catalog_reason in _EXCLUDED_CATALOG_REASONS: + skip_reasons.append(f'catalog_reason:{catalog_reason}') + elif content_hash and content_hash in seen_hashes: + skip_reasons.append('duplicate_content_hash') + elif content_hash and duplicate_content_hashes.get(content_hash, 0) > 1: + seen_hashes.add(content_hash) + if not skip_reasons: + if content_hash: + seen_hashes.add(content_hash) + eligible.append(row) + else: + row['skip_reason_codes'] = skip_reasons + + eligible_ordered = sorted(eligible, key=lambda item: (-int(item['score']), str(item['filename']))) + byte_budget = max(0, int(max_total_bytes or 0)) + planned_bytes = 0 + for index, row in enumerate(eligible_ordered): + size = int(row.get('size') or 0) + if byte_budget and planned_bytes + size > byte_budget: + row['skip_reason_codes'] = ['budget_total_bytes'] + continue + if index < max_initial_attachments: + row['selected'] = True + row['selection_batch'] = 1 + planned_bytes += size + continue + if index < max_total_attachments: + row['planned_selection_batch'] = ( + 2 + ((index - max_initial_attachments) // max(1, int(expansion_batch_size or 1))) + ) + planned_bytes += size + continue + row['skip_reason_codes'] = ['budget_total_limit'] + + group_counts: dict[str, int] = defaultdict(int) + for row in rows: + group_counts[str(row.get('group_key') or 'ungrouped')] += 1 + pending_expansion_batches: dict[int, int] = defaultdict(int) + for row in rows: + planned_batch = int(row.get('planned_selection_batch') or 0) + if planned_batch > 1: + pending_expansion_batches[planned_batch] += 1 + + return { + 'selection_version': 'shipping_notice_attachment_selection.v1', + 'max_initial_attachments': int(max_initial_attachments), + 'max_initial_concurrency': int(max_initial_concurrency), + 'expansion_batch_size': int(expansion_batch_size), + 'max_total_attachments': int(max_total_attachments), + 'max_total_bytes': int(max_total_bytes or 0), + 'max_runtime_seconds': int(max_runtime_seconds or 0), + 'planned_total_bytes': planned_bytes, + 'total_attachment_count': len(rows), + 'eligible_attachment_count': len(eligible), + 'selected_attachment_count': sum(1 for row in rows if row.get('selected')), + 'planned_attachment_count': sum( + 1 for row in rows + if row.get('selected') or int(row.get('planned_selection_batch') or 0) > 1 + ), + 'pending_expansion_attachment_count': sum(pending_expansion_batches.values()), + 'pending_expansion_batches': { + str(batch): count for batch, count in sorted(pending_expansion_batches.items()) + }, + 'group_count': len(group_counts), + 'items': rows, + } diff --git a/backend/app/services/shipping_notice/document_candidate_persist.py b/backend/app/services/shipping_notice/document_candidate_persist.py index 02322610..25727672 100644 --- a/backend/app/services/shipping_notice/document_candidate_persist.py +++ b/backend/app/services/shipping_notice/document_candidate_persist.py @@ -35,7 +35,10 @@ from app.services.shipping_notice.business_fingerprint import ( build_content_fingerprint, ) from app.services.shipping_notice.eml_parse import pop_attachment_payload, strip_attachment_payloads -from app.services.shipping_notice.email_allocation_table_parser import parse_email_allocation_tables +from app.services.shipping_notice.email_allocation_table_parser import ( + parse_email_allocation_tables, + parse_email_allocation_text, +) from app.services.shipping_notice.intake_business_parser import parse_intake_business_summary from app.services.shipping_notice.notice_upload import NoticeIntakeResult from app.services.shipping_notice.order_candidate_builder import ( @@ -465,6 +468,18 @@ def persist_documents_and_candidates( from app.services.shipping_notice.duplicate_detection import detect_duplicates_for_candidate meta = result.meta if isinstance(result.meta, dict) else {} + if str(meta.get('eml_attachment_mode') or '').strip().lower() == 'preview': + # 阶段 1 约束:EML 上传快览只保留目录,不得提前落附件 Document/派生资产或触发布局任务。 + strip_attachment_payloads(meta) + return { + 'document_count': 0, + 'candidate_count': 0, + 'linked_asset_count': 0, + 'created_asset_count': 0, + 'layout_version_count': 0, + 'documents': [], + 'candidates': [], + } email_meta = meta.get('email') if isinstance(meta.get('email'), dict) else {} body_text = str(email_meta.get('body_text') or '') definition = schema_definition or {'fields': []} @@ -539,6 +554,12 @@ def persist_documents_and_candidates( html_tables=canonical_html_tables, content_hash=str(body_doc.content_hash or ''), ) + # Outlook 等客户端可能把正文表展平成纯文本行;HTML 表为空时再使用严格序列解析。 + if not supplement.get('rows') and not canonical_html_tables: + supplement = parse_email_allocation_text( + body_text=body_text, + content_hash=str(body_doc.content_hash or ''), + ) supplement['document_id'] = int(body_doc.id) body_doc.order_extraction_result_json = {'email_supplement': supplement} from app.services.shipping_notice.audit_service import append_shipping_audit_event diff --git a/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py b/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py index 341233eb..d301f535 100644 --- a/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py +++ b/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py @@ -258,8 +258,26 @@ def reconstruct_coordinate_profile_rows( for item in (exclusion_regions or []) if isinstance(item, dict) ] if exclusions: - # Footer, signature and tax blocks are not candidate physical rows at all. - glyphs = [item for item in glyphs if not any(_inside_region(item[1].bbox, region) for region in exclusions)] + # Footer, signature and tax blocks are not candidate rows. Keep an explicit + # deletion marker from an exclusion region, however: it controls the prior + # detail row and must not be discarded before row reconstruction sees it. + deletion_marker_indices = { + glyph_index + for band in _group_visual_rows(glyphs) + if _DELETED_PATTERN.fullmatch(re.sub( + r'\s+', '', ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)), + )) + and any( + any(_inside_region(glyph.bbox, region) for region in exclusions) + for glyph_index, glyph in band + ) + for glyph_index, _glyph in band + } + glyphs = [ + item for item in glyphs + if item[0] in deletion_marker_indices + or not any(_inside_region(item[1].bbox, region) for region in exclusions) + ] if not glyphs: return [] diff --git a/backend/app/services/shipping_notice/document_layout/opencv_table.py b/backend/app/services/shipping_notice/document_layout/opencv_table.py index 7e8696e3..818b9ed4 100644 --- a/backend/app/services/shipping_notice/document_layout/opencv_table.py +++ b/backend/app/services/shipping_notice/document_layout/opencv_table.py @@ -11,7 +11,10 @@ from __future__ import annotations from dataclasses import dataclass from typing import Any -import cv2 +try: + import cv2 # type: ignore +except ModuleNotFoundError: + cv2 = None import numpy as np from pydantic import BaseModel, ConfigDict, Field, model_validator @@ -109,6 +112,8 @@ def reconstruct_opencv_table_geometry( Returns: ready 时包含所有 HTML 原始 cell 的页面 bbox;失败时仅包含问题码。 """ + if cv2 is None: + return _not_ready(grid, 'opencv_unavailable') if min_consensus < 2 or len(configs) < min_consensus: raise ValueError('OpenCV grid reconstruction requires at least two configurations') image = _grayscale_page(page_image) diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py b/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py index 313e7b7b..91211b7d 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py @@ -48,7 +48,8 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout: pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} - if not tables or not pages or not glyph_tables: + # v2 模板按页面坐标区域取证;表格检测只能辅助,不能成为续页区域的硬前提。 + if not pages or (not glyph_tables and not page_glyphs): return ProfileMatchResult(status='evidence_insufficient') candidates: list[tuple[dict[str, Any], OrderCoordinateProfileV2, ProfileMatchCandidate]] = [] @@ -65,8 +66,6 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout: except (TypeError, ValueError): continue reason_codes: list[str] = [] - if len(tables) < len(profile.table_regions): - reason_codes.append('table_region_count_insufficient') required = profile.document_match.required_anchors required_hits = [_anchor_present( anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, @@ -114,6 +113,8 @@ def _anchor_present( if not expected or not all(candidates): return False page_numbers = sorted({str(item.get('page_no') or '') for item in tables if item.get('page_no')}) + if not page_numbers: + page_numbers = sorted(str(page_no) for page_no in pages) for page_no in page_numbers: glyphs = page_glyphs.get(page_no) # v1 frozen snapshots do not have page glyphs. Preserve historical matching diff --git a/backend/app/services/shipping_notice/document_profile_quality_service.py b/backend/app/services/shipping_notice/document_profile_quality_service.py index 49b15f85..0bc079c5 100644 --- a/backend/app/services/shipping_notice/document_profile_quality_service.py +++ b/backend/app/services/shipping_notice/document_profile_quality_service.py @@ -8,6 +8,7 @@ services/shipping_notice/document_profile_quality_service.py from __future__ import annotations +import re from datetime import datetime from decimal import Decimal from typing import Any @@ -21,6 +22,7 @@ from app.models import ( ShippingDocumentProfileAutoFreezeQualification, ShippingNoticeDocument, ShippingNoticeIntake, + ShippingCustomer, ShippingOrderDocumentProfile, ShippingOrderDocumentProfileSample, ) @@ -46,6 +48,7 @@ from app.services.shipping_notice.order_schema.field_rules import normalize_orde # 多明细和声明的跨页覆盖等质量门禁仍然生效。 MINIMUM_BLIND_SAMPLES = 1 HEADERLESS_MINIMUM_BLIND_SAMPLES = 1 +_BUSINESS_SCENARIO_PATTERN = re.compile(r'^[a-z0-9_:-]{1,64}$') def _quality_checksum(profile: ShippingOrderDocumentProfile) -> str: @@ -557,7 +560,11 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]: def approve_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]: - """批准最近一次合格盲测,形成绑定 Profile checksum 的不可变自动建单凭证。""" + """批准合格盲测并升级当前模板版本的自动建单资格。 + + 保留已有的客户、业务场景和人工确认范围配置;盲测批准只证明 + 模板解析质量合格,范围门禁仍由管理员单独配置。 + """ suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id)) if suite is None: raise NotFoundError('Order document profile test suite not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_FOUND') @@ -571,8 +578,14 @@ def approve_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]: suite.status = 'approved' suite.approved_by_id = actor_id suite.approved_at = datetime.utcnow() + qualification = ensure_manual_confirmation_qualification(profile) + qualification.status = 'auto_freeze_approved' + qualification.quality_suite_id = suite.id + qualification.approved_by_id = actor_id + qualification.approved_at = suite.approved_at _audit(profile_id=profile.id, event_type='blind_test_approved', actor_id=actor_id, detail={ 'suite_id': suite.id, 'profile_checksum': _quality_checksum(profile), + 'qualification_id': qualification.id, }) db.session.commit() return serialize_suite(suite) @@ -610,6 +623,45 @@ def ensure_manual_confirmation_qualification(profile: ShippingOrderDocumentProfi return qualification +def _normalize_customer_scope(customer_ids: list[int] | None) -> list[int] | None: + """标准化授权客户列表;只接受存在的客户主键,空列表视为未配置。""" + raw_ids = [int(item) for item in (customer_ids or [])] + normalized = sorted(set(raw_ids)) + if not normalized: + return None + existing_ids = { + int(row.id) + for row in ShippingCustomer.query.filter(ShippingCustomer.id.in_(normalized)).all() + } + missing = [customer_id for customer_id in normalized if customer_id not in existing_ids] + if missing: + raise ValidationError( + 'Customer scope contains unknown customer ids', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_QUALIFICATION_INVALID', + details={'customer_ids': missing}, + ) + return normalized + + +def _normalize_business_scenarios(business_scenarios: list[str] | None) -> list[str] | None: + """标准化授权业务场景列表;仅接受稳定代码,不接受自由文本说明。""" + normalized = sorted({ + str(item or '').strip().lower() + for item in (business_scenarios or []) + if str(item or '').strip() + }) + if not normalized: + return None + invalid = [item for item in normalized if _BUSINESS_SCENARIO_PATTERN.match(item) is None] + if invalid: + raise ValidationError( + 'Business scenarios contain invalid values', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_QUALIFICATION_INVALID', + details={'business_scenarios': invalid}, + ) + return normalized + + def qualification_summary(profile: ShippingOrderDocumentProfile) -> dict[str, Any]: """返回模板版本资格摘要;旧发布版本没有记录时安全降级为人工确认。""" qualification = ShippingDocumentProfileAutoFreezeQualification.query.filter_by( @@ -623,6 +675,11 @@ def qualification_summary(profile: ShippingOrderDocumentProfile) -> dict[str, An 'qualification_id': qualification.id, 'parser_version': qualification.parser_version, 'quality_suite_id': qualification.quality_suite_id, + 'customer_ids': list(qualification.customer_ids_json or []), + 'business_scenarios': list(qualification.business_scenarios_json or []), + 'customer_scope_configured': bool(qualification.customer_ids_json), + 'business_scenario_scope_configured': bool(qualification.business_scenarios_json), + 'requires_customer_confirmation': bool(qualification.requires_customer_confirmation), } @@ -634,9 +691,47 @@ def serialize_qualification(qualification: ShippingDocumentProfileAutoFreezeQual 'qualification_id': qualification.id, 'parser_version': qualification.parser_version, 'quality_suite_id': qualification.quality_suite_id, + 'customer_ids': list(qualification.customer_ids_json or []), + 'business_scenarios': list(qualification.business_scenarios_json or []), + 'customer_scope_configured': bool(qualification.customer_ids_json), + 'business_scenario_scope_configured': bool(qualification.business_scenarios_json), + 'requires_customer_confirmation': bool(qualification.requires_customer_confirmation), + 'scope_updated_at': qualification.scope_updated_at.isoformat() if qualification.scope_updated_at else None, } +def configure_auto_freeze_qualification_scope( + *, + profile_id: int, + actor_id: int, + customer_ids: list[int] | None, + business_scenarios: list[str] | None, + requires_customer_confirmation: bool = True, +) -> ShippingDocumentProfileAutoFreezeQualification: + """配置模板版本的客户/业务场景授权范围;为空时表示清空并回到未配置状态。""" + profile = _profile(profile_id) + qualification = ShippingDocumentProfileAutoFreezeQualification.query.filter_by( + profile_id=profile.id, profile_version=profile.version, profile_checksum=str(profile.checksum or ''), + ).one_or_none() + if qualification is None: + raise ConflictError('Profile qualification is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_QUALIFICATION_NOT_FOUND') + normalized_customer_ids = _normalize_customer_scope(customer_ids) + normalized_business_scenarios = _normalize_business_scenarios(business_scenarios) + qualification.customer_ids_json = normalized_customer_ids + qualification.business_scenarios_json = normalized_business_scenarios + qualification.requires_customer_confirmation = bool(requires_customer_confirmation) + qualification.scope_updated_by_id = actor_id + qualification.scope_updated_at = datetime.utcnow() + _audit(profile_id=profile.id, event_type='auto_freeze_scope_configured', actor_id=actor_id, detail={ + 'qualification_id': qualification.id, + 'customer_scope_count': len(normalized_customer_ids or []), + 'business_scenario_count': len(normalized_business_scenarios or []), + 'requires_customer_confirmation': qualification.requires_customer_confirmation, + }) + db.session.commit() + return qualification + + def suspend_auto_freeze_qualification(*, profile_id: int, actor_id: int, reason: str) -> ShippingDocumentProfileAutoFreezeQualification: """单独暂停一个模板版本资格;即使未来已批准也立即阻断新的自动冻结。""" profile = _profile(profile_id) diff --git a/backend/app/services/shipping_notice/email_allocation_table_parser.py b/backend/app/services/shipping_notice/email_allocation_table_parser.py index 6c81cd1a..17e2c67a 100644 --- a/backend/app/services/shipping_notice/email_allocation_table_parser.py +++ b/backend/app/services/shipping_notice/email_allocation_table_parser.py @@ -99,3 +99,66 @@ def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str) }) result.update({'rows': rows, 'issues': sorted(set(issues))}) return result + + +def parse_email_allocation_text(*, body_text: str, content_hash: str) -> dict[str, Any]: + """解析无 HTML 的纵向表头正文,只有完整唯一表头序列才会产出补充行。 + + 这类邮件客户端会把一行表头和数据单元格都展平成换行文本。按固定表头序列 + 还原时保留文本索引证据;找不到完整序列则安全返回空结果,绝不猜测正文段落。 + """ + result = empty_email_supplement_result() + tokens = [line.strip() for line in str(body_text or '').splitlines() if line.strip()] + expected = [ + 'allocation_id', 'reservation_id', 'source_from_party', 'source_type', + 'allocated_entity', 'mpn', 'allocated_qty', 'po_number', + ] + normalized = [normalize_table_header(token) for token in tokens] + aliases = { + field: {normalize_table_header(alias) for alias in values} + for field, values in _HEADERS.items() + } + start = next(( + index for index in range(0, len(tokens) - len(expected) + 1) + if all(normalized[index + offset] in aliases[field] for offset, field in enumerate(expected)) + ), None) + if start is None: + return result + + column_count = len(expected) + rows: list[dict[str, Any]] = [] + seen_rows: set[tuple[str, ...]] = set() + for offset in range(start + column_count, len(tokens), column_count): + values = tokens[offset:offset + column_count] + if len(values) != column_count: + break + po_number = normalize_po_number(values[-1]) + if not po_number: + # 正文表结束后的普通段落不得作为一条不完整记录继续吞入。 + break + identity = tuple(values) + # 转发邮件常同时含原始正文与引用正文;同一整行仅保留一次,不能制造假冲突。 + if identity in seen_rows: + continue + seen_rows.add(identity) + row = {field: value for field, value in zip(expected, values)} + row['po_number'] = po_number + reservation_id = validated_reservation_id(row.get('reservation_id')) + if not reservation_id: + result['issues'].append('email_supplement_reservation_invalid') + continue + row['reservation_id'] = reservation_id + row['evidence'] = { + field: { + 'table_index': None, 'row_index': len(rows) + 1, 'column_index': column, + 'cell_id': f'email-supplement-text:{content_hash}:r{len(rows) + 1}:c{column}', + 'raw_value': value, + } + for column, (field, value) in enumerate(zip(expected, values)) + } + row['table_index'] = None + row['row_index'] = len(rows) + 1 + rows.append(row) + result['rows'] = rows + result['issues'] = sorted(set(result['issues'])) + return result diff --git a/backend/app/services/shipping_notice/eml_parse.py b/backend/app/services/shipping_notice/eml_parse.py index 89ccd78f..f46ff458 100644 --- a/backend/app/services/shipping_notice/eml_parse.py +++ b/backend/app/services/shipping_notice/eml_parse.py @@ -1,7 +1,7 @@ """ services/shipping_notice/eml_parse.py -用途:将 .eml 解析为结构化结果(邮件元数据、清洗正文、真实附件及各自文本)。 +用途:将 .eml 解析为结构化结果(邮件元数据、清洗正文、附件目录,按模式可选附件全文)。 依赖:标准库 email/html、BeautifulSoup;Flask current_app(可选);notice_upload.extract_notice_text(叶附件抽取)。 逻辑:由 notice_upload.extract_notice_text 在 file_type=eml 时调用;忽略内嵌图片/签名图; 嵌套 message/rfc822 与附件型 multipart(disposition/filename)登记为独立附件; @@ -22,7 +22,7 @@ from email.message import Message from email.parser import BytesParser from email.utils import parsedate_to_datetime from pathlib import Path -from typing import Any, Callable +from typing import Any, Callable, Literal from bs4 import BeautifulSoup, Comment @@ -545,8 +545,8 @@ def _register_and_expand_attached_multipart( "parse_status": "skipped", "extracted_text": "", "warnings": [], - "_payload_bytes": raw or b"", } + _remember_payload(item, raw or b"", retain_payloads=state.retain_payloads) if size > state.limits.max_attachment_bytes: item["parse_status"] = "skipped" @@ -656,12 +656,15 @@ def _guess_suffix(filename: str, mime_type: str) -> str: ExtractTextFn = Callable[[Path], tuple[str, dict[str, Any]]] +AttachmentExtractMode = Literal["deep", "preview"] @dataclass class _ParseState: limits: EmlLimits extract_text: ExtractTextFn + retain_payloads: bool = False + attachment_mode: AttachmentExtractMode = "deep" warnings: list[str] = field(default_factory=list) attachments: list[dict[str, Any]] = field(default_factory=list) nested_bodies: list[str] = field(default_factory=list) # 兼容保留;v3 起 rfc822 改走 attachments,不再写入 @@ -678,6 +681,23 @@ def _next_attachment_key(state: _ParseState) -> str: return f"att-{state.attachment_seq:03d}" +def _skip_inline_resource(state: _ParseState) -> None: + """跳过内嵌资源但保留 MIME 遍历序号,保证快览与深度解析附件键一致。""" + state.skipped_inline += 1 + _next_attachment_key(state) + + +def _remember_payload( + item: dict[str, Any], + payload: bytes, + *, + retain_payloads: bool, +) -> None: + """仅在调用方显式要求时保留附件原始字节,避免预览链路持有大对象。""" + if retain_payloads and payload: + item["_payload_bytes"] = payload + + def _is_eml_payload(*, filename: str, mime_type: str) -> bool: """判定附件是否为可递归的 .eml / rfc822 载荷。""" suffix = Path(filename or "").suffix.lower() @@ -685,6 +705,101 @@ def _is_eml_payload(*, filename: str, mime_type: str) -> bool: return suffix == ".eml" or mime in {"message/rfc822", "application/eml"} +_PREVIEW_READY_SUFFIXES = frozenset( + { + ".pdf", + ".doc", + ".docx", + ".xls", + ".xlsx", + ".csv", + ".txt", + ".html", + ".htm", + ".xml", + ".json", + ".eml", + ".msg", + ".png", + ".jpg", + ".jpeg", + ".webp", + ".bmp", + ".tif", + ".tiff", + } +) +_PREVIEW_ARCHIVE_SUFFIXES = frozenset( + {".zip", ".rar", ".7z", ".tar", ".gz", ".tgz", ".bz2", ".xz"} +) +_PREVIEW_EXECUTABLE_SUFFIXES = frozenset( + {".exe", ".dll", ".bat", ".cmd", ".com", ".msi", ".vbs", ".js", ".jar", ".ps1", ".scr"} +) +_PREVIEW_MACRO_SUFFIXES = frozenset({".docm", ".xlsm", ".pptm", ".xlam", ".xltm"}) +_PREVIEW_READY_MIME_PREFIXES = ("text/", "image/") +_PREVIEW_READY_MIMES = frozenset( + { + "application/pdf", + "message/rfc822", + "application/eml", + "application/msword", + "application/vnd.ms-excel", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + } +) +_PREVIEW_ARCHIVE_MIMES = frozenset( + { + "application/zip", + "application/x-zip-compressed", + "application/x-7z-compressed", + "application/x-rar-compressed", + "application/gzip", + "application/x-tar", + } +) +_PREVIEW_EXECUTABLE_MIMES = frozenset( + { + "application/x-msdownload", + "application/x-msdos-program", + "application/x-sh", + "application/x-powershell", + "application/java-archive", + } +) + + +def _preview_catalog_reason( + *, + filename: str, + mime_type: str, + is_inline_resource: bool, +) -> tuple[bool, str]: + """ + 根据目录阶段可见事实判断附件是否可进入后续深度解析。 + + Returns: + tuple[bool, str]: (是否可进入深度解析, 原因码)。 + """ + suffix = Path(str(filename or "")).suffix.lower() + mime = str(mime_type or "").lower() + if is_inline_resource: + if _looks_like_signature_or_logo(filename): + return False, "signature_or_logo" + return False, "inline_resource" + if suffix in _PREVIEW_ARCHIVE_SUFFIXES or mime in _PREVIEW_ARCHIVE_MIMES: + return False, "archive" + if suffix in _PREVIEW_MACRO_SUFFIXES or "macroenabled" in mime: + return False, "macro_enabled" + if suffix in _PREVIEW_EXECUTABLE_SUFFIXES or mime in _PREVIEW_EXECUTABLE_MIMES: + return False, "executable" + if suffix in _PREVIEW_READY_SUFFIXES: + return True, "ready_for_extraction" + if mime in _PREVIEW_READY_MIMES or any(mime.startswith(prefix) for prefix in _PREVIEW_READY_MIME_PREFIXES): + return True, "ready_for_extraction" + return False, "unknown_binary" + + def _expand_eml_file_attachment( *, state: _ParseState, @@ -812,9 +927,9 @@ def _append_attachment( "parse_status": "skipped", "extracted_text": "", "warnings": [], - # 仅内存保留供阶段二派生资产;写 structured_result / 对外 API 前必须剥离 - "_payload_bytes": payload or b"", } + # 仅在显式深度链路保留原始字节;预览模式不再为后续派生资产持有 payload。 + _remember_payload(item, payload or b"", retain_payloads=state.retain_payloads) # [STEP 2] 单附件 / 总大小上限 # 计费规则:顶层真实附件(含 .eml 容器)计入总量;从已计费 .eml 展开的子内容不计。 @@ -900,8 +1015,8 @@ def _register_and_expand_rfc822( "parse_status": "empty", "extracted_text": "", "warnings": [], - "_payload_bytes": raw or b"", } + _remember_payload(item, raw or b"", retain_payloads=state.retain_payloads) if content_hash and content_hash in state.seen_hashes: item["parse_status"] = "duplicate" @@ -1000,6 +1115,182 @@ def _maybe_charge_rfc822_container( return True +def _append_preview_attachment( + state: _ParseState, + *, + filename: str, + mime_type: str, + payload: bytes, + count_toward_total: bool = True, + is_inline_resource: bool = False, + forced_status: str | None = None, + forced_warning: str | None = None, +) -> None: + """ + 仅登记附件目录,不做正文抽取或递归展开。 + + 核心逻辑:目录阶段只保留文件名、MIME、大小、哈希、内嵌标记和后续是否允许深度解析。 + forced_status/forced_warning 用于记录超深、不可读嵌套等目录不完整事实。 + """ + state.discovered_attachment_count += 1 + if len(state.attachments) >= state.limits.max_attachments: + _note_attachment_limit_exceeded(state) + return + + raw = payload or b"" + size = len(raw) + content_hash = hashlib.sha256(raw).hexdigest().lower() if raw else "" + ready_for_extraction, catalog_reason = _preview_catalog_reason( + filename=filename, + mime_type=mime_type, + is_inline_resource=is_inline_resource, + ) + key = _next_attachment_key(state) + item: dict[str, Any] = { + "attachment_key": key, + "filename": filename, + "mime_type": mime_type or "application/octet-stream", + "size": size, + "content_hash": content_hash, + "parse_status": "ready_for_extraction" if ready_for_extraction else "directory_only", + "extracted_text": "", + "warnings": [], + "ready_for_extraction": ready_for_extraction, + "is_inline_resource": is_inline_resource, + "catalog_reason": catalog_reason, + } + _remember_payload(item, raw, retain_payloads=state.retain_payloads) + + if forced_warning: + item["parse_status"] = forced_status or "skipped" + item["ready_for_extraction"] = False + item["warnings"].append(forced_warning) + if forced_warning.startswith("eml_total_attachment_size_exceeded"): + if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings): + state.warnings.append(forced_warning) + elif forced_warning not in state.warnings: + state.warnings.append(forced_warning) + state.attachments.append(item) + return + + if size > state.limits.max_attachment_bytes: + item["parse_status"] = "skipped" + item["ready_for_extraction"] = False + item["warnings"].append(f"eml_attachment_too_large:{size}") + state.warnings.append(f"eml_attachment_too_large:{filename}:{size}") + state.attachments.append(item) + return + if count_toward_total: + if state.total_attachment_bytes + size > state.limits.max_total_attachment_bytes: + item["parse_status"] = "skipped" + item["ready_for_extraction"] = False + item["warnings"].append("eml_total_attachment_size_exceeded") + if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings): + state.warnings.append( + f"eml_total_attachment_size_exceeded:{state.limits.max_total_attachment_bytes}" + ) + state.attachments.append(item) + return + state.total_attachment_bytes += size + if content_hash and content_hash in state.seen_hashes: + item["parse_status"] = "duplicate" + item["ready_for_extraction"] = False + item["catalog_reason"] = "duplicate" + item["warnings"].append(f"eml_attachment_duplicate:{state.seen_hashes[content_hash]}") + state.warnings.append(f"eml_attachment_duplicate:{filename}") + state.attachments.append(item) + return + if content_hash: + state.seen_hashes[content_hash] = key + state.attachments.append(item) + + +def _walk_message_preview( + msg: Message, + state: _ParseState, + *, + depth: int, + count_toward_total: bool = True, +) -> None: + """ + 遍历 MIME 树并仅登记附件目录。 + + 核心逻辑:正文提取仍由根消息自身负责;目录阶段对 message/rfc822 和附件型 multipart + 只登记容器,不递归进入其内部附件,确保上传时延与附件正文/OCR/表格无关。 + """ + if depth > state.limits.max_nesting_depth: + state.warnings.append(f"eml_nesting_depth_exceeded:{state.limits.max_nesting_depth}") + return + + if not msg.is_multipart(): + is_inline = _is_inline_or_embedded_resource(msg) + if is_inline: + _skip_inline_resource(state) + elif _is_real_attachment(msg): + _append_preview_attachment( + state, + filename=_part_filename(msg), + mime_type=str(msg.get_content_type() or "application/octet-stream"), + payload=_read_part_payload(msg), + count_toward_total=count_toward_total, + ) + return + + parts = list(msg.iter_parts()) if hasattr(msg, "iter_parts") else list(msg.get_payload() or []) + for part in parts: + if not isinstance(part, Message): + continue + ctype = str(part.get_content_type() or "").lower() + + if ctype == "message/rfc822": + _append_preview_attachment( + state, + filename=str(part.get_filename() or "").strip() or "forwarded-message.eml", + mime_type="message/rfc822", + payload=_rfc822_container_bytes(part), + count_toward_total=count_toward_total, + forced_status="skipped" if _unwrap_rfc822(part) is None else None, + forced_warning="eml_nested_message_unreadable" if _unwrap_rfc822(part) is None else None, + ) + continue + if part.is_multipart(): + if _is_attached_multipart(part): + try: + raw = part.as_bytes() + except Exception: + raw = b"" + _append_preview_attachment( + state, + filename=_part_filename(part, fallback="bundle"), + mime_type=str(part.get_content_type() or "multipart/mixed"), + payload=raw, + count_toward_total=count_toward_total, + ) + continue + _walk_message_preview( + part, + state, + depth=depth, + count_toward_total=count_toward_total, + ) + continue + is_inline = _is_inline_or_embedded_resource(part) + if is_inline: + # 内嵌签名图不是用户可识别的业务附件,不能占用附件数量或预算。 + _skip_inline_resource(state) + continue + if _is_body_text_part(part): + continue + if _is_real_attachment(part): + _append_preview_attachment( + state, + filename=_part_filename(part), + mime_type=str(part.get_content_type() or "application/octet-stream"), + payload=_read_part_payload(part), + count_toward_total=count_toward_total, + ) + + def _walk_message( msg: Message, state: _ParseState, @@ -1093,7 +1384,7 @@ def _walk_message( continue if _is_inline_or_embedded_resource(part): - state.skipped_inline += 1 + _skip_inline_resource(state) continue if _is_body_text_part(part): @@ -1140,12 +1431,13 @@ def parse_eml_bytes( limits: EmlLimits | None = None, depth: int = 0, retain_payloads: bool = False, + attachment_mode: AttachmentExtractMode = "deep", ) -> tuple[str, dict[str, Any]]: """ 结构化解析 EML 字节流。 - 核心逻辑:提取邮件头与清洗正文 → 区分真实附件与内嵌图片 → 对附件调用 extract_text; - 嵌套 rfc822 登记为独立附件并展开内层;不执行宏、脚本或嵌入对象。 + 核心逻辑:提取邮件头与清洗正文;`deep` 模式递归抽取附件全文, + `preview` 模式仅登记附件目录(名称、MIME、大小、哈希、是否内嵌、是否允许后续深度解析)。 Args: data: .eml 原始字节。 @@ -1154,6 +1446,7 @@ def parse_eml_bytes( depth: 当前嵌套深度(供嵌套 .eml 附件复用)。 retain_payloads: True 时在 attachments[*]._payload_bytes 保留二进制供派生资产; 默认 False,返回前剥离,避免测试/JSON 路径泄漏。 + attachment_mode: `deep` 递归抽附件文本;`preview` 只生成附件目录。 Returns: tuple[str, dict]: (扁平拼接文本, meta含 email/attachments/attachment_count/warnings)。 @@ -1178,8 +1471,16 @@ def parse_eml_bytes( body_text = _extract_body_text(msg) body_html_tables = _extract_body_html_tables(msg) - state = _ParseState(limits=limits, extract_text=extract_text) - _walk_message(msg, state, depth=depth) + state = _ParseState( + limits=limits, + extract_text=extract_text, + retain_payloads=retain_payloads, + attachment_mode=attachment_mode, + ) + if attachment_mode == "preview": + _walk_message_preview(msg, state, depth=depth) + else: + _walk_message(msg, state, depth=depth) if state.skipped_inline: state.warnings.append(f"eml_inline_resources_skipped:{state.skipped_inline}") @@ -1199,10 +1500,11 @@ def parse_eml_bytes( flat = _compose_flat_text( subject=subject, body_text=combined_body, - attachments=state.attachments, + attachments=state.attachments if attachment_mode == "deep" else [], ) meta: dict[str, Any] = { "file_type": "eml", + "eml_attachment_mode": attachment_mode, "warnings": list(state.warnings), "email": email_meta, "attachments": list(state.attachments), diff --git a/backend/app/services/shipping_notice/freeze_readiness_service.py b/backend/app/services/shipping_notice/freeze_readiness_service.py index 947f570f..2edd4182 100644 --- a/backend/app/services/shipping_notice/freeze_readiness_service.py +++ b/backend/app/services/shipping_notice/freeze_readiness_service.py @@ -4,6 +4,7 @@ 用途:集中检查订单解析、字段裁决、客户、冲突与库存源状态,阻止不完整订单进入不可编辑快照。 依赖:订单 Extraction、字段裁决、冲突门禁、库存源门禁及已发布履约策略。 逻辑:order_freeze_service 在创建 Snapshot 前调用;失败统一返回结构化 blocking issues。 + 阶段 5 自动冻结入口接入后,同一服务继续负责把 Run 级自动冻结门禁摘要折叠为冻结阻断原因。 """ from __future__ import annotations @@ -17,12 +18,21 @@ from app.services.shipping_notice.fulfillment_policy_registry import required_fi from app.services.shipping_notice.task_field_gate import open_field_conflict_issues -def assert_freeze_readiness(*, task: ShippingTask, extraction: ShippingOrderExtraction, policy: Any, configs: dict[str, dict[str, Any]]) -> None: - """校验当前任务是否可冻结;任何问题均 fail closed,附带可展示的 issues。""" +def assert_freeze_readiness( + *, + task: ShippingTask, + extraction: ShippingOrderExtraction, + policy: Any, + configs: dict[str, dict[str, Any]], + freeze_mode: str = 'manual', + auto_freeze_policy: dict[str, Any] | None = None, +) -> None: + """校验当前任务是否可冻结;自动冻结额外消费 Run 级门禁摘要并折叠为统一 issues。""" issues: list[dict[str, Any]] = [] if extraction.status != 'accepted': issues.append({'reason': 'extraction_not_accepted'}) issues.extend(open_field_conflict_issues(task)) + issues.extend(_auto_freeze_blocking_issues(freeze_mode=freeze_mode, auto_freeze_policy=auto_freeze_policy)) required = required_field_configs(extraction.schema_version.definition_json or {}, policy) required_codes = {'reservation_id', 'part_number', 'qty'} @@ -55,3 +65,28 @@ def assert_freeze_readiness(*, task: ShippingTask, extraction: ShippingOrderExtr issues.append({'reason': 'customer_po_missing_or_unreviewed', 'field': 'customer_po_number'}) if issues: raise ValidationError('Order is not ready to freeze', code='SHIPPING.ORDER_FREEZE_BLOCKED', details={'issues': issues}) + + +def _auto_freeze_blocking_issues( + *, + freeze_mode: str, + auto_freeze_policy: dict[str, Any] | None, +) -> list[dict[str, Any]]: + """把 Run 级自动冻结门禁摘要转换为冻结阻断 issues;人工冻结路径不消费这层策略。""" + if str(freeze_mode or 'manual') != 'auto': + return [] + policy = auto_freeze_policy if isinstance(auto_freeze_policy, dict) else {} + issues: list[dict[str, Any]] = [] + if not policy: + return [{'reason': 'auto_freeze_policy_missing'}] + if not bool(policy.get('enabled')): + issues.append({ + 'reason': 'auto_freeze_not_enabled', + 'mode': str(policy.get('mode') or '') or None, + 'qualification_status': str(policy.get('qualification_status') or '') or None, + 'customer_scope_status': str(policy.get('customer_scope_status') or '') or None, + }) + for code in policy.get('blocking_reason_codes') or []: + if str(code).strip(): + issues.append({'reason': 'auto_freeze_blocked', 'blocking_reason_code': str(code)}) + return issues diff --git a/backend/app/services/shipping_notice/intake_parse_workflow.py b/backend/app/services/shipping_notice/intake_parse_workflow.py index 5b5b253a..9006065d 100644 --- a/backend/app/services/shipping_notice/intake_parse_workflow.py +++ b/backend/app/services/shipping_notice/intake_parse_workflow.py @@ -15,7 +15,7 @@ from __future__ import annotations import tempfile from datetime import datetime from pathlib import Path -from typing import Any +from typing import Any, Literal from flask import current_app @@ -78,8 +78,7 @@ def _attachment_summaries_for_structured(meta: dict[str, Any]) -> tuple[list[dic """ 从 EML 抽取 meta 生成可写入 structured_result_json 的附件摘要。 - 核心逻辑:单附件按 NOTICE_TEXT_MAX_CHARS 截断;全部附件再共享 - SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS 总预算。 + 核心逻辑:`preview` 模式只保留附件目录字段;`deep` 模式才会写入附件全文与截断预算。 Returns: (附件摘要列表, 汇总级 warnings) @@ -92,24 +91,11 @@ def _attachment_summaries_for_structured(meta: dict[str, Any]) -> tuple[list[dic per_limit = 200000 budget = _eml_stored_attachment_chars_budget() remaining = budget + preview_mode = str(meta.get('eml_attachment_mode') or '').strip().lower() == 'preview' for item in meta.get('attachments') or []: if not isinstance(item, dict): continue - original = str(item.get('extracted_text') or '') - text, truncated = _truncate_meta_text(original, limit=per_limit) warn = list(item.get('warnings') or []) - if truncated: - warn = [*warn, f'eml_attachment_text_truncated:{per_limit}'] - if remaining <= 0: - if text: - text = '' - warn = [*warn, f'eml_attachment_text_budget_exhausted:{budget}'] - elif len(text) > remaining: - text = text[:remaining] - warn = [*warn, f'eml_attachment_text_budget_exhausted:{budget}'] - remaining = 0 - else: - remaining -= len(text) row: dict[str, Any] = { 'attachment_key': item.get('attachment_key'), 'filename': item.get('filename'), @@ -117,11 +103,30 @@ def _attachment_summaries_for_structured(meta: dict[str, Any]) -> tuple[list[dic 'size': item.get('size'), 'content_hash': item.get('content_hash'), 'parse_status': item.get('parse_status'), - 'extracted_text': text, - 'text_length': len(original), - 'stored_text_length': len(text), 'warnings': warn, + 'ready_for_extraction': bool(item.get('ready_for_extraction')), + 'is_inline_resource': bool(item.get('is_inline_resource')), + 'catalog_reason': item.get('catalog_reason'), } + if not preview_mode: + original = str(item.get('extracted_text') or '') + text, truncated = _truncate_meta_text(original, limit=per_limit) + if truncated: + warn = [*warn, f'eml_attachment_text_truncated:{per_limit}'] + if remaining <= 0: + if text: + text = '' + warn = [*warn, f'eml_attachment_text_budget_exhausted:{budget}'] + elif len(text) > remaining: + text = text[:remaining] + warn = [*warn, f'eml_attachment_text_budget_exhausted:{budget}'] + remaining = 0 + else: + remaining -= len(text) + row['warnings'] = warn + row['extracted_text'] = text + row['text_length'] = len(original) + row['stored_text_length'] = len(text) if item.get('asset_no'): row['asset_no'] = item.get('asset_no') if item.get('asset_id') is not None: @@ -129,7 +134,7 @@ def _attachment_summaries_for_structured(meta: dict[str, Any]) -> tuple[list[dic if item.get('document_id') is not None: row['document_id'] = item.get('document_id') rows.append(row) - if any( + if (not preview_mode) and any( any(str(w).startswith('eml_attachment_text_budget_exhausted:') for w in (row.get('warnings') or [])) for row in rows ): @@ -137,16 +142,46 @@ def _attachment_summaries_for_structured(meta: dict[str, Any]) -> tuple[list[dic return rows, extra_warnings +def _attachment_directory_complete(payload: dict[str, Any]) -> bool: + """ + 判定上传快览拿到的附件目录是否完整。 + + 核心逻辑:重复、内嵌资源和目录保留项不阻断;只有目录发现缺口才标记 incomplete。 + """ + warnings = payload.get('warnings') or [] + if any( + str(item).startswith(prefix) + for item in warnings + for prefix in ( + 'eml_nesting_depth_exceeded:', + 'eml_attachment_limit_exceeded:', + 'eml_total_attachment_size_exceeded:', + 'eml_nested_message_unreadable', + ) + ): + return False + rows = payload.get('attachments') or [] + if int(payload.get('attachment_count') or 0) > len(rows): + return False + for row in rows: + if not isinstance(row, dict): + continue + if str(row.get('parse_status') or '').strip().lower() == 'skipped': + return False + return True + + def intake_result_to_structured_summary( result: NoticeIntakeResult, *, business_summary: dict[str, Any] | None = None, + technical_failure: bool = False, ) -> dict[str, Any]: """ 生成前端可展示的预解析摘要(技术摘要 + 可选业务摘要)。 - 核心逻辑:普通文件仅写文件级统计;EML 额外写入 email 元数据、attachment_count 与附件摘要 - (含各附件独立 extracted_text);email.body_text 按 notice 文本上限截断; + 核心逻辑:普通文件仅写文件级统计;EML 额外写入 email 元数据、attachment_count 与附件摘要。 + `preview` 模式只落附件目录和白名单 HTML 表格快照,不写附件全文;email.body_text 按 notice 文本上限截断; 截断警告统一为 `eml_*_truncated:{limit}`(N=上限字符数)。 """ line_count = 0 @@ -160,8 +195,12 @@ def intake_result_to_structured_summary( 'line_count': line_count, 'warnings': list(result.warnings), 'parser_version': _parser_version(), + 'technical_failure': bool(technical_failure), } meta = result.meta if isinstance(result.meta, dict) else {} + attachment_mode = str(meta.get('eml_attachment_mode') or '').strip().lower() + if attachment_mode: + payload['eml_attachment_mode'] = attachment_mode email_meta = meta.get('email') if isinstance(email_meta, dict) and email_meta: original_body = str(email_meta.get('body_text') or '') @@ -179,6 +218,7 @@ def intake_result_to_structured_summary( 'body_text': body_text, 'body_text_length': len(original_body), 'stored_body_text_length': len(body_text), + 'body_html_tables': [str(item) for item in (email_meta.get('body_html_tables') or []) if str(item).strip()], } if body_truncated: payload['warnings'] = [ @@ -194,6 +234,36 @@ def intake_result_to_structured_summary( payload['warnings'] = [*payload['warnings'], *attach_extra_warnings] if attachments: payload['attachments'] = attachments + if attachment_mode == 'preview': + attachment_directory_complete = _attachment_directory_complete(payload) + payload['ready_attachment_count'] = sum( + 1 for row in attachments if bool(row.get('ready_for_extraction')) + ) + payload['directory_only_attachment_count'] = sum( + 1 + for row in attachments + if str(row.get('parse_status') or '').strip().lower() == 'directory_only' + ) + payload['duplicate_attachment_count'] = sum( + 1 + for row in attachments + if str(row.get('parse_status') or '').strip().lower() == 'duplicate' + ) + payload['attachment_directory_complete'] = attachment_directory_complete + payload['ready_for_extraction'] = (not technical_failure) and attachment_directory_complete + payload['preview_status'] = ( + 'technical_failed' + if technical_failure + else 'ready_for_extraction' + if attachment_directory_complete + else 'directory_incomplete' + ) + elif technical_failure: + payload['ready_for_extraction'] = False + payload['preview_status'] = 'technical_failed' + else: + payload['ready_for_extraction'] = True + payload['preview_status'] = 'ready_for_extraction' if isinstance(business_summary, dict): payload['business_summary'] = business_summary payload['confidence'] = business_summary.get('confidence') @@ -201,7 +271,13 @@ def intake_result_to_structured_summary( return payload -def extract_notice_from_asset(asset: FileAsset) -> NoticeIntakeResult: +def extract_notice_from_asset( + asset: FileAsset, + *, + eml_attachment_mode: Literal['deep', 'preview'] = 'deep', + retain_payloads: bool = True, + preview_only: bool = False, +) -> NoticeIntakeResult: """ 从 FileAsset 下载并抽取发货通知文本。 核心逻辑:写入临时文件后复用 extract_notice_text,避免长期落盘到 notice_uploads。 @@ -214,8 +290,12 @@ def extract_notice_from_asset(asset: FileAsset) -> NoticeIntakeResult: tmp.write(raw) tmp_path = Path(tmp.name) try: - # EML 须保留附件二进制,供阶段二幂等创建派生 FileAsset - text, meta = extract_notice_text(tmp_path, retain_payloads=True) + text, meta = extract_notice_text( + tmp_path, + retain_payloads=retain_payloads, + eml_attachment_mode=eml_attachment_mode, + preview_only=preview_only, + ) warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else [] except Exception as exc: return NoticeIntakeResult( @@ -236,7 +316,17 @@ def extract_notice_from_asset(asset: FileAsset) -> NoticeIntakeResult: except OSError: pass - if not str(text or '').strip(): + preview_accept_without_text = bool(preview_only) or ( + isinstance(meta, dict) + and str(meta.get('file_type') or '').lower() == 'eml' + and str(meta.get('eml_attachment_mode') or '').lower() == 'preview' + and ( + bool(meta.get('attachment_count')) + or bool(meta.get('attachments')) + or bool(meta.get('email')) + ) + ) + if not str(text or '').strip() and not preview_accept_without_text: return NoticeIntakeResult( filename=filename, source_type=source_type, @@ -615,7 +705,13 @@ def run_intake_parse( ) from app.services.shipping_notice.eml_parse import strip_attachment_payloads - result = extract_notice_from_asset(asset) + preview_only = str(intake.purpose or '') != 'order_document_profile_sample' + result = extract_notice_from_asset( + asset, + eml_attachment_mode='preview' if preview_only else 'deep', + retain_payloads=not preview_only, + preview_only=preview_only, + ) intake_id = int(intake.id) intake_no = intake.intake_no parser_version = _parser_version() @@ -625,7 +721,10 @@ def run_intake_parse( if result.status in {'extract_failed', 'empty_text'}: strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {}) - summary = intake_result_to_structured_summary(result) + summary = intake_result_to_structured_summary( + result, + technical_failure=(result.status == 'extract_failed'), + ) error_message = ( '; '.join(warnings)[:1000] or '文本抽取失败' if result.status == 'extract_failed' @@ -667,7 +766,7 @@ def run_intake_parse( 'reason': 'stale_parse_lease', } - persist_info: dict[str, Any] = {} + persist_info: dict[str, Any] = {'document_count': 0, 'candidate_count': 0} uploaded_storage_keys: list[str] = [] try: is_profile_sample = str(locked.purpose or '') == 'order_document_profile_sample' @@ -677,14 +776,15 @@ def run_intake_parse( 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] 上传阶段只完成文件预处理;禁止提前生成 Candidate 或业务判重。 - persist_info = persist_intake_documents( - intake=locked, - parent_asset=asset, - result=result, - uploaded_storage_keys=uploaded_storage_keys, - schema_definition=schema_definition, - ) + # [STEP 2] shipping_notice 上传阶段只落快览摘要;模板样本用途保留文档/布局持久化。 + if is_profile_sample: + persist_info = persist_intake_documents( + intake=locked, + parent_asset=asset, + result=result, + uploaded_storage_keys=uploaded_storage_keys, + schema_definition=schema_definition, + ) tech_summary = intake_result_to_structured_summary(result) tech_summary['document_count'] = persist_info.get('document_count') @@ -767,7 +867,10 @@ def run_intake_parse( storage_bucket=storage_bucket, ) strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {}) - fail_summary = intake_result_to_structured_summary(result) + fail_summary = intake_result_to_structured_summary( + result, + technical_failure=True, + ) fail_warnings = [ *warnings, f'document_candidate_persist_failed:{type(exc).__name__}:{str(exc)[:200]}', diff --git a/backend/app/services/shipping_notice/intake_service.py b/backend/app/services/shipping_notice/intake_service.py index 247d9c59..62761a9d 100644 --- a/backend/app/services/shipping_notice/intake_service.py +++ b/backend/app/services/shipping_notice/intake_service.py @@ -127,6 +127,7 @@ def _lean_parse_summary(structured: dict[str, Any] | None) -> dict[str, Any]: if email.get('stored_body_text_length') is not None else len(str(email.get('body_text') or '')) ), + 'body_html_table_count': len(email.get('body_html_tables') or []), } out['email'] = lean_email attachments = out.get('attachments') @@ -145,6 +146,9 @@ def _lean_parse_summary(structured: dict[str, Any] | None) -> dict[str, Any]: 'text_length': item.get('text_length'), 'stored_text_length': item.get('stored_text_length'), 'warnings': list(item.get('warnings') or []), + 'ready_for_extraction': bool(item.get('ready_for_extraction')), + 'is_inline_resource': bool(item.get('is_inline_resource')), + 'catalog_reason': item.get('catalog_reason'), } if item.get('asset_no'): row['asset_no'] = item.get('asset_no') @@ -192,6 +196,7 @@ def serialize_intake( 'intake_no': intake.intake_no, 'asset_no': asset.asset_no if asset else None, 'conversation_id': intake.conversation_id, + 'upload_batch_id': intake.upload_batch_id, 'parse_status': intake.parse_status, 'parser_version': intake.parser_version, 'order_extraction_status': intake.order_extraction_status, @@ -326,6 +331,7 @@ def create_shipping_notice_intake( user_id: int, asset_no: str, conversation_id: str | None = None, + upload_batch_id: str | None = None, ) -> dict[str, Any]: """ 基于已上传 FileAsset 创建接入记录并投递解析 Job。 @@ -339,7 +345,7 @@ def create_shipping_notice_intake( """ return _create_intake_for_asset( user_id=user_id, asset_no=asset_no, purpose='shipping_notice', - conversation_id=conversation_id, + conversation_id=conversation_id, upload_batch_id=upload_batch_id, ) @@ -352,12 +358,13 @@ def create_order_document_profile_sample_intake(*, user_id: int, asset_no: str) """ return _create_intake_for_asset( user_id=user_id, asset_no=asset_no, purpose=ORDER_DOCUMENT_PROFILE_SAMPLE_PURPOSE, - conversation_id=None, + conversation_id=None, upload_batch_id=None, ) def _create_intake_for_asset( *, user_id: int, asset_no: str, purpose: str, conversation_id: str | None, + upload_batch_id: str | None, ) -> dict[str, Any]: """按受控 purpose 创建幂等 Intake;模板样本与业务发货通知共享基础设施但隔离用途。""" asset = get_asset_for_user(asset_no, user_id) @@ -368,6 +375,9 @@ def _create_intake_for_asset( parser_version = _parser_version() conv = str(conversation_id or '').strip() or None + provided_batch_id = str(upload_batch_id or '').strip() + # Workspace API 强制提供批次;服务层保留内部调用的隔离默认值。 + batch_id = provided_batch_id or str(uuid.uuid4()) if purpose == ORDER_DOCUMENT_PROFILE_SAMPLE_PURPOSE: extension = str(asset.extension or '').strip().lower() if extension not in {'pdf', 'eml'}: @@ -388,6 +398,7 @@ def _create_intake_for_asset( asset_id=int(asset.id), user_id=int(user_id), conversation_id=conv, + upload_batch_id=batch_id or str(uuid.uuid4()), purpose=purpose, parse_status='created', parser_version=parser_version, @@ -408,6 +419,13 @@ def _create_intake_for_asset( if intake is None: raise + if purpose == 'shipping_notice' and provided_batch_id and intake.upload_batch_id != batch_id: + db.session.rollback() + raise ConflictError( + code='SHIPPING_NOTICE.UPLOAD_BATCH_MISMATCH', + message='Uploaded asset already belongs to another input batch', + ) + # [STEP 2] 终态 / 已在飞 / 禁止复活 status_now = str(intake.parse_status or '') if status_now in {'parsed', 'consumed', 'queued', 'parsing'}: diff --git a/backend/app/services/shipping_notice/notice_upload.py b/backend/app/services/shipping_notice/notice_upload.py index d077a708..d234bb88 100644 --- a/backend/app/services/shipping_notice/notice_upload.py +++ b/backend/app/services/shipping_notice/notice_upload.py @@ -149,16 +149,21 @@ def extract_notice_text( file_path: Path, *, retain_payloads: bool = False, + eml_attachment_mode: Literal["deep", "preview"] = "deep", + preview_only: bool = False, ) -> tuple[str, dict[str, Any]]: """ 从发货通知附件抽取纯文本(PDF/DOCX/CSV/图片 OCR/EML/HTML 等)。 - 核心逻辑:普通文件走 edkb loaders;.eml 委托 eml_parse 做结构化解析(元数据 + 真实附件独立抽取), - 内嵌 Logo/签名图不进入附件列表,也不参与订单文本拼接。 + 核心逻辑:普通文件走 edkb loaders;.eml 委托 eml_parse 做结构化解析。 + `deep` 模式递归抽取附件文本,`preview` 模式仅保留邮件头/正文/附件目录。 + 非 EML 的 `preview_only` 只返回文件元信息,避免上传阶段触发 Loader 或 OCR。 Args: file_path: 已落盘的通知文件路径。 retain_payloads: 仅 EML;True 时保留 attachments[*]._payload_bytes 供 Intake 派生资产。 + eml_attachment_mode: `preview` 仅生成附件目录;`deep` 递归抽取附件文本。 + preview_only: True 时普通文件不执行文本/OCR 抽取,留待发送后的深度识别阶段。 Returns: tuple[str, dict]: (抽取文本, meta 含 warnings、file_type;eml 另含 email/attachments/attachment_count)。 @@ -168,6 +173,13 @@ def extract_notice_text( ctx = Context(file_type=ext) warnings: list[str] = [] + if preview_only and ext != "eml": + return "", { + "warnings": warnings, + "file_type": ext, + "content_mode": "preview", + } + if ext in {"txt", "md", "log"}: return _decode_text(path.read_bytes()).strip(), {"warnings": warnings, "file_type": ext} if ext in {"html", "htm"}: @@ -178,6 +190,7 @@ def extract_notice_text( path.read_bytes(), extract_text=extract_notice_text, retain_payloads=retain_payloads, + attachment_mode=eml_attachment_mode, ) blocks: list[Block] = [] @@ -325,6 +338,7 @@ def intake_notice_attachment( task_no: str | None = None, temp_request_id: str | None = None, temp_index: int = 1, + eml_attachment_mode: Literal["deep", "preview"] = "preview", ) -> NoticeIntakeResult: """ 单份发货通知附件的统一接入:落盘 → 抽取 → 截断 → 失败分流。 @@ -339,6 +353,7 @@ def intake_notice_attachment( task_no: storage=task 时必填。 temp_request_id: storage=temp 时必填。 temp_index: storage=temp 时文件序号,避免同名覆盖。 + eml_attachment_mode: EML 上传模式;`preview` 仅保留附件目录,适合输入栏快览。 Returns: NoticeIntakeResult: 含 accepted / empty_text / extract_failed 状态与截断后正文。 @@ -363,7 +378,7 @@ def intake_notice_attachment( if not temp_request_id: raise ValueError("temp_request_id is required for temp storage") saved_path = save_temp_notice_upload(temp_request_id, temp_index, name, raw_bytes) - text, meta = extract_notice_text(saved_path) + text, meta = extract_notice_text(saved_path, eml_attachment_mode=eml_attachment_mode) warnings = list(meta.get("warnings") or []) if isinstance(meta, dict) else [] except Exception as exc: warnings = [f"notice_extract_failed:{exc}"] @@ -381,7 +396,17 @@ def intake_notice_attachment( saved_path=saved_path, ) - if not str(text or "").strip(): + preview_accept_without_text = ( + isinstance(meta, dict) + and str(meta.get("file_type") or "").lower() == "eml" + and str(meta.get("eml_attachment_mode") or "").lower() == "preview" + and ( + bool(meta.get("attachment_count")) + or bool(meta.get("attachments")) + or bool(meta.get("email")) + ) + ) + if not str(text or "").strip() and not preview_accept_without_text: return NoticeIntakeResult( filename=name, source_type=source_type, diff --git a/backend/app/services/shipping_notice/order_auto_freeze_execution.py b/backend/app/services/shipping_notice/order_auto_freeze_execution.py new file mode 100644 index 00000000..5aa7abee --- /dev/null +++ b/backend/app/services/shipping_notice/order_auto_freeze_execution.py @@ -0,0 +1,309 @@ +""" +services/shipping_notice/order_auto_freeze_execution.py + +用途:消费 Run 级自动冻结门禁摘要,把当前 Run 已接受的候选订单落成 Task 并冻结为 Snapshot。 +依赖:Run/Candidate/Task 模型、候选建批编排与订单冻结服务。 +逻辑:只有当 run.auto_freeze_policy_json 已明确放行时才执行;执行范围严格限定在当前 Run, + 且只创建/冻结本轮 accepted + selected 的候选,不触碰库存、Excel 或外部上传链路。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app import db +from app.models import ( + ShippingNoticeCandidate, + ShippingOrderCustomerMatch, + ShippingOrderExtraction, + ShippingOrderExtractionRun, + ShippingTask, +) +from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates +from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot + + +def maybe_execute_run_auto_freeze( + *, + run: ShippingOrderExtractionRun, + submission_result: dict[str, Any], +) -> dict[str, Any]: + """在门禁已放行时消费当前 Run 的 accepted Candidate,并自动冻结其新建任务。""" + result = dict(submission_result or {}) + policy = run.auto_freeze_policy_json if isinstance(run.auto_freeze_policy_json, dict) else {} + if not bool(policy.get('enabled')): + return result + + candidate_nos = _eligible_candidate_nos(run) + create_result: dict[str, Any] | None = None + if candidate_nos: + create_result = create_shipping_batch_from_candidates( + user_id=int(run.user_id), + conversation_id=run.conversation_id, + intake_nos=_snapshot_intake_nos(run), + candidate_nos=candidate_nos, + create_idempotency_key=f"extract:{str(run.input_snapshot_hash or '')[:48]}", + ) + + frozen_task_nos, blocked_tasks = _freeze_created_tasks(run=run, policy=policy) + refreshed = _refresh_submission_result( + run=run, + previous_result=result, + create_result=create_result, + ) + refreshed['auto_freeze'] = { + 'enabled': True, + 'frozen_task_nos': frozen_task_nos, + 'blocked_tasks': blocked_tasks, + } + return refreshed + + +def _eligible_candidate_nos(run: ShippingOrderExtractionRun) -> list[str]: + """只返回当前 Run 中可以自动建单的 accepted + selected 候选。""" + rows = ( + ShippingNoticeCandidate.query + .filter_by( + order_extraction_run_id=int(run.id), + is_current_version=True, + candidate_status='accepted', + selected=True, + ) + .filter(ShippingNoticeCandidate.consumed_task_id.is_(None)) + .order_by(ShippingNoticeCandidate.id.asc()) + .all() + ) + return [str(item.candidate_no) for item in rows if str(item.candidate_no or '').strip()] + + +def _snapshot_intake_nos(run: ShippingOrderExtractionRun) -> list[str]: + """从 Run 冻结快照提取 Intake 编号,确保自动消费范围不越过本轮输入。""" + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else [] + return [ + str(item.get('intake_no') or '').strip().upper() + for item in intakes + if isinstance(item, dict) and str(item.get('intake_no') or '').strip() + ] + + +def _freeze_created_tasks( + *, + run: ShippingOrderExtractionRun, + policy: dict[str, Any], +) -> tuple[list[str], list[dict[str, Any]]]: + """冻结当前 Run 已建出的任务;任一任务阻断时只保留 fail-closed 事实。""" + candidates = ( + ShippingNoticeCandidate.query + .filter_by(order_extraction_run_id=int(run.id), is_current_version=True) + .filter(ShippingNoticeCandidate.consumed_task_id.isnot(None)) + .order_by(ShippingNoticeCandidate.id.asc()) + .all() + ) + frozen_task_nos: list[str] = [] + blocked_tasks: list[dict[str, Any]] = [] + for candidate in candidates: + if str(candidate.duplicate_resolution or '').strip().lower() == 'open_existing': + continue + task = db.session.get(ShippingTask, int(candidate.consumed_task_id or 0)) + if task is None: + continue + _inherit_confirmed_ordering_customer(run=run, task=task, policy=policy) + try: + snapshot = freeze_order_snapshot( + task, + actor_id=None, + expected_order_data_version=int(task.order_data_version or 1), + freeze_mode='auto', + auto_freeze_policy=policy, + ) + frozen_task_nos.append(str(task.task_no or f"snapshot-{snapshot.id}")) + except Exception as exc: # pragma: no cover - 阻断明细由调用侧测试断言 + blocked_tasks.append({ + 'candidate_no': str(candidate.candidate_no or ''), + 'task_no': str(task.task_no or ''), + 'code': str(getattr(exc, 'code', '') or ''), + 'message': str(exc), + 'details': getattr(exc, 'details', None), + }) + return frozen_task_nos, blocked_tasks + + +def _inherit_confirmed_ordering_customer( + *, + run: ShippingOrderExtractionRun, + task: ShippingTask, + policy: dict[str, Any], +) -> None: + """把 Run 已确认的唯一 Bill-to 客户补写到当前任务 Extraction,供自动冻结门禁复用。""" + confirmed_ids = sorted({ + int(item) + for item in (policy.get('confirmed_customer_ids') or []) + if str(item).strip().isdigit() + }) + if len(confirmed_ids) != 1 or not task.current_order_extraction_id: + return + extraction = db.session.get(ShippingOrderExtraction, int(task.current_order_extraction_id)) + if extraction is None: + return + target = ShippingOrderCustomerMatch.query.filter_by( + extraction_id=int(extraction.id), + role='bill_to', + ).one_or_none() + if ( + target is not None + and target.status == 'confirmed' + and int(target.customer_id or 0) == confirmed_ids[0] + and bool(target.customer_short_code_snapshot) + and bool(target.identity_fingerprint) + and bool(target.identity_rule_version) + ): + return + if target is not None and target.status == 'confirmed' and target.customer_id not in {None, confirmed_ids[0]}: + return + source = ( + ShippingOrderCustomerMatch.query + .join(ShippingOrderExtraction, ShippingOrderExtraction.id == ShippingOrderCustomerMatch.extraction_id) + .filter( + ShippingOrderExtraction.run_id == int(run.id), + ShippingOrderCustomerMatch.role == 'bill_to', + ShippingOrderCustomerMatch.status == 'confirmed', + ShippingOrderCustomerMatch.customer_id == confirmed_ids[0], + ) + .order_by(ShippingOrderCustomerMatch.confirmed_at.desc(), ShippingOrderCustomerMatch.id.desc()) + .first() + ) + if source is None: + return + if target is None: + target = ShippingOrderCustomerMatch( + extraction_id=int(extraction.id), + role='bill_to', + identity_components_json={}, + candidates_json=[], + ) + db.session.add(target) + target.raw_name = source.raw_name + target.normalized_name = source.normalized_name + target.source_system = source.source_system + target.external_code = source.external_code + target.identity_fingerprint = source.identity_fingerprint + target.identity_rule_version = source.identity_rule_version + target.identity_components_json = dict(source.identity_components_json or {}) + target.status = 'confirmed' + target.customer_id = source.customer_id + target.site_id = source.site_id + target.customer_name_snapshot = source.customer_name_snapshot + target.customer_short_code_snapshot = source.customer_short_code_snapshot + target.candidates_json = list(source.candidates_json or []) + target.resolution_method = source.resolution_method or 'run_auto_freeze_inherited' + target.confirmation_reason = source.confirmation_reason or 'run_auto_freeze_inherited' + target.confirmed_by_id = source.confirmed_by_id + target.confirmed_at = source.confirmed_at or datetime.utcnow() + target.updated_at = datetime.utcnow() + db.session.flush() + + +def _refresh_submission_result( + *, + run: ShippingOrderExtractionRun, + previous_result: dict[str, Any], + create_result: dict[str, Any] | None, +) -> dict[str, Any]: + """按当前 Run 持久化事实重建摘要,确保自动建单后 created/pending 计数可恢复。""" + candidates = ( + ShippingNoticeCandidate.query + .filter_by(order_extraction_run_id=int(run.id), is_current_version=True) + .order_by(ShippingNoticeCandidate.id.asc()) + .all() + ) + pending_by_candidate_no = { + str(item.get('candidate_no') or ''): item + for item in previous_result.get('pending_orders') or [] + if isinstance(item, dict) and str(item.get('candidate_no') or '').strip() + } + created: list[dict[str, Any]] = [] + opened_existing: list[dict[str, Any]] = [] + pending_orders: list[dict[str, Any]] = [] + created_with_missing_fields_count = 0 + for candidate in candidates: + if candidate.consumed_task_id is None: + pending_item = pending_by_candidate_no.get(str(candidate.candidate_no or '')) + if pending_item is not None: + pending_orders.append(pending_item) + continue + task = db.session.get(ShippingTask, int(candidate.consumed_task_id)) + if task is None: + continue + if str(candidate.duplicate_resolution or '').strip().lower() == 'open_existing': + opened_existing.append({ + 'candidate_no': candidate.candidate_no, + 'task_no': task.task_no, + 'batch_no': None, + }) + continue + created.append({'task_no': task.task_no}) + if candidate.missing_fields_json: + created_with_missing_fields_count += 1 + created_with_missing_fields_count = min(created_with_missing_fields_count, len(created)) + non_shipping_orders = list(previous_result.get('non_shipping_orders') or []) + refreshed = { + 'status': 'ok', + 'request_id': str(run.run_no), + 'batch_no': ( + create_result.get('batch_no') + if isinstance(create_result, dict) and create_result.get('batch_no') + else previous_result.get('batch_no') + ), + 'created': created, + 'opened_existing': opened_existing, + 'pending_orders': pending_orders, + 'non_shipping_orders': non_shipping_orders, + 'created_count': len(created), + 'opened_existing_count': len(opened_existing), + 'pending_count': len(pending_orders), + 'non_shipping_count': len(non_shipping_orders), + 'created_with_missing_fields_count': created_with_missing_fields_count, + } + refreshed['message'] = _build_submission_message( + created_count=refreshed['created_count'], + opened_existing_count=refreshed['opened_existing_count'], + pending_count=refreshed['pending_count'], + non_shipping_count=refreshed['non_shipping_count'], + created_with_missing_fields_count=created_with_missing_fields_count, + ) + return refreshed + + +def _build_submission_message( + *, + created_count: int, + opened_existing_count: int, + pending_count: int, + non_shipping_count: int, + created_with_missing_fields_count: int, +) -> str: + """生成自动冻结执行后的统一结果摘要,保持与订单抽取主链路文案一致。""" + if not created_count and not opened_existing_count and not pending_count: + if non_shipping_count: + return f'未识别到需要处理的发货订单,已忽略 {non_shipping_count} 项非发货内容;本次未创建任务。' + return '未识别到发货订单,本次未创建任务。' + + parts: list[str] = [] + if created_count: + parts.append(f'已创建 {created_count} 个发货任务') + if opened_existing_count: + parts.append(f'已打开 {opened_existing_count} 个已有任务') + if pending_count: + prefix = '另有' if parts else '有' + parts.append(f'{prefix} {pending_count} 个订单需要补充信息或处理冲突') + if non_shipping_count: + parts.append(f'已忽略 {non_shipping_count} 项非发货内容') + message = ';'.join(parts) + '。' + if created_with_missing_fields_count: + message += ( + f'其中 {created_with_missing_fields_count} 个新建任务仍缺少 Reservation ID,' + '可通过自然对话补充。' + ) + return message diff --git a/backend/app/services/shipping_notice/order_auto_freeze_policy.py b/backend/app/services/shipping_notice/order_auto_freeze_policy.py new file mode 100644 index 00000000..a0c5429a --- /dev/null +++ b/backend/app/services/shipping_notice/order_auto_freeze_policy.py @@ -0,0 +1,255 @@ +""" +services/shipping_notice/order_auto_freeze_policy.py + +用途:统一生成订单抽取 Run 的自动冻结门禁摘要,不让各处各自拼 policy JSON。 +依赖:Run/Unit/RouteDecision/Qualification 模型;只读取脱敏事实,不触碰履约副作用。 +逻辑:Run 创建时冻结初始人工确认策略;结果落库后按模板资格、技术失败、预算停止和复核状态刷新门禁摘要。 +""" + +from __future__ import annotations + +from typing import Any + +from app.models import ( + ShippingDocumentProfileAutoFreezeQualification, + ShippingOrderCustomerMatch, + ShippingOrderExtraction, + ShippingOrderExtractionProgressEvent, + ShippingOrderExtractionRouteDecision, + ShippingOrderExtractionRun, +) + +_DEFAULT_BUSINESS_SCENARIO = 'shipping_notice_order' + + +def build_initial_auto_freeze_policy(*, schema_policy_version: str | None) -> dict[str, Any]: + """创建 Run 时冻结首版自动冻结策略,默认仅允许人工确认。""" + return { + 'mode': 'manual_confirmation', + 'enabled': False, + 'schema_policy_version': schema_policy_version, + } + + +def evaluate_run_auto_freeze_policy( + *, + run: ShippingOrderExtractionRun, + submission_result: dict[str, Any] | None = None, +) -> dict[str, Any]: + """按 Run 已知事实计算自动冻结门禁摘要,并消费模板资格里的客户/场景授权范围。""" + current = dict(run.auto_freeze_policy_json or {}) + policy = build_initial_auto_freeze_policy( + schema_policy_version=str(current.get('schema_policy_version') or '') or None, + ) + approved_routes = _approved_routes(run) + qualification = None + selected_route = None + blocking_reason_codes: list[str] = [] + confirmed_customer_ids: list[int] = [] + customer_scope_status = 'unconfigured' + current_business_scenario = _DEFAULT_BUSINESS_SCENARIO + business_scenario_status = 'unconfigured' + requires_customer_confirmation = True + + if not approved_routes: + blocking_reason_codes.append('profile_not_auto_freeze_approved') + elif len({ + (int(route.selected_profile_id or 0), str(route.selected_profile_checksum or '')) + for route in approved_routes + if route.selected_profile_id + }) > 1: + blocking_reason_codes.append('multiple_profiles_detected') + else: + selected_route = approved_routes[-1] + qualification = _qualification_for_route(selected_route) + if qualification is None: + blocking_reason_codes.append('profile_auto_freeze_qualification_missing') + elif str(qualification.status or '') == 'manual_confirmation': + blocking_reason_codes.append('profile_manual_confirmation_required') + elif str(qualification.status or '') == 'auto_freeze_suspended': + blocking_reason_codes.append('profile_auto_freeze_suspended') + confirmed_customer_ids = _confirmed_customer_ids(run) + customer_scope_status, customer_scope_reason_codes = _evaluate_customer_scope( + qualification=qualification, + confirmed_customer_ids=confirmed_customer_ids, + ) + blocking_reason_codes.extend(customer_scope_reason_codes) + business_scenario_status, business_scenario_reason_codes = _evaluate_business_scenario_scope( + qualification=qualification, + business_scenario=current_business_scenario, + ) + blocking_reason_codes.extend(business_scenario_reason_codes) + requires_customer_confirmation = bool( + qualification.requires_customer_confirmation + ) if qualification is not None else True + + if _has_technical_failure(run): + blocking_reason_codes.append('technical_failure_present') + if _has_review_required_unit(run): + # Worker 提交候选时 Run 仍可能处于 processing,不能等最终状态才阻断副作用。 + blocking_reason_codes.append('unit_review_required') + if _has_budget_stop(run): + blocking_reason_codes.append('budget_stopped') + if str(run.status or '') in {'review_required', 'partially_completed'}: + blocking_reason_codes.append('review_required') + if str(run.status or '') == 'failed': + blocking_reason_codes.append('run_failed') + if str(run.status or '') == 'cancelled': + blocking_reason_codes.append('run_cancelled') + if _has_blocking_pending_orders(submission_result): + blocking_reason_codes.append('pending_orders_present') + + enabled = bool( + qualification is not None + and str(qualification.status or '') == 'auto_freeze_approved' + and customer_scope_status == 'matched' + and business_scenario_status == 'matched' + and not requires_customer_confirmation + and not blocking_reason_codes + ) + + if requires_customer_confirmation: + blocking_reason_codes.append('customer_confirmation_required') + + policy.update({ + 'enabled': enabled, + 'selected_profile_id': int(selected_route.selected_profile_id) if selected_route and selected_route.selected_profile_id else None, + 'selected_profile_code': str(selected_route.selected_profile_code or '') or None if selected_route else None, + 'selected_profile_checksum': str(selected_route.selected_profile_checksum or '') or None if selected_route else None, + 'qualification_id': int(qualification.id) if qualification is not None else None, + 'qualification_status': str(qualification.status or '') if qualification is not None else None, + 'authorized_customer_ids': list(qualification.customer_ids_json or []) if qualification is not None else [], + 'confirmed_customer_ids': confirmed_customer_ids, + 'customer_scope_status': customer_scope_status, + 'authorized_business_scenarios': list(qualification.business_scenarios_json or []) if qualification is not None else [], + 'business_scenario': current_business_scenario, + 'business_scenario_status': business_scenario_status, + 'customer_confirmation_required': requires_customer_confirmation, + 'blocking_reason_codes': sorted(set(code for code in blocking_reason_codes if code)), + 'evaluated_from_run': True, + }) + return policy + + +def _approved_routes(run: ShippingOrderExtractionRun) -> list[ShippingOrderExtractionRouteDecision]: + """只返回声明可自动冻结模板命中的分流决策。""" + return [ + route for route in (run.route_decisions or []) + if bool(route.auto_create_approved) and route.selected_profile_id + ] + + +def _qualification_for_route( + route: ShippingOrderExtractionRouteDecision, +) -> ShippingDocumentProfileAutoFreezeQualification | None: + """按命中的模板版本读取当前资格状态;缺失时按 fail-closed 处理。""" + return ShippingDocumentProfileAutoFreezeQualification.query.filter_by( + profile_id=int(route.selected_profile_id), + profile_checksum=str(route.selected_profile_checksum or ''), + ).one_or_none() + + +def _confirmed_customer_ids(run: ShippingOrderExtractionRun) -> list[int]: + """读取本轮已确认的 Bill-to 客户;跨订单多客户时必须维持 fail-closed。""" + rows = ( + ShippingOrderCustomerMatch.query + .join(ShippingOrderExtraction, ShippingOrderExtraction.id == ShippingOrderCustomerMatch.extraction_id) + .filter( + ShippingOrderExtraction.run_id == int(run.id), + ShippingOrderCustomerMatch.role == 'bill_to', + ShippingOrderCustomerMatch.status == 'confirmed', + ShippingOrderCustomerMatch.customer_id.isnot(None), + ) + .all() + ) + return sorted({int(row.customer_id) for row in rows if row.customer_id is not None}) + + +def _evaluate_customer_scope( + *, + qualification: ShippingDocumentProfileAutoFreezeQualification | None, + confirmed_customer_ids: list[int], +) -> tuple[str, list[str]]: + """根据资格白名单和 Run 已确认客户判断当前客户授权状态。""" + if qualification is None: + return 'unconfigured', [] + configured_ids = [int(item) for item in (qualification.customer_ids_json or [])] + if not configured_ids: + return 'unconfigured', ['customer_scope_not_configured'] + if not confirmed_customer_ids: + return 'customer_unconfirmed', ['customer_confirmation_required'] + if len(confirmed_customer_ids) > 1: + return 'ambiguous', ['multiple_customers_detected'] + if int(confirmed_customer_ids[0]) not in set(configured_ids): + return 'out_of_scope', ['customer_scope_out_of_scope'] + return 'matched', [] + + +def _evaluate_business_scenario_scope( + *, + qualification: ShippingDocumentProfileAutoFreezeQualification | None, + business_scenario: str, +) -> tuple[str, list[str]]: + """根据资格白名单判断当前 Run 所属业务场景是否允许自动冻结。""" + if qualification is None: + return 'unconfigured', [] + configured = [ + str(item or '').strip().lower() + for item in (qualification.business_scenarios_json or []) + if str(item or '').strip() + ] + if not configured: + return 'unconfigured', ['business_scenario_not_configured'] + if str(business_scenario or '').strip().lower() not in set(configured): + return 'out_of_scope', ['business_scenario_out_of_scope'] + return 'matched', [] + + +def _has_technical_failure(run: ShippingOrderExtractionRun) -> bool: + """任一单元技术失败或技术失败事件均阻断自动冻结。""" + units = (run.extraction_plan.units if run.extraction_plan is not None else []) + if any(str(unit.technical_failure_reason_code or '').strip() for unit in units): + return True + return ShippingOrderExtractionProgressEvent.query.filter_by( + run_id=int(run.id), + event_code='technical_failed', + ).first() is not None + + +def _has_review_required_unit(run: ShippingOrderExtractionRun) -> bool: + """任一 Unit 已要求人工复核时,禁止其余订单绕过整体 Run 门禁自动冻结。""" + units = run.extraction_plan.units if run.extraction_plan is not None else [] + return any(str(unit.status or '') == 'review_required' for unit in units) + + +def _has_budget_stop(run: ShippingOrderExtractionRun) -> bool: + """预算停止事件是自动冻结硬阻断。""" + return ShippingOrderExtractionProgressEvent.query.filter_by( + run_id=int(run.id), + event_code='budget_stopped', + ).first() is not None + + +def _has_blocking_pending_orders(submission_result: dict[str, Any] | None) -> bool: + """ + 判断提交结果中的待处理订单是否属于真实阻断。 + + AI 触发时机:阶段 5 需要区分“业务上仍待复核的 pending”与“已 accepted、仅等待自动消费为 Task 的 pending”。 + 后者不会携带原因码或缺字段清单,不应把本应放行的自动冻结继续卡死在 pending_count 上。 + """ + if not isinstance(submission_result, dict): + return False + pending_orders = submission_result.get('pending_orders') + if not isinstance(pending_orders, list): + return int(submission_result.get('pending_count') or 0) > 0 + if not pending_orders: + return False + for item in pending_orders: + if not isinstance(item, dict): + return True + reasons = [str(code) for code in item.get('reasons') or [] if str(code).strip()] + missing_fields = [str(code) for code in item.get('missing_fields') or [] if str(code).strip()] + duplicate_status = str(item.get('duplicate_status') or '').strip().lower() + if reasons or missing_fields or duplicate_status not in {'', 'none'}: + return True + return False diff --git a/backend/app/services/shipping_notice/order_document_profile_service.py b/backend/app/services/shipping_notice/order_document_profile_service.py index dfa30dab..5069967c 100644 --- a/backend/app/services/shipping_notice/order_document_profile_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_service.py @@ -57,6 +57,7 @@ from app.services.shipping_notice.order_schema.compatibility import ( remap_profile_field_codes, ) from app.services.shipping_notice.document_layout.order_profile_extractors import registered_extractor_output_codes +from app.services.shipping_notice.preview_grant_store import preview_grant_store PROFILE_CODE_PATTERN = re.compile(r'^[A-Z0-9][A-Z0-9_-]{1,63}$') @@ -141,16 +142,8 @@ def _bound_sample_document(profile_id: int, document_id: int) -> ShippingNoticeD def _preview_grant_store() -> Any: - """取得预览令牌 Redis;多 Worker 下必须可原子消费,连接不可用时拒绝预览。""" - from app.services.redis_client import get_redis_client - - client = get_redis_client() - if client is None: - raise ServiceUnavailableError( - 'Order profile preview is temporarily unavailable', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE', - ) - return client + """取得预览令牌存储;生产强依赖 Redis,开发环境可显式启用单进程兜底。""" + return preview_grant_store() def _schema_fields(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, Any]]: diff --git a/backend/app/services/shipping_notice/order_extraction.py b/backend/app/services/shipping_notice/order_extraction.py index 5ac4dd11..79e19cc9 100644 --- a/backend/app/services/shipping_notice/order_extraction.py +++ b/backend/app/services/shipping_notice/order_extraction.py @@ -33,6 +33,8 @@ from app.services.shipping_notice.business_fingerprint import ( build_business_fingerprint, build_content_fingerprint, ) +from app.services.shipping_notice.order_auto_freeze_policy import evaluate_run_auto_freeze_policy +from app.services.shipping_notice.order_auto_freeze_execution import maybe_execute_run_auto_freeze from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary from app.services.shipping_notice.duplicate_detection import ( aggregate_intake_duplicate_from_candidates, @@ -99,6 +101,26 @@ def _order_extraction_submission(intake: ShippingNoticeIntake) -> dict[str, Any] return submission if isinstance(submission, dict) else {} +def _store_run_submission_result( + *, + intakes: list[ShippingNoticeIntake], + snapshot_hash: str, + request_id: str, + result: dict[str, Any], +) -> None: + """把最新 Run 提交结果回写到 Intake,确保自动冻结后的 created/pending 摘要可重放。""" + for intake in intakes: + structured = dict(intake.structured_result_json or {}) + structured['order_extraction_submission'] = { + 'input_snapshot_hash': snapshot_hash, + 'request_id': request_id, + 'result': result, + 'submitted_at': datetime.utcnow().isoformat(), + } + intake.structured_result_json = structured + flag_modified(intake, 'structured_result_json') + + def _float(value: Any, default: float = 0.0) -> float: """将 LLM 置信度规范为 0..1 浮点数。""" try: @@ -188,6 +210,7 @@ def persist_order_extraction_result( frozen_layout_candidates_by_document: dict[int, list[dict[str, Any]]] | None = None, frozen_evidence_text_by_document: dict[int, str] | None = None, auto_create_enabled: bool = False, + allow_orphaned_consumed_reparse: bool = False, ) -> dict[str, Any]: """ 持久化后台订单抽取 Run 的结构化结果,并执行后端裁决、判重与自动建单。 @@ -235,7 +258,16 @@ def persist_order_extraction_result( replay = dict(replay_results[0]) replay['idempotent_replay'] = True return replay - if any(row.parse_status == 'consumed' for row in intakes): + if any(row.parse_status == 'consumed' for row in intakes) and not ( + allow_orphaned_consumed_reparse + and all( + row.parse_status == 'consumed' + and row.consumed_at is not None + and row.consumed_task_id is None + and row.consumed_batch_id is None + for row in intakes + ) + ): raise ConflictError( code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING', message='已消费的 Intake 仅允许回放原订单抽取结果', @@ -756,21 +788,21 @@ def submit_order_extraction_run_result( if len(intakes) != len(intake_nos): raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='Run 输入 Intake 不完整') run_extractions = ShippingOrderExtraction.query.filter_by(run_id=int(run.id)).all() - if run_extractions and all( + run_candidates = ShippingNoticeCandidate.query.filter_by(order_extraction_run_id=int(run.id)).all() + if run_extractions and run_candidates and all( extraction.status in {'accepted', 'needs_review'} for extraction in run_extractions ): - candidates = ShippingNoticeCandidate.query.filter_by(order_extraction_run_id=int(run.id)).all() consumed_task_ids = { int(candidate.consumed_task_id) - for candidate in candidates + for candidate in run_candidates if candidate.consumed_task_id is not None } task_nos = sorted({ str(task.task_no) for task in ShippingTask.query.filter(ShippingTask.id.in_(consumed_task_ids)).all() }) if consumed_task_ids else [] - pending = [candidate for candidate in candidates if candidate.consumed_task_id is None] + pending = [candidate for candidate in run_candidates if candidate.consumed_task_id is None] result = { 'status': 'ok', 'request_id': str(run.run_no), @@ -787,16 +819,17 @@ def submit_order_extraction_run_result( 'idempotent_replay': True, 'recovered_from_run_facts': True, } - for intake in intakes: - structured = dict(intake.structured_result_json or {}) - structured['order_extraction_submission'] = { - 'input_snapshot_hash': run.input_snapshot_hash, - 'request_id': str(run.run_no), - 'result': result, - 'submitted_at': datetime.utcnow().isoformat(), - } - intake.structured_result_json = structured - flag_modified(intake, 'structured_result_json') + run.auto_freeze_policy_json = evaluate_run_auto_freeze_policy(run=run, submission_result=result) + flag_modified(run, 'auto_freeze_policy_json') + result = maybe_execute_run_auto_freeze(run=run, submission_result=result) + _store_run_submission_result( + intakes=intakes, + snapshot_hash=str(run.input_snapshot_hash), + request_id=str(run.run_no), + result=result, + ) + run.auto_freeze_policy_json = evaluate_run_auto_freeze_policy(run=run, submission_result=result) + flag_modified(run, 'auto_freeze_policy_json') db.session.commit() return result cached_orders = ( @@ -826,28 +859,41 @@ def submit_order_extraction_run_result( 'idempotent_replay': True, 'recovered_from_consumed_empty_result': True, } - for intake in intakes: - structured = dict(intake.structured_result_json or {}) - structured['order_extraction_submission'] = { - 'input_snapshot_hash': run.input_snapshot_hash, - 'request_id': str(run.run_no), - 'result': result, - 'submitted_at': datetime.utcnow().isoformat(), - } - intake.structured_result_json = structured - flag_modified(intake, 'structured_result_json') + run.auto_freeze_policy_json = evaluate_run_auto_freeze_policy(run=run, submission_result=result) + flag_modified(run, 'auto_freeze_policy_json') + result = maybe_execute_run_auto_freeze(run=run, submission_result=result) + _store_run_submission_result( + intakes=intakes, + snapshot_hash=str(run.input_snapshot_hash), + request_id=str(run.run_no), + result=result, + ) + run.auto_freeze_policy_json = evaluate_run_auto_freeze_policy(run=run, submission_result=result) + flag_modified(run, 'auto_freeze_policy_json') db.session.commit() return result is_replay = all( str(_order_extraction_submission(intake).get('request_id') or '') == str(run.run_no) for intake in intakes ) + # 重识别只可复用“曾被空结果误标 consumed、但未实际建单/建批”的 Intake。 + # 已绑定任务或批次的记录仍保持不可写,避免新版本覆盖真实业务结果。 + is_orphaned_reparse = ( + run.reparse_of_run_id is not None + and all( + intake.parse_status == 'consumed' + and intake.consumed_at is not None + and intake.consumed_task_id is None + and intake.consumed_batch_id is None + for intake in intakes + ) + ) session = db.session.query(ChatSession).filter_by(session_id=run.conversation_id).one() current_intakes = _load_intakes( session=session, intake_nos=intake_nos, lock=True, - allow_consumed=is_replay, + allow_consumed=is_replay or is_orphaned_reparse, ) current_documents = _load_documents(current_intakes, lock=True) current_intake_by_id = {int(item.id): item for item in current_intakes} @@ -876,7 +922,7 @@ def submit_order_extraction_run_result( code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED', message='Run 冻结后的邮件或附件内容已变化', ) - return persist_order_extraction_result( + result = persist_order_extraction_result( session=session, intakes=current_intakes, documents=current_documents, @@ -892,4 +938,18 @@ def submit_order_extraction_run_result( auto_create_enabled=bool( ((run.auto_freeze_policy_json or {}).get('enabled', False)) ), + allow_orphaned_consumed_reparse=is_orphaned_reparse, ) + run.auto_freeze_policy_json = evaluate_run_auto_freeze_policy(run=run, submission_result=result) + flag_modified(run, 'auto_freeze_policy_json') + result = maybe_execute_run_auto_freeze(run=run, submission_result=result) + _store_run_submission_result( + intakes=current_intakes, + snapshot_hash=str(run.input_snapshot_hash), + request_id=str(run.run_no), + result=result, + ) + run.auto_freeze_policy_json = evaluate_run_auto_freeze_policy(run=run, submission_result=result) + flag_modified(run, 'auto_freeze_policy_json') + db.session.commit() + return result diff --git a/backend/app/services/shipping_notice/order_extraction_materialization.py b/backend/app/services/shipping_notice/order_extraction_materialization.py new file mode 100644 index 00000000..eba93575 --- /dev/null +++ b/backend/app/services/shipping_notice/order_extraction_materialization.py @@ -0,0 +1,312 @@ +""" +services/shipping_notice/order_extraction_materialization.py + +用途:在点击发送后,按附件选择计划为 Run 物化本次真正需要的输入文档。 +依赖:ShippingNoticeIntake/FileAsset、notice_upload、document_candidate_persist、attachment_selection。 +逻辑:上传阶段保持快览轻量;发送阶段只为本次计划选中的附件和邮件正文创建 Document/派生资产, + 不把未选附件偷偷升级成可执行输入。 +""" + +from __future__ import annotations + +import tempfile +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +from flask import current_app + +from app import db +from app.core.errors import ConflictError +from app.models import FileAsset, ShippingNoticeDocument, ShippingNoticeIntake +from app.services.shipping_notice.attachment_selection import build_attachment_selection_snapshot +from app.services.shipping_notice.document_candidate_persist import persist_intake_documents +from app.services.shipping_notice.eml_parse import pop_attachment_payload +from app.services.shipping_notice.notice_upload import ( + NoticeIntakeResult, + extract_notice_text, +) +from app.services.shipping_notice.intake_parse_workflow import extract_notice_from_asset + + +def _existing_document_keys(intake: ShippingNoticeIntake) -> set[str]: + """返回当前 Intake 已落库文档键,供发送阶段判断是否需要补物化。""" + rows = ( + db.session.query(ShippingNoticeDocument.attachment_key) + .filter(ShippingNoticeDocument.intake_id == int(intake.id)) + .all() + ) + return {str(value or '').strip() for (value,) in rows if str(value or '').strip()} + + +def _selected_attachment_keys_for_intake( + *, + intake: ShippingNoticeIntake, + attachment_selection: dict[str, Any], + selection_batches: set[int] | None = None, +) -> set[str]: + """从计划摘要中取出某个 Intake 在指定批次内被授权深度解析的附件键。""" + normalized = str(intake.intake_no or '').strip().upper() + allowed_batches = {int(batch) for batch in (selection_batches or {1}) if int(batch) > 0} + selected: set[str] = set() + for row in attachment_selection.get('items') or []: + if not isinstance(row, dict): + continue + if str(row.get('intake_no') or '').strip().upper() != normalized: + continue + batch_no = int( + row.get('selection_batch') + or row.get('planned_selection_batch') + or 0 + ) + if batch_no not in allowed_batches: + continue + if batch_no == 1 and not row.get('selected'): + continue + key = str(row.get('attachment_key') or '').strip() + if key: + selected.add(key) + return selected + + +def _parse_attachment_payload( + *, payload: bytes, filename: str, mime_type: str, flask_app: Any | None = None, +) -> tuple[str, dict[str, Any]]: + """仅对选中的附件载荷做深度文本抽取;并发线程必须自建 Flask 上下文。""" + suffix = Path(str(filename or 'attachment')).suffix or '.bin' + with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp: + tmp.write(payload or b'') + tmp_path = Path(tmp.name) + try: + if flask_app is None: + return extract_notice_text(tmp_path) + with flask_app.app_context(): + return extract_notice_text(tmp_path) + finally: + try: + tmp_path.unlink(missing_ok=True) + except OSError: + pass + + +def _build_selected_eml_result( + *, + intake: ShippingNoticeIntake, + parent_asset: FileAsset, + selected_attachment_keys: set[str], + max_concurrency: int = 1, +) -> NoticeIntakeResult: + """ + 基于 preview 目录和载荷,只为本次选中的 EML 附件构造深度持久化输入。 + + 核心逻辑:先以 preview+retain_payloads 读取目录和原始二进制,再仅对 selected keys 深度抽取。 + """ + preview_result = extract_notice_from_asset( + parent_asset, + eml_attachment_mode='preview', + retain_payloads=True, + ) + if preview_result.status != 'accepted': + raise ConflictError( + 'Shipping notice preview is not ready for extraction', + code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', + details={'intake_nos': [str(intake.intake_no or '')]}, + ) + meta = dict(preview_result.meta or {}) if isinstance(preview_result.meta, dict) else {} + selected_rows: list[dict[str, Any]] = [] + parse_inputs: list[tuple[int, dict[str, Any], bytes]] = [] + for raw_item in meta.get('attachments') or []: + if not isinstance(raw_item, dict): + continue + item = dict(raw_item) + key = str(item.get('attachment_key') or '').strip() + payload = pop_attachment_payload(item) + if key not in selected_attachment_keys: + continue + warnings = [str(value) for value in (item.get('warnings') or [])] + if not payload: + item['parse_status'] = 'failed' + item['extracted_text'] = '' + item['warnings'] = [*warnings, 'selected_attachment_payload_missing'] + selected_rows.append(item) + continue + + parse_inputs.append((len(selected_rows), item, payload)) + selected_rows.append(item) + + flask_app = current_app._get_current_object() + + # 线程只处理附件字节和临时文件,禁止访问 ORM/Session;Document 写入仍在主线程串行收口。 + def parse_one(item: dict[str, Any], payload: bytes) -> tuple[str, dict[str, Any]]: + return _parse_attachment_payload( + payload=payload, + filename=str(item.get('filename') or item.get('attachment_key') or 'attachment'), + mime_type=str(item.get('mime_type') or 'application/octet-stream'), + flask_app=flask_app, + ) + + parsed: dict[int, tuple[str, dict[str, Any]]] = {} + worker_count = min(max(1, int(max_concurrency or 1)), len(parse_inputs)) + if worker_count > 1: + with ThreadPoolExecutor(max_workers=worker_count, thread_name_prefix='shipping-attachment-extract') as pool: + futures = { + index: pool.submit(parse_one, item, payload) + for index, item, payload in parse_inputs + } + for index, future in futures.items(): + parsed[index] = future.result() + else: + for index, item, payload in parse_inputs: + parsed[index] = parse_one(item, payload) + + for index, item, payload in parse_inputs: + text, attachment_meta = parsed[index] + warnings = [str(value) for value in (item.get('warnings') or [])] + attachment_warnings = [str(value) for value in (attachment_meta.get('warnings') or [])] + item['parse_status'] = 'parsed' if str(text or '').strip() else 'empty' + item['extracted_text'] = str(text or '') + item['warnings'] = [*warnings, *attachment_warnings] + item['_payload_bytes'] = payload + email_meta = meta.get('email') if isinstance(meta.get('email'), dict) else {} + return NoticeIntakeResult( + filename=str(parent_asset.original_filename or intake.intake_no or 'notice.eml'), + source_type='email', + source_file_type=parent_asset.mime_type, + text=str(preview_result.text or ''), + warnings=list(preview_result.warnings or []), + meta={ + 'file_type': 'eml', + 'eml_attachment_mode': 'deep', + 'warnings': list(preview_result.warnings or []), + 'email': { + 'message_id': email_meta.get('message_id') or '', + 'subject': email_meta.get('subject') or '', + 'from': email_meta.get('from') or '', + 'to': email_meta.get('to') or '', + 'date': email_meta.get('date') or '', + 'body_text': email_meta.get('body_text') or '', + 'body_html_tables': [str(item) for item in (email_meta.get('body_html_tables') or []) if str(item).strip()], + }, + 'attachments': selected_rows, + 'attachment_count': len(selected_rows), + 'attachment_registered_count': len(selected_rows), + }, + content_hash=str(parent_asset.content_hash or ''), + file_size=int(parent_asset.file_size or 0), + status='accepted', + saved_path=None, + ) + + +def _asset_read_snapshot(asset: FileAsset) -> SimpleNamespace: + """把线程所需的 Asset 字段复制为纯数据,禁止背景线程触碰主线程 ORM 实体。""" + return SimpleNamespace( + deleted_at=asset.deleted_at, + expires_at=asset.expires_at, + lifecycle_status=asset.lifecycle_status, + storage_key=str(asset.storage_key or ''), + original_filename=str(asset.original_filename or ''), + mime_type=asset.mime_type, + content_hash=str(asset.content_hash or ''), + file_size=int(asset.file_size or 0), + ) + + +def _build_single_file_result_in_thread(*, parent_asset: Any, flask_app: Any) -> NoticeIntakeResult: + """复用资产抽取入口在线程中处理普通文件;禁止访问 Session 或持久化任何 ORM 事实。""" + with flask_app.app_context(): + return extract_notice_from_asset(parent_asset, eml_attachment_mode='deep') + + +def ensure_order_extraction_input_documents( + *, + intakes: list[ShippingNoticeIntake], + attachment_selection: dict[str, Any], + schema_definition: dict[str, Any] | None = None, + selection_batches: set[int] | None = None, +) -> None: + """ + 在创建 Run 前,确保当前发送批次所需的输入文档已按计划物化。 + + AI 触发时机:点击发送后、冻结 Run 快照前使用。上传阶段禁止调用本函数。 + 核心逻辑: + 1. 普通单文件只物化唯一 `file` 文档; + 2. EML 只物化正文 + 当前授权批次的附件,不等待布局任务终态; + 3. 已满足本次计划的 Intake 不重复物化。 + """ + definition = dict(schema_definition or {}) + allowed_batches = {int(batch) for batch in (selection_batches or {1}) if int(batch) > 0} + max_concurrency = max(1, int(attachment_selection.get('max_initial_concurrency') or 1)) + normal_inputs: list[tuple[ShippingNoticeIntake, FileAsset]] = [] + eml_inputs: list[tuple[ShippingNoticeIntake, FileAsset, set[str]]] = [] + for intake in intakes: + parent_asset = db.session.get(FileAsset, int(intake.asset_id)) if intake.asset_id else None + if parent_asset is None: + raise ConflictError( + 'Shipping notice asset is unavailable', + code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', + details={'intake_nos': [str(intake.intake_no or '')], 'reason': 'parent_asset_missing'}, + ) + existing_keys = _existing_document_keys(intake) + source_name = str(parent_asset.original_filename or '') + is_eml = source_name.lower().endswith('.eml') or str(parent_asset.mime_type or '').lower() in {'message/rfc822', 'application/eml'} + if not is_eml: + if existing_keys == {'file'}: + continue + normal_inputs.append((intake, parent_asset)) + continue + + selected_attachment_keys = _selected_attachment_keys_for_intake( + intake=intake, + attachment_selection=attachment_selection, + selection_batches=allowed_batches, + ) + required_keys = {'body', *selected_attachment_keys} + if required_keys and required_keys.issubset(existing_keys): + continue + if not selected_attachment_keys: + raise ConflictError( + 'Shipping notice contains no eligible attachments for automatic extraction', + code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', + details={'intake_nos': [str(intake.intake_no or '')], 'reason': 'no_eligible_selected_attachment'}, + ) + eml_inputs.append((intake, parent_asset, selected_attachment_keys)) + + flask_app = current_app._get_current_object() + normal_results: dict[int, NoticeIntakeResult] = {} + if normal_inputs: + worker_count = min(max_concurrency, len(normal_inputs)) + with ThreadPoolExecutor(max_workers=worker_count, thread_name_prefix='shipping-file-extract') as pool: + futures = { + int(intake.id): pool.submit( + _build_single_file_result_in_thread, + parent_asset=_asset_read_snapshot(parent_asset), + flask_app=flask_app, + ) + for intake, parent_asset in normal_inputs + } + for intake_id, future in futures.items(): + normal_results[intake_id] = future.result() + + # 所有 Document / Candidate 写入继续在 Worker 主线程按输入顺序收口。 + for intake, parent_asset in normal_inputs: + persist_intake_documents( + intake=intake, + parent_asset=parent_asset, + result=normal_results[int(intake.id)], + schema_definition=definition, + ) + for intake, parent_asset, selected_attachment_keys in eml_inputs: + persist_intake_documents( + intake=intake, + parent_asset=parent_asset, + result=_build_selected_eml_result( + intake=intake, + parent_asset=parent_asset, + selected_attachment_keys=selected_attachment_keys, + # 每批最多两个附件;后续扩批仍按相同的安全上限执行。 + max_concurrency=max_concurrency, + ), + schema_definition=definition, + ) diff --git a/backend/app/services/shipping_notice/order_extraction_plan.py b/backend/app/services/shipping_notice/order_extraction_plan.py index 6ef61f15..fa2afdb6 100644 --- a/backend/app/services/shipping_notice/order_extraction_plan.py +++ b/backend/app/services/shipping_notice/order_extraction_plan.py @@ -8,6 +8,7 @@ services/shipping_notice/order_extraction_plan.py from __future__ import annotations +from collections import defaultdict from datetime import datetime from typing import Any @@ -15,6 +16,7 @@ from app import db from app.core.errors import ConflictError, ValidationError from app.models import ( ShippingOrderExtractionPlan, + ShippingNoticeDocument, ShippingOrderExtractionRun, ShippingOrderExtractionUnit, ) @@ -22,18 +24,78 @@ from app.models import ( PLAN_VERSION = 'shipping_order_extraction.plan.v1' UNIT_TRANSITIONS = { - 'pending': {'running', 'skipped'}, - 'running': {'succeeded', 'failed', 'skipped'}, + 'pending': {'routing', 'matching_profile', 'cancelled'}, + 'routing': {'matching_profile', 'review_required', 'failed', 'cancelled'}, + 'matching_profile': {'extracting', 'review_required', 'failed', 'cancelled'}, + 'extracting': {'merging_supplement', 'candidate_ready', 'review_required', 'failed', 'cancelled'}, + 'merging_supplement': {'candidate_ready', 'review_required', 'failed', 'cancelled'}, 'failed': {'pending'}, - 'succeeded': set(), - 'skipped': set(), + 'candidate_ready': set(), + 'review_required': set(), + 'cancelled': set(), } +def _selection_snapshot(run: ShippingOrderExtractionRun) -> dict[str, Any]: + """提取 Run 冻结的附件选择快照,供首轮与扩批复用。""" + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + return snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {} + + +def _selection_items(selection_snapshot: dict[str, Any]) -> list[dict[str, Any]]: + """返回可用的选择计划明细行。""" + items = selection_snapshot.get('items') if isinstance(selection_snapshot.get('items'), list) else [] + return [item for item in items if isinstance(item, dict)] + + +def _selection_row_batch(row: dict[str, Any]) -> int | None: + """统一读取首轮已选批次或后续计划批次。""" + batch = int(row.get('selection_batch') or row.get('planned_selection_batch') or 0) + return batch if batch > 0 else None + + +def _selection_batch_counts(selection_snapshot: dict[str, Any]) -> dict[int, int]: + """统计每个批次计划中的附件数量,供预算事实落入 unit。""" + counts: dict[int, int] = defaultdict(int) + for row in _selection_items(selection_snapshot): + batch = _selection_row_batch(row) + if batch is not None: + counts[batch] += 1 + return counts + + +def _unit_budget_cost( + *, + selection_snapshot: dict[str, Any], + selection_batch: int | None, + batch_counts: dict[int, int], +) -> dict[str, Any] | None: + """构造单元级预算摘要,保持首轮与扩展批次口径一致。""" + if selection_batch is None: + return None + return { + 'initial_attachment_budget': int(selection_snapshot.get('max_initial_attachments') or 0), + 'initial_concurrency_budget': int(selection_snapshot.get('max_initial_concurrency') or 0), + 'expansion_batch_size': int(selection_snapshot.get('expansion_batch_size') or 0), + 'max_total_attachments': int(selection_snapshot.get('max_total_attachments') or 0), + 'selected_in_batch': int(batch_counts.get(selection_batch, 0) or 0), + } + + def _snapshot_documents(run: ShippingOrderExtractionRun) -> list[dict[str, Any]]: """按冻结 Intake/Document 顺序展开计划输入,并校验必要引用完整。""" snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else [] + selection_snapshot = _selection_snapshot(run) + selection_items = _selection_items(selection_snapshot) + selection_by_key: dict[tuple[str, str], dict[str, Any]] = {} + selected_count_by_batch = _selection_batch_counts(selection_snapshot) + for row in selection_items: + intake_no = str(row.get('intake_no') or '').strip().upper() + attachment_key = str(row.get('attachment_key') or '').strip() + if not intake_no or not attachment_key: + continue + selection_by_key[(intake_no, attachment_key)] = row documents: list[dict[str, Any]] = [] for intake_position, intake in enumerate(intakes): if not isinstance(intake, dict): @@ -42,6 +104,7 @@ def _snapshot_documents(run: ShippingOrderExtractionRun) -> list[dict[str, Any]] code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE', ) intake_id = intake.get('intake_id') + intake_no = str(intake.get('intake_no') or '').strip().upper() raw_documents = intake.get('documents') if isinstance(intake.get('documents'), list) else [] for document_position, document in enumerate(raw_documents): if not isinstance(document, dict) or not intake_id or not document.get('document_id'): @@ -49,13 +112,27 @@ def _snapshot_documents(run: ShippingOrderExtractionRun) -> list[dict[str, Any]] 'Frozen extraction document reference is invalid', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE', ) + selection_row = selection_by_key.get( + (intake_no, str(document.get('attachment_key') or '').strip()), + {}, + ) + selection_batch = _selection_row_batch(selection_row) documents.append({ 'intake_id': int(intake_id), 'document_id': int(document['document_id']), 'document_type': str(document.get('document_type') or 'attachment'), + 'attachment_key': str(document.get('attachment_key') or '').strip() or None, 'content_hash': str(document.get('content_hash') or '') or None, 'intake_position': intake_position, 'document_position': document_position, + 'selection_batch': selection_batch, + 'selection_reason_codes': list(selection_row.get('score_reasons') or []), + 'group_key': str(selection_row.get('group_key') or '').strip() or None, + 'budget_cost': _unit_budget_cost( + selection_snapshot=selection_snapshot, + selection_batch=selection_batch, + batch_counts=selected_count_by_batch, + ), }) if not documents: raise ValidationError( @@ -65,6 +142,114 @@ def _snapshot_documents(run: ShippingOrderExtractionRun) -> list[dict[str, Any]] return documents +def _planned_selection_rows(run: ShippingOrderExtractionRun, *, selection_batch: int) -> list[dict[str, Any]]: + """读取某个未来批次在冻结选择计划中的附件明细。""" + normalized_batch = int(selection_batch or 0) + if normalized_batch <= 1: + return [] + rows: list[dict[str, Any]] = [] + for row in _selection_items(_selection_snapshot(run)): + if _selection_row_batch(row) != normalized_batch: + continue + intake_no = str(row.get('intake_no') or '').strip().upper() + attachment_key = str(row.get('attachment_key') or '').strip() + if not intake_no or not attachment_key: + continue + rows.append(row) + return rows + + +def ensure_order_extraction_plan_batch( + run: ShippingOrderExtractionRun, + *, + selection_batch: int, +) -> list[ShippingOrderExtractionUnit]: + """ + 幂等追加某个未来批次的附件单元。 + + AI 触发时机:仅在首轮处理后确认需要扩批,并且该批附件已完成发送阶段物化时调用。 + """ + normalized_batch = int(selection_batch or 0) + if normalized_batch <= 1: + return [] + plan = ensure_order_extraction_plan(run) + selection_rows = _planned_selection_rows(run, selection_batch=normalized_batch) + if not selection_rows: + return [] + + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + intake_id_by_no = { + str(item.get('intake_no') or '').strip().upper(): int(item.get('intake_id')) + for item in (snapshot.get('intakes') or []) + if isinstance(item, dict) and item.get('intake_id') + } + existing_document_ids = {int(unit.document_id) for unit in plan.units} + selection_snapshot = _selection_snapshot(run) + batch_counts = _selection_batch_counts(selection_snapshot) + keys_by_intake: dict[int, set[str]] = defaultdict(set) + ordered_pairs: list[tuple[int, str, dict[str, Any]]] = [] + for row in selection_rows: + intake_id = intake_id_by_no.get(str(row.get('intake_no') or '').strip().upper()) + attachment_key = str(row.get('attachment_key') or '').strip() + if intake_id is None or not attachment_key: + continue + keys_by_intake[intake_id].add(attachment_key) + ordered_pairs.append((intake_id, attachment_key, row)) + if not ordered_pairs: + return [] + + documents = ( + ShippingNoticeDocument.query + .filter(ShippingNoticeDocument.intake_id.in_(keys_by_intake.keys())) + .all() + ) + document_by_pair = { + (int(document.intake_id), str(document.attachment_key or '').strip()): document + for document in documents + if str(document.attachment_key or '').strip() in keys_by_intake.get(int(document.intake_id), set()) + } + next_position = max((int(unit.position) for unit in plan.units), default=-1) + 1 + created_units: list[ShippingOrderExtractionUnit] = [] + for intake_id, attachment_key, row in ordered_pairs: + document = document_by_pair.get((intake_id, attachment_key)) + if document is None: + raise ValidationError( + 'Frozen extraction attachment batch is unavailable', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE', + ) + if int(document.id) in existing_document_ids: + continue + unit = ShippingOrderExtractionUnit( + plan_id=plan.id, + intake_id=intake_id, + document_id=int(document.id), + position=next_position, + unit_type='document_extraction', + document_type=str(document.document_type or 'attachment'), + content_hash=str(document.content_hash or '') or None, + selection_batch=normalized_batch, + selection_reason_codes_json=list(row.get('score_reasons') or []) or None, + group_key=str(row.get('group_key') or '').strip() or None, + budget_cost_json=_unit_budget_cost( + selection_snapshot=selection_snapshot, + selection_batch=normalized_batch, + batch_counts=batch_counts, + ), + retry_status='not_started', + technical_failure_reason_code=None, + status='pending', + ) + db.session.add(unit) + created_units.append(unit) + existing_document_ids.add(int(document.id)) + next_position += 1 + if created_units: + db.session.flush() + plan.unit_count = len(plan.units) + _refresh_plan_status(plan) + return created_units + + def ensure_order_extraction_plan(run: ShippingOrderExtractionRun) -> ShippingOrderExtractionPlan: """ 幂等创建 Run 的文档级抽取计划。 @@ -113,6 +298,12 @@ def ensure_order_extraction_plan(run: ShippingOrderExtractionRun) -> ShippingOrd unit_type='document_extraction', document_type=document_type, content_hash=document['content_hash'], + selection_batch=document.get('selection_batch'), + selection_reason_codes_json=document.get('selection_reason_codes') or None, + group_key=document.get('group_key'), + budget_cost_json=document.get('budget_cost'), + retry_status='not_started', + technical_failure_reason_code=None, status='pending', )) db.session.flush() @@ -124,9 +315,9 @@ def _refresh_plan_status(plan: ShippingOrderExtractionPlan) -> None: statuses = [str(unit.status) for unit in plan.units] if not statuses or all(status == 'pending' for status in statuses): plan.status = 'planned' - elif any(status in {'pending', 'running'} for status in statuses): + elif any(status in {'pending', 'routing', 'matching_profile', 'extracting', 'merging_supplement'} for status in statuses): plan.status = 'running' - elif all(status in {'succeeded', 'skipped'} for status in statuses): + elif all(status in {'candidate_ready', 'review_required'} for status in statuses): plan.status = 'completed' elif all(status == 'failed' for status in statuses): plan.status = 'failed' @@ -143,13 +334,13 @@ def transition_order_extraction_unit( error_message: str | None = None, ) -> ShippingOrderExtractionUnit: """ - 单调推进一个文档单元并同步计划汇总状态。 + 单调推进一个附件单元并同步计划汇总状态。 Args: unit: 已加载且由调用方在事务内持有的计划单元。 - target_status: 当前状态允许的下一状态;`skipped` 表示业务复核,失败重试必须先回到 pending。 - result: 仅 succeeded 可写的结构化局部结果,不得包含正文或凭据。 - error_code/error_message: 仅 failed 可写的安全诊断摘要。 + target_status: 当前状态允许的下一状态;失败重试必须先回到 pending 再开启新 attempt。 + result: 仅 candidate_ready 可写的结构化局部结果,不得包含正文或凭据。 + error_code/error_message: review_required/failed/cancelled 可写的稳定原因摘要。 Returns: 已更新但尚未提交的单元。 """ @@ -164,32 +355,70 @@ def transition_order_extraction_unit( before_projection = {'status': current, 'attempt_count': int(unit.attempt_count or 0)} now = datetime.utcnow() unit.status = target_status - if target_status == 'running': + unit.last_activity_at = now + if target_status in {'routing', 'matching_profile'}: unit.attempt_count = int(unit.attempt_count or 0) + 1 - unit.started_at = now + unit.retry_status = 'retrying' if int(unit.attempt_count or 0) > 1 else 'running' + unit.started_at = unit.started_at or now unit.finished_at = None + unit.reason_code = None + unit.summary_json = None unit.result_json = None unit.error_code = None unit.error_message = None - elif target_status == 'succeeded': + unit.technical_failure_reason_code = None + elif target_status in {'extracting', 'merging_supplement'}: + unit.finished_at = None + unit.reason_code = None + unit.summary_json = dict(result or unit.summary_json or {}) + unit.error_code = None + unit.error_message = None + unit.retry_status = 'running' + unit.technical_failure_reason_code = None + elif target_status == 'candidate_ready': + unit.summary_json = dict(result or {}) unit.result_json = dict(result or {}) + unit.reason_code = None unit.error_code = None unit.error_message = None unit.finished_at = now + unit.retry_status = 'succeeded' + unit.technical_failure_reason_code = None + elif target_status == 'review_required': + unit.summary_json = dict(result or {}) + unit.result_json = None + unit.reason_code = str(error_code or 'review_required')[:64] + unit.error_code = None + unit.error_message = str(error_message or 'Order extraction requires manual review')[:2000] + unit.finished_at = now + unit.retry_status = 'review_required' + unit.technical_failure_reason_code = None elif target_status == 'failed': unit.result_json = None + unit.summary_json = dict(result or {}) + unit.reason_code = None unit.error_code = str(error_code or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED')[:64] unit.error_message = str(error_message or 'Order extraction unit failed')[:2000] unit.finished_at = now + unit.retry_status = 'failed' + unit.technical_failure_reason_code = unit.error_code elif target_status == 'pending': unit.finished_at = None + unit.reason_code = None + unit.summary_json = None unit.error_code = None unit.error_message = None - elif target_status == 'skipped': + unit.retry_status = 'pending_retry' + unit.technical_failure_reason_code = None + elif target_status == 'cancelled': unit.result_json = None - unit.error_code = str(error_code or 'SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED')[:64] - unit.error_message = str(error_message or 'Order extraction requires review')[:2000] + unit.summary_json = dict(result or {}) + unit.reason_code = str(error_code or 'cancelled')[:64] + unit.error_code = None + unit.error_message = str(error_message or 'Order extraction unit was cancelled')[:2000] unit.finished_at = now + unit.retry_status = 'cancelled' + unit.technical_failure_reason_code = None plan_run = getattr(unit.plan, 'run', None) if plan_run is not None and getattr(plan_run, 'run_no', None): append_shipping_audit_event( @@ -198,7 +427,7 @@ def transition_order_extraction_unit( aggregate_id=str(unit.id), run_no=str(plan_run.run_no), actor_type='system', - reason_code=unit.error_code if target_status in {'failed', 'skipped'} else None, + reason_code=unit.reason_code if target_status in {'review_required', 'cancelled'} else unit.error_code if target_status == 'failed' else None, before=before_projection, after={'status': target_status, 'attempt_count': int(unit.attempt_count or 0)}, metadata={'target_status': target_status}, diff --git a/backend/app/services/shipping_notice/order_extraction_progress.py b/backend/app/services/shipping_notice/order_extraction_progress.py index 31116ead..e910f9db 100644 --- a/backend/app/services/shipping_notice/order_extraction_progress.py +++ b/backend/app/services/shipping_notice/order_extraction_progress.py @@ -1,9 +1,9 @@ """ services/shipping_notice/order_extraction_progress.py -用途:把已脱敏的 Workflow 生命周期事件持久化为订单抽取 Run 的当前进度与诊断时间线。 -依赖:Dify 事件观察器、ShippingOrderExtractionRun、独立 SQLAlchemy Session。 -逻辑:订单 Worker 的长事务只负责业务事实;本模块使用短事务去重并更新可恢复投影,任何记录失败均不影响主链路。 +用途:记录订单抽取 Run/Unit 的确定性业务事件,作为用户态进度与管理员诊断的共同事实源。 +依赖:ShippingOrderExtractionRun/Unit/ProgressEvent ORM、统一数据库会话。 +逻辑:调用方只能写入受控 event_code;服务负责幂等、顺序号、终态保护和最小化 Run 投影。 """ from __future__ import annotations @@ -14,189 +14,255 @@ import logging from datetime import datetime, timedelta from typing import Any -from sqlalchemy import select -from sqlalchemy.exc import IntegrityError -from sqlalchemy.orm import Session +from sqlalchemy import func from app import db -from app.models import ShippingOrderExtractionProgressEvent, ShippingOrderExtractionRun +from app.models import ( + ShippingOrderExtractionProgressEvent, + ShippingOrderExtractionRun, + ShippingOrderExtractionUnit, +) _LOGGER = logging.getLogger(__name__) -# 数据库列限制为 VARCHAR(32),映射版本必须保持在该上限内。 -MAPPING_VERSION = 'shipping-order-extract-node-v1' +MAPPING_VERSION = 'shipping-order-progress-v2' EVENT_RETENTION_DAYS = 90 -TERMINAL_RUN_STATUSES = {'completed', 'needs_review', 'failed', 'cancelled'} -_STAGE_PRIORITY = { - 'auto_recovering': 90, - 'hxops_persistence': 80, - 'provider_result_ready': 70, - 'result_processing': 60, - 'order_recognition': 50, - 'document_processing': 40, - 'generic_processing': 30, - 'workflow_accepted': 20, - 'queued': 10, +EVENT_CODE_ORDER = { + 'plan_created': 5, + 'initial_wave_started': 8, + 'expansion_wave_started': 9, + 'document_queued': 10, + 'profile_matching': 20, + 'profile_matched': 30, + 'table_reconstructed': 40, + 'order_fields_extracted': 50, + 'email_supplement_merged': 60, + 'technical_retrying': 65, + 'candidate_ready': 70, + 'review_required': 70, + 'technical_failed': 70, + 'budget_stopped': 80, + 'run_completed': 90, } +WORKSPACE_EVENT_CODES = { + 'plan_created', + 'initial_wave_started', + 'expansion_wave_started', + 'document_queued', + 'profile_matching', + 'profile_matched', + 'table_reconstructed', + 'order_fields_extracted', + 'email_supplement_merged', + 'candidate_ready', + 'review_required', + 'technical_retrying', + 'technical_failed', + 'budget_stopped', + 'run_completed', +} +VISIBILITIES = {'workspace', 'admin'} +TERMINAL_RUN_STATUSES = {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'} def _safe_text(value: Any, limit: int) -> str | None: - """压缩外部事件标识;调用方只允许传入无业务正文的技术枚举或编号。""" + """压缩受控标识文本,防止异常正文或路径被误写入事件表。""" text = ' '.join(str(value or '').replace('\x00', '').split()).strip() return text[:limit] if text else None -def _event_key(event: dict[str, Any]) -> str: - """为缺少节点执行编号的 Dify 版本生成稳定、无业务正文的去重键。""" +def _safe_summary(summary: Any) -> dict[str, Any] | None: + """仅接受可 JSON 序列化的结构化摘要;失败时回退为空。""" + if not isinstance(summary, dict): + return None + try: + return json.loads(json.dumps(summary, ensure_ascii=True, sort_keys=True, default=str)) + except (TypeError, ValueError): + return None + + +def _event_key(*, run_id: int, unit_id: int | None, document_id: int | None, event_code: str, status: str, visibility: str, reason_code: str | None, attempt_count: int | None, summary: dict[str, Any] | None) -> str: + """生成稳定事件幂等键,重复执行或重放不会插入重复用户事件。""" payload = { - 'workflow_run_id': _safe_text(event.get('workflow_run_id'), 128), - 'node_execution_id': _safe_text(event.get('node_execution_id'), 128), - 'event_type': _safe_text(event.get('event_type'), 64), - 'node_type': _safe_text(event.get('node_type'), 64), - 'event_status': _safe_text(event.get('event_status'), 32), - 'job_id': event.get('job_id') if isinstance(event.get('job_id'), int) else None, - 'attempt_count': event.get('attempt_count') if isinstance(event.get('attempt_count'), int) else None, - 'provider_occurred_at': _safe_text(event.get('provider_occurred_at'), 64), + 'run_id': int(run_id), + 'unit_id': int(unit_id) if unit_id is not None else None, + 'document_id': int(document_id) if document_id is not None else None, + 'event_code': event_code, + 'status': status, + 'visibility': visibility, + 'reason_code': reason_code, + 'attempt_count': int(attempt_count) if attempt_count is not None else None, + 'summary': summary or None, } return hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=True).encode('ascii')).hexdigest() -def _stage_for_event(event: dict[str, Any]) -> str | None: - """按节点技术类型映射通用阶段;禁止从节点标题或输出猜测业务含义。""" - event_type = str(event.get('event_type') or '').lower() - if event_type == 'workflow_started': - return 'workflow_accepted' - if event_type == 'hxops_persistence_started': - return 'hxops_persistence' - if event_type in {'poll_started', 'retry_started', 'stream_interrupted'}: - return 'auto_recovering' - if event_type == 'workflow_finished' and str(event.get('event_status') or '').lower() in {'succeeded', 'success'}: - return 'provider_result_ready' - node_type = str(event.get('node_type') or '').lower().replace('_', '-').replace(' ', '-') - if not node_type: - return None - if any(token in node_type for token in ('document', 'file-extractor', 'text-extractor')): - return 'document_processing' - if node_type in {'llm', 'agent'} or 'llm' in node_type: - return 'order_recognition' - if any(token in node_type for token in ('code', 'template', 'parameter', 'json')): - return 'result_processing' - return 'generic_processing' +def _next_sequence_no(run_id: int) -> int: + """按 Run 内稳定自增序号排序,前端无需猜测事件时序。""" + current = db.session.query(func.max(ShippingOrderExtractionProgressEvent.sequence_no)).filter_by(run_id=run_id).scalar() + return int(current or 0) + 1 -def _main_stage(active: set[str], completed: set[str], previous: str | None) -> str: - """并行阶段按优先级归并;除自动恢复结束外,用户主阶段不得向低优先级回退。""" - if previous == 'hxops_persistence': - return previous - candidates = active or completed or {'queued'} - candidate = max(candidates, key=lambda item: _STAGE_PRIORITY.get(item, 0)) - if previous and previous != 'auto_recovering': - return max((previous, candidate), key=lambda item: _STAGE_PRIORITY.get(item, 0)) - return candidate +def _should_update_projection(run: ShippingOrderExtractionRun, event_code: str) -> bool: + """迟到事件不能把 Run 当前活动从更后阶段回退。""" + current = str(run.current_stage_code or '').strip() + if not current: + return True + return EVENT_CODE_ORDER.get(event_code, 0) >= EVENT_CODE_ORDER.get(current, 0) -def _apply_projection(run: ShippingOrderExtractionRun, event: dict[str, Any], stage: str | None, now: datetime) -> None: - """更新用户可见投影;终态 Run 仍保留明细,但不再被Dify事件改回运行态。""" - event_type = str(event.get('event_type') or '').lower() +def _apply_run_projection(run: ShippingOrderExtractionRun, *, event_code: str, occurred_at: datetime) -> None: + """维持最小 Run 投影,供阶段一验证恢复性与轮询版本控制。""" if run.status in TERMINAL_RUN_STATUSES: return - active = {str(item) for item in (run.active_stage_codes_json or []) if str(item)} + if _should_update_projection(run, event_code): + run.current_stage_code = event_code + run.active_stage_codes_json = [] if event_code in { + 'candidate_ready', 'review_required', 'technical_failed', 'budget_stopped', 'run_completed', + } else [event_code] completed = {str(item) for item in (run.completed_stage_codes_json or []) if str(item)} - if event_type == 'node_started' and stage: - # Workflow 已被真实节点接管后,连接成功只作为已完成里程碑保留。 - if 'workflow_accepted' in active: - active.discard('workflow_accepted') - completed.add('workflow_accepted') - active.add(stage) - elif event_type == 'node_finished' and stage: - active.discard(stage) - completed.add(stage) - elif event_type == 'workflow_started' and stage: - active.add(stage) - elif event_type == 'workflow_finished' and stage: - active.clear() - completed.add(stage) - elif event_type == 'hxops_persistence_started' and stage: - active.clear() - active.add(stage) - elif event_type in {'poll_started', 'retry_started', 'stream_interrupted'} and stage: - active.add(stage) - elif event_type == 'recovered': - active.discard('auto_recovering') - - run.active_stage_codes_json = sorted(active) + if event_code in WORKSPACE_EVENT_CODES: + completed.add(event_code) run.completed_stage_codes_json = sorted(completed) - run.current_stage_code = _main_stage(active, completed, run.current_stage_code) - run.progress_message_code = f'shipping.order_extraction.{run.current_stage_code}' + run.progress_message_code = f'shipping.order_extraction.events.{event_code}' run.progress_mapping_version = MAPPING_VERSION - run.last_activity_at = now + run.last_activity_at = occurred_at run.progress_version = int(run.progress_version or 0) + 1 -def record_order_extraction_progress_event(*, run_no: str, event: dict[str, Any]) -> bool: +def record_order_extraction_progress_event( + *, + run_no: str, + event: dict[str, Any], + commit: bool = True, +) -> bool: """ - 使用独立短事务写入一个脱敏进度事件与 Run 投影。 + 写入一个确定性订单抽取事件。 - AI 触发时机:无;仅由订单抽取 Worker 的 Dify 观察器或 HXOPS 持久化边界调用。 + AI 触发时机:无需直接调用;仅供 Worker、Run service 或测试写入已发生的业务事实。 Args: run_no: 订单抽取 Run 编号。 - event: 已标准化的安全事件,禁止包含节点输入、输出、Prompt、正文或异常堆栈。 + event: 受控事件对象,必须包含 event_code;禁止传入堆栈、路径、原文与 Workflow 节点数据。 + commit: 是否在函数内提交事务;Worker 可传 False 后与状态机同事务提交。 Returns: - 是否新增了事件;重复事件或未知 Run 返回 False。 + 新事件是否真正写入。 """ normalized_no = str(run_no or '').strip() - if not normalized_no: + event_code = _safe_text((event or {}).get('event_code'), 64) + if not normalized_no or not event_code or event_code not in WORKSPACE_EVENT_CODES: return False - now = datetime.utcnow() - stage = _stage_for_event(event) - key = _event_key(event) + visibility = _safe_text(event.get('visibility'), 32) or 'workspace' + if visibility not in VISIBILITIES: + return False + status = _safe_text(event.get('status'), 32) or 'completed' + occurred_at = event.get('occurred_at') if isinstance(event.get('occurred_at'), datetime) else datetime.utcnow() + summary = _safe_summary(event.get('summary')) + reason_code = _safe_text(event.get('reason_code'), 64) try: - with Session(bind=db.engine) as session: - run = session.execute( - select(ShippingOrderExtractionRun) - .where(ShippingOrderExtractionRun.run_no == normalized_no) - .with_for_update(), - ).scalar_one_or_none() - if run is None: - return False - row = ShippingOrderExtractionProgressEvent( - run_id=run.id, - job_id=event.get('job_id') if isinstance(event.get('job_id'), int) else None, - attempt_count=event.get('attempt_count') if isinstance(event.get('attempt_count'), int) else None, - workflow_run_id=_safe_text(event.get('workflow_run_id'), 128), - node_execution_id=_safe_text(event.get('node_execution_id'), 128), - event_type=_safe_text(event.get('event_type'), 64) or 'unknown', - node_type=_safe_text(event.get('node_type'), 64), - stage_code=stage, - event_status=_safe_text(event.get('event_status'), 32), - received_at=now, - details_json={'source': 'dify_workflow_observer'}, - idempotency_key=key, - mapping_version=MAPPING_VERSION, - expires_at=now + timedelta(days=EVENT_RETENTION_DAYS), - ) - session.add(row) - try: - session.flush() - except IntegrityError: - session.rollback() - return False - _apply_projection(run, event, stage, now) - session.commit() - return True + run = ShippingOrderExtractionRun.query.filter_by(run_no=normalized_no).with_for_update().first() + if run is None: + return False + if run.status in TERMINAL_RUN_STATUSES and event_code not in {'run_completed', 'technical_failed'}: + return False + unit_id = int(event['unit_id']) if event.get('unit_id') is not None else None + document_id = int(event['document_id']) if event.get('document_id') is not None else None + attempt_count = int(event['attempt_count']) if event.get('attempt_count') is not None else None + key = _event_key( + run_id=int(run.id), + unit_id=unit_id, + document_id=document_id, + event_code=event_code, + status=status, + visibility=visibility, + reason_code=reason_code, + attempt_count=attempt_count, + summary=summary, + ) + if ShippingOrderExtractionProgressEvent.query.filter_by(idempotency_key=key).first() is not None: + return False + row = ShippingOrderExtractionProgressEvent( + run_id=run.id, + unit_id=unit_id, + document_id=document_id, + job_id=int(event['job_id']) if event.get('job_id') is not None else None, + attempt_count=attempt_count, + sequence_no=_next_sequence_no(int(run.id)), + visibility=visibility, + event_code=event_code, + status=status, + occurred_at=occurred_at, + reason_code=reason_code, + received_at=datetime.utcnow(), + summary_json=summary, + idempotency_key=key, + mapping_version=MAPPING_VERSION, + expires_at=occurred_at + timedelta(days=EVENT_RETENTION_DAYS), + ) + db.session.add(row) + _apply_run_projection(run, event_code=event_code, occurred_at=occurred_at) + if commit: + db.session.commit() + else: + db.session.flush() + return True except Exception: - _LOGGER.exception('order extraction progress recording failed run_no=%s event_type=%s', normalized_no, event.get('event_type')) + if commit: + db.session.rollback() + _LOGGER.exception('order extraction progress recording failed run_no=%s event_code=%s', normalized_no, event_code) return False -def record_order_extraction_persistence_started(*, run_no: str, job_id: int, attempt_count: int) -> bool: - """在HXOPS开始落库前写入不可被Dify迟到事件覆盖的持久化阶段。""" +def record_unit_progress( + *, + run: ShippingOrderExtractionRun, + unit: ShippingOrderExtractionUnit, + event_code: str, + summary: dict[str, Any] | None = None, + reason_code: str | None = None, + visibility: str = 'workspace', + job_id: int | None = None, + commit: bool = False, +) -> bool: + """以 Run/Unit 实体写入业务事件,供 Worker 在状态推进时复用。""" return record_order_extraction_progress_event( - run_no=run_no, + run_no=str(run.run_no), + commit=commit, event={ - 'event_type': 'hxops_persistence_started', - 'event_status': 'running', - 'job_id': job_id, - 'attempt_count': attempt_count, - 'node_type': 'hxops_persistence', + 'unit_id': int(unit.id), + 'document_id': int(unit.document_id), + 'event_code': event_code, + 'status': 'completed', + 'summary': summary, + 'reason_code': reason_code, + 'visibility': visibility, + 'job_id': int(job_id) if job_id is not None else None, + 'attempt_count': int(unit.attempt_count or 0), + 'occurred_at': datetime.utcnow(), + }, + ) + + +def record_run_progress( + *, + run: ShippingOrderExtractionRun, + event_code: str, + summary: dict[str, Any] | None = None, + reason_code: str | None = None, + visibility: str = 'workspace', + job_id: int | None = None, + commit: bool = False, +) -> bool: + """记录 Run 级事件,如 run_completed。""" + return record_order_extraction_progress_event( + run_no=str(run.run_no), + commit=commit, + event={ + 'event_code': event_code, + 'status': 'completed', + 'summary': summary, + 'reason_code': reason_code, + 'visibility': visibility, + 'job_id': int(job_id) if job_id is not None else None, + 'attempt_count': int(run.attempt_count or 0), + 'occurred_at': datetime.utcnow(), }, ) diff --git a/backend/app/services/shipping_notice/order_extraction_run_service.py b/backend/app/services/shipping_notice/order_extraction_run_service.py index c5af717a..178308a2 100644 --- a/backend/app/services/shipping_notice/order_extraction_run_service.py +++ b/backend/app/services/shipping_notice/order_extraction_run_service.py @@ -16,6 +16,7 @@ from collections import Counter from datetime import datetime, timedelta from typing import Any +from flask import current_app from sqlalchemy.exc import IntegrityError from sqlalchemy import or_ @@ -30,26 +31,50 @@ from app.models import ( ShippingNoticeDocument, ShippingNoticeIntake, ShippingNoticeCandidate, - ShippingDocumentLayoutVersion, ShippingOrderExtractionRun, ShippingOrderExtractionRunIntake, + ShippingOrderExtractionPlan, ShippingOrderSchemaVersion, User, ) from app.services.shipping_notice.order_schema.runtime import dify_contract, published_version from app.services.shipping_notice.context_fields.runtime import canonical_mail_context +from app.services.shipping_notice.attachment_selection import build_attachment_selection_snapshot +from app.services.shipping_notice.order_extraction_snapshot_selection import ( + has_attachment_catalog, + has_selected_attachments, + should_include_snapshot_document, +) +from app.services.shipping_notice.order_extraction_materialization import ( + ensure_order_extraction_input_documents, +) +from app.services.shipping_notice.order_auto_freeze_policy import build_initial_auto_freeze_policy +from app.services.shipping_notice.order_extraction_progress import record_run_progress _LOGGER = logging.getLogger(__name__) RUN_TRANSITIONS: dict[str, set[str]] = { - 'queued': {'running', 'cancelled'}, - 'running': {'queued', 'result_persisted', 'failed', 'cancelled'}, - 'result_persisted': {'completed', 'needs_review'}, + 'queued': {'processing', 'cancelled'}, + 'processing': {'queued', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'}, 'completed': set(), - 'needs_review': set(), - 'failed': {'queued', 'cancelled'}, + 'partially_completed': set(), + 'review_required': set(), + # 候选持久化在 Worker 收尾后独立提交;若已落出当前版本候选,可从该技术失败恢复为人工复核。 + 'failed': {'queued', 'review_required', 'cancelled'}, 'cancelled': set(), } +EXPANDABLE_UNIT_REVIEW_REASON_CODES = { + 'required_anchor_missing', + 'required_field_missing', + 'business_table_not_found', + 'multiple_business_tables', + 'po_missing', + 'multiple_po_detected', + 'row_needs_review', +} +EXPANDABLE_ORDER_CONFLICT_REASON_CODES = { + 'supplement_relation_ambiguous', +} def _canonical_json(payload: Any) -> str: @@ -85,6 +110,66 @@ def _require_owner_agent(*, user: User, agent_id: int) -> Agent: return agent +def _selection_budget_settings() -> dict[str, int]: + """读取订单抽取附件预算,统一生成首轮与后续扩展批次的选择计划。""" + max_initial_attachments = max( + int(current_app.config.get('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_ATTACHMENTS', 2) or 2), + 1, + ) + max_initial_concurrency = min( + max( + int(current_app.config.get('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_CONCURRENCY', 2) or 2), + 1, + ), + max_initial_attachments, + ) + expansion_batch_size = max( + int(current_app.config.get('SHIPPING_NOTICE_ORDER_EXTRACTION_EXPANSION_BATCH_SIZE', 2) or 2), + 1, + ) + max_total_attachments = max( + int(current_app.config.get('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS', 6) or 6), + max_initial_attachments, + ) + return { + 'max_initial_attachments': max_initial_attachments, + 'max_initial_concurrency': max_initial_concurrency, + 'expansion_batch_size': expansion_batch_size, + 'max_total_attachments': max_total_attachments, + 'max_total_bytes': max( + int(current_app.config.get('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_BYTES', 30 * 1024 * 1024) or 0), + 1, + ), + 'max_runtime_seconds': max( + int(current_app.config.get('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_RUNTIME_SECONDS', 300) or 0), + 1, + ), + } + + +def _build_attachment_selection_for_run(*, intakes: list[ShippingNoticeIntake]) -> dict[str, Any]: + """按当前环境预算生成发送批次的附件选择计划。""" + selection = build_attachment_selection_snapshot(intakes=intakes, **_selection_budget_settings()) + # 预算按用户实际上传的原始资产计费:EML 父文件已包含其附件字节,禁止重复累加目录项。 + input_total_bytes = sum( + max(0, int(getattr(db.session.get(FileAsset, intake.asset_id), 'file_size', 0) or 0)) + for intake in intakes + ) + selection['input_total_bytes'] = input_total_bytes + max_total_bytes = int(selection.get('max_total_bytes') or 0) + if max_total_bytes and input_total_bytes > max_total_bytes: + selection['input_budget_exceeded'] = True + for item in selection.get('items') or []: + if isinstance(item, dict) and not item.get('skip_reason_codes'): + item['selected'] = False + item['selection_batch'] = None + item['planned_selection_batch'] = None + item['skip_reason_codes'] = ['budget_total_bytes'] + else: + selection['input_budget_exceeded'] = False + return selection + + def _require_conversation(*, user_id: int, agent_id: int, conversation_id: str) -> ChatSession: """确认会话属于当前用户和货代入口 Agent,防止跨会话冻结附件。""" session = db.session.query(ChatSession).filter_by( @@ -100,32 +185,52 @@ def _require_conversation(*, user_id: int, agent_id: int, conversation_id: str) return session -def _load_intakes(*, user_id: int, intake_nos: list[str]) -> list[ShippingNoticeIntake]: - """按稳定编号加载并锁定 Intake;先校验业务资格,会话归属由后续事务步骤统一处理。""" +def _load_intakes( + *, user_id: int, intake_nos: list[str], upload_batch_id: str | None = None, + allow_orphaned_consumed_reparse: bool = False, +) -> list[ShippingNoticeIntake]: + """锁定当前输入框上传批次的 Intake,拒绝历史附件混入本次发送。 + + 重新识别可复用“未生成批次或任务”的历史空结果;已产生业务单的 + Intake 仍一律禁止复用,避免重复建单。 + """ normalized = sorted({str(value or '').strip().upper() for value in intake_nos if str(value or '').strip()}) if not normalized or len(normalized) > 50: raise ValidationError( 'intake_nos must contain 1 to 50 values', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INTAKES_INVALID', ) - rows = ( + batch_id = str(upload_batch_id or '').strip() + query = ( db.session.query(ShippingNoticeIntake) - .filter(ShippingNoticeIntake.intake_no.in_(normalized), ShippingNoticeIntake.user_id == user_id) + .filter( + ShippingNoticeIntake.intake_no.in_(normalized), + ShippingNoticeIntake.user_id == user_id, + ) .order_by(ShippingNoticeIntake.intake_no.asc()) .with_for_update() - .all() ) + if batch_id: + query = query.filter(ShippingNoticeIntake.upload_batch_id == batch_id) + rows = query.all() if len(rows) != len(normalized): raise NotFoundError('Shipping notice intake not found', code='SHIPPING_NOTICE.INTAKE_NOT_FOUND') now = datetime.utcnow() for intake in rows: - if intake.consumed_at is not None or intake.consumed_batch_id is not None or intake.consumed_task_id is not None: + has_business_consumption = intake.consumed_batch_id is not None or intake.consumed_task_id is not None + is_orphaned_consumed = intake.consumed_at is not None and not has_business_consumption + if has_business_consumption or (intake.consumed_at is not None and not ( + allow_orphaned_consumed_reparse and is_orphaned_consumed + )): raise ConflictError('Shipping notice intake was consumed', code='SHIPPING_NOTICE.INTAKE_ALREADY_CONSUMED') if intake.parse_status == 'cancelled': raise ConflictError('Shipping notice intake was cancelled', code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS') if intake.expires_at is not None and intake.expires_at <= now: raise ConflictError('Shipping notice intake expired', code='SHIPPING_NOTICE.INTAKE_EXPIRED') - if intake.parse_status != 'parsed': + if intake.parse_status != 'parsed' and not ( + allow_orphaned_consumed_reparse and is_orphaned_consumed + and intake.parse_status == 'consumed' + ): raise ConflictError( 'Shipping notice intake is not parsed', code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING', @@ -202,12 +307,29 @@ def _build_snapshot( conversation_id: str, intakes: list[ShippingNoticeIntake], schema_version: ShippingOrderSchemaVersion, + attachment_selection: dict[str, Any] | None = None, + allow_unmaterialized: bool = False, ) -> dict[str, Any]: - """冻结 Worker 所需的正文、布局和 Schema 映射;后续执行不再回读可变 Document。""" + """冻结 Worker 所需的正文、已选附件文档和 Schema 映射;后续执行不再回读可变 Document。""" from app.services.shipping_notice.order_document_profile_service import ( published_snapshots_for_schema, ) + selection_snapshot = ( + attachment_selection + if isinstance(attachment_selection, dict) + else _build_attachment_selection_for_run(intakes=intakes) + ) + if has_attachment_catalog(selection_snapshot) and not has_selected_attachments(selection_snapshot): + raise ConflictError( + 'Shipping notice contains no eligible attachments for automatic extraction', + code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', + details={ + 'intake_nos': [str(intake.intake_no or '') for intake in intakes], + 'reason': 'no_eligible_selected_attachment', + }, + ) + intake_ids = [intake.id for intake in intakes] documents = ( db.session.query(ShippingNoticeDocument) @@ -224,11 +346,20 @@ def _build_snapshot( documents_by_intake: dict[int, list[dict[str, Any]]] = {intake.id: [] for intake in intakes} from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot from app.services.shipping_notice.document_layout.schema_mapping import map_layout_document_to_schema + from app.services.shipping_notice.email_allocation_table_parser import parse_email_allocation_text from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract table_contract = compile_table_header_contract(dict(schema_version.definition_json or {})) + intake_no_by_id = {int(intake.id): str(intake.intake_no or '').strip().upper() for intake in intakes} for document in documents: + if not should_include_snapshot_document( + selection_snapshot=selection_snapshot, + intake_no=intake_no_by_id.get(int(document.intake_id), ''), + document_type=str(document.document_type or ''), + attachment_key=document.attachment_key, + ): + continue asset = assets.get(document.asset_id) if document.asset_id is not None else None layout_snapshot = current_layout_snapshot(document) layout_candidate = ( @@ -247,6 +378,20 @@ def _build_snapshot( 'mapping_status': 'failed', 'issues': ['layout_schema_mapping_invalid'], }] + email_supplement = ( + (document.order_extraction_result_json or {}).get('email_supplement') + if document.document_type == 'email_body' + and isinstance(document.order_extraction_result_json, dict) + else None + ) + # 旧 Intake 已经持久化时,也在重新识别的冻结边界补齐纯文本正文补充事实。 + # 结果只进入本 Run 快照,原始解析记录保持不变,确保可审计。 + if document.document_type == 'email_body' and not isinstance(email_supplement, dict): + email_supplement = parse_email_allocation_text( + body_text=str(document.extracted_text or ''), + content_hash=str(document.content_hash or ''), + ) + email_supplement['document_id'] = int(document.id) documents_by_intake[document.intake_id].append({ 'document_id': document.id, 'document_type': document.document_type, @@ -261,22 +406,19 @@ def _build_snapshot( 'parse_warnings': document.parse_warnings_json or [], 'layout_snapshot': layout_snapshot, 'layout_schema_candidates': layout_schema_candidates, - 'email_supplement': ( - (document.order_extraction_result_json or {}).get('email_supplement') - if document.document_type == 'email_body' - and isinstance(document.order_extraction_result_json, dict) - else None - ), + 'email_supplement': email_supplement, }) incomplete = [ intake.intake_no for intake in intakes if not any( - item['parse_status'] == 'parsed' and bool(str(item['extracted_text'] or '').strip()) + item['document_type'] != 'email_body' + and item['parse_status'] == 'parsed' + and bool(str(item['extracted_text'] or '').strip()) for item in documents_by_intake[intake.id] ) ] - if incomplete: + if incomplete and not allow_unmaterialized: raise ConflictError( 'Shipping notice documents are incomplete', code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', @@ -313,36 +455,71 @@ def _build_snapshot( } for intake in intakes ], + 'attachment_selection': selection_snapshot, } -def _require_layouts_terminal_before_snapshot(*, intakes: list[ShippingNoticeIntake]) -> None: - """阻断仍在解析版面的附件,避免 Run 冻结空 Layout 后永久错过确定性模板路由。""" - document_ids = [ - int(document_id) - for (document_id,) in db.session.query(ShippingNoticeDocument.id) - .filter(ShippingNoticeDocument.intake_id.in_([intake.id for intake in intakes])) - .all() - ] - if not document_ids: - return - pending = ( - db.session.query(ShippingDocumentLayoutVersion) - .filter( - ShippingDocumentLayoutVersion.document_id.in_(document_ids), - ShippingDocumentLayoutVersion.status.in_({'queued', 'running'}), - ) - .order_by(ShippingDocumentLayoutVersion.document_id.asc()) - .all() - ) - if pending: +def materialize_order_extraction_run_inputs(run: ShippingOrderExtractionRun) -> ShippingOrderExtractionPlan: + """ + 在 Worker 中物化首轮附件并替换轻量输入快照为不可变 Document 快照。 + + AI 触发时机:仅订单抽取 Job 开始时调用;HTTP 发送路径严禁调用。 + 核心逻辑:使用创建时冻结的 Schema/附件选择和 Intake 标识,先物化首轮,再生成计划; + 物化失败保持 Run 可重试,且不会把深度解析延迟转嫁给用户请求。 + """ + from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan + + # 已完成物化并建计划的 Run 重试时直接复用,避免再次抽取或改变执行证据快照。 + if ShippingOrderExtractionPlan.query.filter_by(run_id=int(run.id)).first() is not None: + return ensure_order_extraction_plan(run) + + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {} + schema_version_id = int(schema.get('schema_version_id') or run.schema_version_id or 0) + schema_version = db.session.get(ShippingOrderSchemaVersion, schema_version_id) + if schema_version is None: raise ConflictError( - 'Shipping notice document layout is still processing', - code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PENDING', - details={'document_ids': [int(item.document_id) for item in pending]}, + 'Frozen order schema is unavailable', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE', ) - - + intake_ids = [ + int(item.get('intake_id')) + for item in snapshot.get('intakes') or [] + if isinstance(item, dict) and item.get('intake_id') is not None + ] + intakes = ( + ShippingNoticeIntake.query + .filter(ShippingNoticeIntake.id.in_(intake_ids)) + .order_by(ShippingNoticeIntake.id.asc()) + .with_for_update() + .all() + ) if intake_ids else [] + if len(intakes) != len(set(intake_ids)): + raise ConflictError( + 'Frozen shipping notice intake is unavailable', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE', + ) + selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {} + ensure_order_extraction_input_documents( + intakes=intakes, + attachment_selection=selection, + schema_definition=dict(schema_version.definition_json or {}), + selection_batches={1}, + ) + materialized = _build_snapshot( + user_id=int(run.user_id), + owner_agent_id=int(run.owner_agent_id), + conversation_id=str(run.conversation_id or ''), + intakes=intakes, + schema_version=schema_version, + attachment_selection=selection, + ) + materialized['auto_freeze_policy'] = dict(run.auto_freeze_policy_json or {}) + materialized['upload_batch_id'] = snapshot.get('upload_batch_id') + run.input_snapshot_json = materialized + run.input_snapshot_hash = _sha256(materialized) + db.session.flush() + return ensure_order_extraction_plan(run) def _active_run_for_intakes(intake_ids: list[int]) -> ShippingOrderExtractionRun | None: """读取占用任一 Intake 的未释放 Run,供并发唯一约束冲突后返回明确业务结果。""" return ( @@ -366,7 +543,7 @@ def _active_run_for_conversation( ShippingOrderExtractionRun.user_id == user_id, ShippingOrderExtractionRun.owner_agent_id == owner_agent_id, ShippingOrderExtractionRun.conversation_id == conversation_id, - ShippingOrderExtractionRun.status.in_({'queued', 'running', 'result_persisted'}), + ShippingOrderExtractionRun.status.in_({'queued', 'processing'}), ) .order_by(ShippingOrderExtractionRun.created_at.desc()) .first() @@ -384,6 +561,7 @@ def create_order_extraction_run( agent_id: int, conversation_id: str, intake_nos: list[str], + upload_batch_id: str | None = None, reparse_of_run: ShippingOrderExtractionRun | None = None, reparse_reason: str | None = None, reparse_comment: str | None = None, @@ -395,7 +573,8 @@ def create_order_extraction_run( user: 当前认证用户;管理员可使用任意启用货代 Agent,普通用户必须拥有 Agent 权限。 agent_id: 用户入口货代 Agent 主键,不是后台 Provider ID。 conversation_id: HXOPS ChatSession.session_id;首次后台 Run 可为空,由服务端创建并绑定 Intake。 - intake_nos: 1-50 个已解析且未消费的 Intake 编号。 + intake_nos: 1-50 个已解析且未消费的当前输入框 Intake 编号。 + upload_batch_id: 当前输入框上传批次,必须与每个 Intake 完全一致。 reparse_of_run: 可选的终态来源 Run;提供时创建新的版本化识别 Run。 reparse_reason/reparse_comment: 用户选择的重识别原因及可选备注,仅用于审计。 Returns: @@ -404,23 +583,26 @@ def create_order_extraction_run( owner_agent = _require_owner_agent(user=user, agent_id=agent_id) if reparse_of_run is not None and ( int(reparse_of_run.user_id) != int(user.id) - or str(reparse_of_run.status or '') not in {'completed', 'needs_review', 'failed', 'cancelled'} + or str(reparse_of_run.status or '') not in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'} ): raise ConflictError( 'Only a terminal run owned by the current user can be reparsed', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_REPARSABLE', ) - intakes = _load_intakes(user_id=user.id, intake_nos=intake_nos) + intakes = _load_intakes( + user_id=user.id, + intake_nos=intake_nos, + upload_batch_id=upload_batch_id, + allow_orphaned_consumed_reparse=reparse_of_run is not None, + ) schema_version = published_version() from app.services.shipping_notice.order_schema.service import get_auto_creation_policy schema_auto_creation_policy = get_auto_creation_policy() # 第一版统一人工确认;Schema 的历史自动建单开关不再驱动订单解析执行器。 - auto_freeze_policy = { - 'mode': 'manual_confirmation', - 'enabled': False, - 'schema_policy_version': schema_auto_creation_policy.get('version'), - } + auto_freeze_policy = build_initial_auto_freeze_policy( + schema_policy_version=schema_auto_creation_policy.get('version'), + ) session = _resolve_conversation( user_id=user.id, agent_id=owner_agent.id, @@ -428,15 +610,27 @@ def create_order_extraction_run( intakes=intakes, ) conversation_id = session.session_id - _require_layouts_terminal_before_snapshot(intakes=intakes) + attachment_selection = _build_attachment_selection_for_run(intakes=intakes) + if attachment_selection.get('input_budget_exceeded'): + raise ConflictError( + 'Shipping notice input exceeds the extraction byte budget', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_BUDGET_EXCEEDED', + details={ + 'input_total_bytes': attachment_selection.get('input_total_bytes'), + 'max_total_bytes': attachment_selection.get('max_total_bytes'), + }, + ) snapshot = _build_snapshot( user_id=user.id, owner_agent_id=owner_agent.id, conversation_id=conversation_id, intakes=intakes, schema_version=schema_version, + attachment_selection=attachment_selection, + allow_unmaterialized=True, ) snapshot['auto_freeze_policy'] = auto_freeze_policy + snapshot['upload_batch_id'] = str(upload_batch_id or '').strip() or None snapshot_hash = _sha256(snapshot) idempotency_key = _sha256({ 'user_id': user.id, @@ -483,6 +677,8 @@ def create_order_extraction_run( reparse_comment=str(reparse_comment or '').strip()[:2000] or None, conversation_id=conversation_id, schema_version_id=schema_version.id, + request_snapshot_hash=snapshot_hash, + request_snapshot_json=snapshot, input_snapshot_hash=snapshot_hash, input_snapshot_json=snapshot, idempotency_key=idempotency_key, @@ -498,9 +694,16 @@ def create_order_extraction_run( for index, intake in enumerate(intakes) ]) db.session.flush() - from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan - - ensure_order_extraction_plan(run) + record_run_progress( + run=run, + event_code='plan_created', + summary={ + 'plan_version': None, + 'unit_count': 0, + 'selection': _selection_plan_summary(attachment_selection), + }, + commit=False, + ) from app.jobs.queue import enqueue from app.jobs.types import JobType @@ -572,7 +775,7 @@ def reparse_order_extraction_run( ) if source is None: raise NotFoundError('Shipping order extraction run not found', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND') - if str(source.status or '') not in {'completed', 'needs_review', 'failed', 'cancelled'}: + if str(source.status or '') not in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'}: raise ConflictError( 'Only terminal order extraction runs can be reparsed', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_REPARSABLE', details={'status': source.status}, @@ -584,7 +787,7 @@ def reparse_order_extraction_run( ShippingOrderExtractionRun.query.filter_by(reparse_of_run_id=source.id) .order_by(ShippingOrderExtractionRun.created_at.desc()).all() ) - active = next((item for item in successors if item.status in {'queued', 'running', 'result_persisted'}), None) + active = next((item for item in successors if item.status in {'queued', 'processing'}), None) if active is not None: return active, True intake_nos = [ @@ -594,12 +797,14 @@ def reparse_order_extraction_run( ] if not intake_nos: raise ConflictError('The source run has no reusable intake snapshot', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE') + source_batch_id = str((source.input_snapshot_json or {}).get('upload_batch_id') or '').strip() or None owner_agent = db.session.get(Agent, int(source.owner_agent_id)) user = db.session.get(User, int(user_id)) if owner_agent is None or user is None: raise ConflictError('The source run cannot be reparsed', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_REPARSABLE') run, reused = create_order_extraction_run( user=user, agent_id=owner_agent.id, conversation_id=source.conversation_id, intake_nos=intake_nos, + upload_batch_id=source_batch_id, reparse_of_run=source, reparse_reason=normalized_reason, reparse_comment=comment, ) if not reused: @@ -658,7 +863,7 @@ def retry_order_extraction_run(*, user_id: int, run_no: str) -> tuple[ShippingOr current_job = db.session.get(Job, run.current_job_id) if run.current_job_id else None if ( - run.status in {'queued', 'running'} + run.status in {'queued', 'processing'} and run.phase in {'manual_retry_queued', 'deterministic_parsing'} and current_job is not None and current_job.status in {'queued', 'running'} @@ -762,17 +967,158 @@ def _reparse_difference_summary(run: ShippingOrderExtractionRun) -> dict[str, An } +def _selection_plan_summary(selection_snapshot: dict[str, Any]) -> dict[str, Any] | None: + """把附件选择计划压缩为用户态稳定摘要,不暴露文件名、分数或正文线索。""" + if not isinstance(selection_snapshot, dict) or not selection_snapshot: + return None + items = selection_snapshot.get('items') if isinstance(selection_snapshot.get('items'), list) else [] + pending_rows = [ + item for item in items + if isinstance(item, dict) and int(item.get('planned_selection_batch') or 0) > 1 + ] + skipped_rows = [ + item for item in items + if isinstance(item, dict) + and not item.get('selected') + and int(item.get('planned_selection_batch') or 0) <= 1 + ] + duplicate_count = sum( + 1 for item in skipped_rows + if 'duplicate_content_hash' in {str(code) for code in (item.get('skip_reason_codes') or [])} + ) + budget_limited_count = sum( + 1 for item in skipped_rows + if {'budget_initial_limit', 'budget_total_limit', 'budget_total_bytes'} & { + str(code) for code in (item.get('skip_reason_codes') or []) + } + ) + return { + 'selection_version': selection_snapshot.get('selection_version'), + 'max_initial_attachments': int(selection_snapshot.get('max_initial_attachments') or 0), + 'max_initial_concurrency': int(selection_snapshot.get('max_initial_concurrency') or 0), + 'expansion_batch_size': int(selection_snapshot.get('expansion_batch_size') or 0), + 'max_total_attachments': int(selection_snapshot.get('max_total_attachments') or 0), + 'max_total_bytes': int(selection_snapshot.get('max_total_bytes') or 0), + 'max_runtime_seconds': int(selection_snapshot.get('max_runtime_seconds') or 0), + 'input_total_bytes': int(selection_snapshot.get('input_total_bytes') or 0), + 'planned_total_bytes': int(selection_snapshot.get('planned_total_bytes') or 0), + 'total_attachment_count': int(selection_snapshot.get('total_attachment_count') or 0), + 'eligible_attachment_count': int(selection_snapshot.get('eligible_attachment_count') or 0), + 'selected_attachment_count': int(selection_snapshot.get('selected_attachment_count') or 0), + 'planned_attachment_count': int(selection_snapshot.get('planned_attachment_count') or 0), + 'pending_expansion_attachment_count': int(selection_snapshot.get('pending_expansion_attachment_count') or 0), + 'pending_expansion_batches': dict(selection_snapshot.get('pending_expansion_batches') or {}), + 'skipped_attachment_count': len(skipped_rows), + 'duplicate_attachment_count': duplicate_count, + 'budget_limited_attachment_count': budget_limited_count, + 'group_count': int(selection_snapshot.get('group_count') or 0), + } + + +def _schema_field_ids_by_code(run: ShippingOrderExtractionRun) -> dict[str, set[str]]: + """建立冻结 Schema 的 field_code -> field_id 集合,供业务缺口摘要复用。""" + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {} + definition = schema.get('definition') if isinstance(schema.get('definition'), dict) else {} + mapping: dict[str, set[str]] = {} + for item in definition.get('fields') or []: + if not isinstance(item, dict): + continue + field_code = str(item.get('field_code') or '').strip() + field_id = str(item.get('field_id') or '').strip() + if not field_code or not field_id: + continue + mapping.setdefault(field_code, set()).add(field_id) + return mapping + + +def _unit_orders(unit: Any) -> list[dict[str, Any]]: + """读取单元结果中的订单列表;非结构化结果统一视为无订单。""" + result = unit.result_json if isinstance(getattr(unit, 'result_json', None), dict) else {} + return [item for item in result.get('orders') or [] if isinstance(item, dict)] + + +def _line_has_field_value(line: dict[str, Any], *, field_ids: set[str]) -> bool: + """判断订单行中是否已有指定字段的非空值。""" + for field in line.get('fields') or []: + if not isinstance(field, dict) or str(field.get('field_id') or '') not in field_ids: + continue + for observation in field.get('observations') or []: + if isinstance(observation, dict) and str(observation.get('value') or '').strip(): + return True + return False + + +def _expansion_trigger_reason_codes(run: ShippingOrderExtractionRun, units: list[Any]) -> list[str]: + """汇总当前 Run 中确实会触发扩批的业务缺口原因码。""" + reason_codes = { + str(unit.reason_code or '').strip() + for unit in units + if str(unit.status or '') == 'review_required' + and str(unit.reason_code or '').strip() in EXPANDABLE_UNIT_REVIEW_REASON_CODES + } + reservation_field_ids = _schema_field_ids_by_code(run).get('reservation_id', set()) + for unit in units: + for order in _unit_orders(unit): + for conflict in order.get('conflicts') or []: + if not isinstance(conflict, dict): + continue + code = str(conflict.get('reason') or '').strip() + if code in EXPANDABLE_ORDER_CONFLICT_REASON_CODES: + reason_codes.add(code) + if reservation_field_ids and any( + isinstance(line, dict) and not _line_has_field_value(line, field_ids=reservation_field_ids) + for line in order.get('lines') or [] + ): + reason_codes.add('missing_reservation_id') + return sorted(reason_codes) + + +def _unit_fact_summary(run: ShippingOrderExtractionRun) -> dict[str, Any] | None: + """聚合执行单元的重试、失败和预算事实,供工作台直接展示。""" + units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else [] + if not units: + return None + retry_status_counter = Counter(str(unit.retry_status or '').strip() for unit in units if str(unit.retry_status or '').strip()) + selection_batch_counter = Counter(int(unit.selection_batch) for unit in units if unit.selection_batch is not None) + technical_failure_codes = sorted({ + str(unit.technical_failure_reason_code or '').strip() + for unit in units if str(unit.technical_failure_reason_code or '').strip() + }) + review_required_reason_codes = sorted({ + str(unit.reason_code or '').strip() + for unit in units + if str(unit.status or '') == 'review_required' and str(unit.reason_code or '').strip() + }) + expansion_trigger_reason_codes = _expansion_trigger_reason_codes(run, units) + return { + 'total_units': len(units), + 'selected_units': sum(1 for unit in units if unit.selection_batch is not None), + 'retrying_units': retry_status_counter.get('retrying', 0) + retry_status_counter.get('running', 0), + 'pending_retry_units': retry_status_counter.get('pending_retry', 0), + 'failed_units': retry_status_counter.get('failed', 0), + 'review_required_units': retry_status_counter.get('review_required', 0), + 'succeeded_units': retry_status_counter.get('succeeded', 0), + 'selection_batches': {str(key): value for key, value in sorted(selection_batch_counter.items())}, + 'review_required_reason_codes': review_required_reason_codes, + 'expansion_trigger_reason_codes': expansion_trigger_reason_codes, + 'technical_failure_reason_codes': technical_failure_codes, + } + + def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str, Any]: """输出用户态 Run 与通用进度投影;不返回正文、Provider、Job 或节点诊断字段。""" + from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run + intake_snapshot = run.input_snapshot_json.get('intakes', []) if isinstance(run.input_snapshot_json, dict) else [] schema_snapshot = run.input_snapshot_json.get('schema', {}) if isinstance(run.input_snapshot_json, dict) else {} - now = datetime.utcnow() - activity_at = run.last_activity_at or run.started_at or run.created_at - idle_seconds = max(0, int((now - activity_at).total_seconds())) if activity_at else 0 - slow_threshold_seconds = get_order_extraction_user_slow_threshold_seconds() - health = 'slow' if run.status in {'queued', 'running', 'result_persisted'} and idle_seconds >= slow_threshold_seconds else ( - 'idle' if run.status in {'queued', 'running', 'result_persisted'} and idle_seconds >= 60 else 'normal' + selection_snapshot = ( + run.input_snapshot_json.get('attachment_selection', {}) + if isinstance(run.input_snapshot_json, dict) + and isinstance(run.input_snapshot_json.get('attachment_selection'), dict) + else {} ) + workspace_projection = serialize_workspace_run(run) return { 'run_no': run.run_no, 'agent_id': run.owner_agent_id, @@ -791,15 +1137,11 @@ def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str, 'superseded_at': run.superseded_at.isoformat() + 'Z' if run.superseded_at else None, 'difference_summary': _reparse_difference_summary(run), }, - 'progress': { - 'version': int(run.progress_version or 0), - 'current_stage_code': run.current_stage_code or ('queued' if run.status == 'queued' else None), - 'active_stage_codes': list(run.active_stage_codes_json or []), - 'completed_stage_codes': list(run.completed_stage_codes_json or []), - 'message_code': run.progress_message_code, - 'health': health, - 'last_activity_at': run.last_activity_at.isoformat() + 'Z' if run.last_activity_at else None, - }, + 'summary': workspace_projection['summary'], + 'selection_plan': _selection_plan_summary(selection_snapshot), + 'unit_summary': _unit_fact_summary(run), + 'current_activity': workspace_projection['current_activity'], + 'available_actions': workspace_projection['available_actions'], 'result': run.result_json, # Worker/provider error text can contain upstream details. Workspace cards only need a # stable code to select a safe, actionable user hint; full diagnostics stay admin-only. @@ -813,28 +1155,9 @@ def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str, def serialize_order_extraction_message_state(run: ShippingOrderExtractionRun) -> dict[str, Any]: """把服务端 Run 事实投影为聊天状态卡;历史恢复和实时持久化必须共用同一映射。""" - result = run.result_json if isinstance(run.result_json, dict) else {} - failed = run.status in {'failed', 'cancelled'} - partial = run.status == 'needs_review' - completed = run.status == 'completed' - return { - 'status': 'failed' if failed else 'partially_completed' if partial else 'completed' if completed else 'extracting', - 'phase': 'failed' if failed else 'result_persisted' if run.status == 'result_persisted' else 'deterministic_parsing', - # The chat log is user-visible on history replay. It must follow the same redaction - # boundary as the workspace Run API and never persist upstream error text. - 'message': '', - 'created_count': int(result.get('created_count') or 0), - 'opened_existing_count': int(result.get('opened_existing_count') or 0), - 'pending_count': int(result.get('pending_count') or 0), - 'non_shipping_count': int(result.get('non_shipping_count') or 0), - 'created_with_missing_fields_count': int(result.get('created_with_missing_fields_count') or 0), - 'batch_no': result.get('batch_no'), - 'terminal': failed or partial or completed, - 'current_stage_code': run.current_stage_code, - 'health': 'normal' if failed or partial or completed else serialize_order_extraction_run(run)['progress']['health'], - 'last_activity_at': run.last_activity_at.isoformat() + 'Z' if run.last_activity_at else None, - 'started_at': (run.started_at or run.created_at).isoformat() + 'Z' if (run.started_at or run.created_at) else None, - } + from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run_chat_state + + return serialize_workspace_run_chat_state(run) def _sync_order_extraction_chat_log(run: ShippingOrderExtractionRun) -> None: @@ -890,48 +1213,55 @@ def cleanup_expired_order_extraction_progress_events(*, limit: int = 1000, now: def list_user_order_extraction_progress_events(*, user_id: int, run_no: str) -> list[dict[str, Any]]: - """返回当前用户可见的归并业务阶段,不暴露节点、Workflow或Job诊断字段。""" + """返回当前执行周期的用户进度,避免历史重试技术事件干扰最终业务结论。""" from app.models import ShippingOrderExtractionProgressEvent run = get_order_extraction_run(user_id=user_id, run_no=run_no) - rows = ( + query = ( ShippingOrderExtractionProgressEvent.query - .filter_by(run_id=run.id) - .order_by(ShippingOrderExtractionProgressEvent.created_at.asc(), ShippingOrderExtractionProgressEvent.id.asc()) - .all() + .filter_by(run_id=run.id, visibility='workspace') ) - seen: set[tuple[str, str]] = set() + # 手工重试会创建新 Job;保留本次 Run 在入队前产生的计划事件,过滤旧 Job 的执行事件。 + if run.current_job_id is not None: + query = query.filter(or_( + ShippingOrderExtractionProgressEvent.job_id.is_(None), + ShippingOrderExtractionProgressEvent.job_id == int(run.current_job_id), + )) + rows = query.order_by( + ShippingOrderExtractionProgressEvent.sequence_no.asc(), + ShippingOrderExtractionProgressEvent.id.asc(), + ).all() + seen: set[tuple[str, str, str]] = set() items: list[dict[str, Any]] = [] for row in rows: - stage = str(row.stage_code or '').strip() - if not stage: + event_code = str(row.event_code or '').strip() + if not event_code: continue - event_type = str(row.event_type or '').lower() - raw_status = str(row.event_status or '').lower() - if raw_status in {'started', 'running', 'completed', 'failed', 'recovered'}: - public_status = raw_status - elif event_type in {'workflow_started', 'node_started', 'poll_started', 'retry_started'}: - public_status = 'running' - elif event_type in {'workflow_finished', 'node_finished'}: - public_status = 'completed' - elif event_type == 'recovered': - public_status = 'recovered' - elif event_type == 'stream_interrupted': - public_status = 'failed' - else: - public_status = 'updated' - key = (stage, public_status) + public_status = str(row.status or 'completed').lower() + key = (event_code, public_status, str(row.document_id or '')) if key in seen: continue seen.add(key) items.append({ - 'stage_code': stage, + 'event_code': event_code, 'status': public_status, - 'occurred_at': (row.provider_occurred_at or row.received_at or row.created_at).isoformat() + 'Z', + 'unit_id': row.unit_id, + 'document_id': row.document_id, + 'reason_code': row.reason_code, + 'summary': row.summary_json, + 'occurred_at': (row.occurred_at or row.received_at or row.created_at).isoformat() + 'Z', }) return items +def list_user_order_extraction_documents(*, user_id: int, run_no: str) -> list[dict[str, Any]]: + """返回按 PDF 归并的工作台详情结果;前端不得再从事件流自行推断文档结论。""" + from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run_documents + + run = get_order_extraction_run(user_id=user_id, run_no=run_no) + return serialize_workspace_run_documents(run) + + def mark_order_extraction_run_seen(*, user_id: int, run_no: str) -> bool: """ 确认当前用户已经看见一条终态订单抽取卡片。 @@ -946,7 +1276,7 @@ def mark_order_extraction_run_seen(*, user_id: int, run_no: str) -> bool: 本次是否首次写入 `seen_at`。 """ run = get_order_extraction_run(user_id=user_id, run_no=run_no) - if run.status not in {'completed', 'needs_review', 'failed', 'cancelled'} or run.attention_generated_at is None: + if run.status not in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'} or run.attention_generated_at is None: return False if run.seen_at is not None: return False @@ -967,8 +1297,27 @@ def _diagnostic_elapsed_ms(started_at: datetime | None, finished_at: datetime | return max(0, int((finished_at - started_at).total_seconds() * 1000)) +def _diagnostic_auto_freeze_policy(run: ShippingOrderExtractionRun) -> dict[str, Any]: + """输出管理员可读的自动冻结门禁摘要,不回传原始 JSON 中的非必要内部字段。""" + policy = run.auto_freeze_policy_json if isinstance(run.auto_freeze_policy_json, dict) else {} + return { + 'mode': str(policy.get('mode') or 'manual_confirmation'), + 'enabled': bool(policy.get('enabled')), + 'selected_profile_code': str(policy.get('selected_profile_code') or '') or None, + 'qualification_status': str(policy.get('qualification_status') or '') or None, + 'customer_scope_status': str(policy.get('customer_scope_status') or '') or None, + 'business_scenario_status': str(policy.get('business_scenario_status') or '') or None, + 'customer_confirmation_required': bool(policy.get('customer_confirmation_required')), + 'evaluated_from_run': bool(policy.get('evaluated_from_run')), + 'blocking_reason_codes': [ + str(code) for code in (policy.get('blocking_reason_codes') or []) + if str(code).strip() + ], + } + + def _serialize_order_extraction_diagnostic_run(run: ShippingOrderExtractionRun) -> dict[str, Any]: - """构建管理员 Run 摘要,只包含状态、标识、计数、时间和脱敏阶段,不含输入输出或错误正文。""" + """构建管理员 Run 摘要,只包含状态、标识、计数、时间和脱敏事件,不含输入输出或错误正文。""" result = run.result_json if isinstance(run.result_json, dict) else {} return { 'run_no': run.run_no, @@ -978,19 +1327,19 @@ def _serialize_order_extraction_diagnostic_run(run: ShippingOrderExtractionRun) 'parser_engine_version': run.parser_engine_version, 'parser_policy_version': run.parser_policy_version, 'attempt_count': int(run.attempt_count or 0), - 'current_stage_code': run.current_stage_code, + 'current_event_code': run.current_stage_code, 'active_stage_codes': list(run.active_stage_codes_json or []), 'completed_stage_codes': list(run.completed_stage_codes_json or []), 'created_at': _diagnostic_iso(run.created_at), 'started_at': _diagnostic_iso(run.started_at), 'extraction_completed_at': _diagnostic_iso(run.extraction_completed_at), - 'result_persisted_at': _diagnostic_iso(run.result_persisted_at), + 'candidate_materialized_at': _diagnostic_iso(run.result_persisted_at), 'finished_at': _diagnostic_iso(run.finished_at), 'last_activity_at': _diagnostic_iso(run.last_activity_at), 'durations_ms': { 'queue': _diagnostic_elapsed_ms(run.created_at, run.started_at), 'deterministic_parsing': _diagnostic_elapsed_ms(run.started_at, run.extraction_completed_at), - 'hxops_persistence': _diagnostic_elapsed_ms(run.extraction_completed_at, run.result_persisted_at), + 'candidate_materialization': _diagnostic_elapsed_ms(run.extraction_completed_at, run.result_persisted_at), 'total': _diagnostic_elapsed_ms(run.created_at, run.finished_at), }, 'result_counts': { @@ -999,6 +1348,7 @@ def _serialize_order_extraction_diagnostic_run(run: ShippingOrderExtractionRun) 'pending': int(result.get('pending_count') or 0), 'non_shipping': int(result.get('non_shipping_count') or 0), }, + 'auto_freeze_policy': _diagnostic_auto_freeze_policy(run), # 仅错误码可用于运维归类,错误正文可能含上游响应内容,严禁返回。 'error_code': run.error_code, } @@ -1033,7 +1383,7 @@ def list_order_extraction_diagnostic_runs( ) -> dict[str, Any]: """分页读取管理员诊断 Run 摘要,并写入只读访问审计。""" normalized_status = str(status or '').strip() or None - if normalized_status and normalized_status not in {'queued', 'running', 'result_persisted', 'completed', 'needs_review', 'failed', 'cancelled'}: + if normalized_status and normalized_status not in {'queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'}: raise ValidationError('status is invalid') safe_page = max(1, int(page)) safe_page_size = min(100, max(1, int(page_size))) @@ -1140,13 +1490,15 @@ def get_order_extraction_diagnostic_run(*, admin_user_id: int, request_id: str | # Job message/error/result/payload 可能含输入输出,统一不出现在诊断 DTO。 } for job in jobs], 'progress_events': [{ - 'event_type': event.event_type, - 'node_type': event.node_type, - 'stage_code': event.stage_code, - 'status': event.event_status, - 'workflow_run_id': event.workflow_run_id, - 'node_execution_id': event.node_execution_id, - 'occurred_at': _diagnostic_iso(event.provider_occurred_at or event.received_at or event.created_at), + 'sequence_no': int(event.sequence_no or 0), + 'visibility': event.visibility, + 'event_code': event.event_code, + 'status': event.status, + 'unit_id': event.unit_id, + 'document_id': event.document_id, + 'reason_code': event.reason_code, + 'summary': event.summary_json, + 'occurred_at': _diagnostic_iso(event.occurred_at or event.received_at or event.created_at), } for event in events], 'units': [{ 'unit_id': unit.id, @@ -1194,14 +1546,23 @@ def transition_order_extraction_run( Args: run: 已加载且由调用方持有事务锁的 Run。 - target_status: 必须是当前状态允许的下一状态;`result_persisted` 后禁止回退失败或取消。 + target_status: 必须是当前状态允许的下一状态;终态后禁止回退到处理中。 phase: 可选细分阶段;不改变领域状态机语义。 - result: 仅 `result_persisted/completed/needs_review` 可写的安全业务摘要。 + result: 仅 `completed/partially_completed/review_required` 可写的安全业务摘要。 error_code/error_message: 仅 failed 状态可写;不得包含凭据或文档全文。 Returns: 已更新但尚未提交的 Run。 """ current_status = str(run.status or '') + if current_status == 'failed' and target_status == 'review_required': + has_current_candidate = ShippingNoticeCandidate.query.filter_by( + order_extraction_run_id=int(run.id), is_current_version=True, + ).first() is not None + if not has_current_candidate: + raise ConflictError( + 'Failed run has no persisted candidate to recover', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_TRANSITION_INVALID', + ) if target_status not in RUN_TRANSITIONS.get(current_status, set()): raise ConflictError( f'Invalid order extraction run transition: {current_status} -> {target_status}', @@ -1229,7 +1590,7 @@ def transition_order_extraction_run( after={'status': target_status, 'phase': phase or target_status, 'lock_version': int(run.lock_version or 0)}, metadata={'target_status': target_status}, ) - if target_status == 'running' and run.started_at is None: + if target_status == 'processing' and run.started_at is None: run.started_at = now intake_ids = [member.intake_id for member in run.intakes] intake_rows = ( @@ -1249,20 +1610,23 @@ def transition_order_extraction_run( intake.order_extraction_status = 'extracting' intake.order_extraction_error_code = None intake.order_extraction_error_message = None - elif target_status == 'running': + elif target_status == 'processing': for intake in intake_rows: intake.order_extraction_status = 'extracting' intake.order_extraction_error_code = None intake.order_extraction_error_message = None - if target_status == 'result_persisted': + if target_status in {'completed', 'partially_completed', 'review_required'}: run.result_persisted_at = now - run.result_json = result or {} - run.error_code = None - run.error_message = None - elif target_status in {'completed', 'needs_review'}: if result is not None: run.result_json = result + run.error_code = None + run.error_message = None run.finished_at = now + intake_status = 'completed' if target_status == 'completed' else 'partially_completed' + for intake in intake_rows: + intake.order_extraction_status = intake_status + intake.order_extraction_error_code = None + intake.order_extraction_error_message = None elif target_status == 'failed': run.error_code = str(error_code or 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED')[:64] run.error_message = str(error_message or 'Order extraction failed')[:2000] @@ -1280,7 +1644,7 @@ def transition_order_extraction_run( intake.order_extraction_status = 'failed' intake.order_extraction_error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_CANCELLED' intake.order_extraction_error_message = 'Order extraction was cancelled' - if target_status in {'completed', 'needs_review', 'failed', 'cancelled'}: + if target_status in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'}: # 仅新产生的终态创建提醒;历史 Run 不回填,重复终态路径也不覆盖既有提醒时间。 if run.attention_generated_at is None: run.attention_generated_at = now @@ -1314,15 +1678,14 @@ def _restore_candidates_after_failed_reparse(run: ShippingOrderExtractionRun) -> def mark_order_extraction_persistence_started(run: ShippingOrderExtractionRun) -> None: - """在主业务事务内投影HXOPS落库阶段,避免与冻结输入校验产生跨Session写竞争。""" - if run.status in {'completed', 'needs_review', 'failed', 'cancelled'}: + """在主业务事务内刷新活跃时间,供后续候选落库阶段衔接。""" + if run.status in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'}: return - run.active_stage_codes_json = ['hxops_persistence'] completed = {str(item) for item in (run.completed_stage_codes_json or []) if str(item)} - completed.add('deterministic_result_ready') + completed.add('candidate_ready') run.completed_stage_codes_json = sorted(completed) - run.current_stage_code = 'hxops_persistence' - run.progress_message_code = 'shipping.order_extraction.hxops_persistence' + run.current_stage_code = 'candidate_ready' + run.progress_message_code = 'shipping.order_extraction.events.candidate_ready' from app.services.shipping_notice.order_extraction_progress import MAPPING_VERSION run.progress_mapping_version = MAPPING_VERSION @@ -1338,13 +1701,13 @@ def sync_order_extraction_run_after_job_recovery(job: Any) -> None: job: 已由 `recover_stale_jobs` 条件更新成功并刷新的 Job。 """ run = ShippingOrderExtractionRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first() - if run is None or run.status in {'result_persisted', 'completed', 'needs_review', 'cancelled'}: + if run is None or run.status in {'completed', 'partially_completed', 'review_required', 'cancelled'}: return - if job.status == 'queued' and run.status == 'running': + if job.status == 'queued' and run.status == 'processing': transition_order_extraction_run(run, target_status='queued', phase='timeout_retry_queued') - elif job.status in {'failed', 'dead', 'cancelled'} and run.status in {'queued', 'running'}: + elif job.status in {'failed', 'dead', 'cancelled'} and run.status in {'queued', 'processing'}: if run.status == 'queued': - transition_order_extraction_run(run, target_status='running', phase='timeout_failing') + transition_order_extraction_run(run, target_status='processing', phase='timeout_failing') transition_order_extraction_run( run, target_status='failed', @@ -1379,7 +1742,7 @@ def get_order_extraction_run_health( Args: window_hours: 终态统计窗口,限制为 1-168 小时;活动 Run 不受窗口过滤。 queued_stale_seconds: queued 超过该秒数记为积压,限制为 30-86400。 - running_stale_seconds: running/result_persisted 超过该秒数记为卡住,限制为 60-86400。 + running_stale_seconds: processing 超过该秒数记为卡住,限制为 60-86400。 now: 测试可注入的 UTC 当前时间;生产调用留空。 Returns: 仅含聚合指标和最多 20 个异常 Run 编号的安全视图,不含输入、Provider 或错误正文。 @@ -1389,7 +1752,7 @@ def get_order_extraction_run_health( queued_threshold = min(max(int(queued_stale_seconds or 300), 30), 86400) running_threshold = min(max(int(running_stale_seconds or 1800), 60), 86400) since = current - timedelta(hours=hours) - active_statuses = {'queued', 'running', 'result_persisted'} + active_statuses = {'queued', 'processing'} rows = ( ShippingOrderExtractionRun.query .filter( @@ -1410,7 +1773,7 @@ def get_order_extraction_run_health( age_seconds = max(0, int((current - (row.started_at or row.created_at)).total_seconds())) if row.status == 'queued' and age_seconds >= queued_threshold: stale_rows.append(row) - elif row.status in {'running', 'result_persisted'} and age_seconds >= running_threshold: + elif row.status == 'processing' and age_seconds >= running_threshold: stale_rows.append(row) def elapsed_ms(start: datetime | None, end: datetime | None) -> int | None: @@ -1454,7 +1817,7 @@ def get_order_extraction_run_health( 'latency': { 'queue': _latency_summary(queue_ms), 'deterministic_parsing': _latency_summary(parsing_ms), - 'hxops_persistence': _latency_summary(persistence_ms), + 'candidate_materialization': _latency_summary(persistence_ms), 'total': _latency_summary(total_ms), }, # 仅暴露异常 Run 编号,最多 20 条,避免泄露输入/Provider/错误正文。 diff --git a/backend/app/services/shipping_notice/order_extraction_runtime_snapshot.py b/backend/app/services/shipping_notice/order_extraction_runtime_snapshot.py new file mode 100644 index 00000000..b654745d --- /dev/null +++ b/backend/app/services/shipping_notice/order_extraction_runtime_snapshot.py @@ -0,0 +1,81 @@ +""" +services/shipping_notice/order_extraction_runtime_snapshot.py + +用途:为订单抽取 Worker 提供“冻结正文 + 当前可用布局”的运行时快照兜底。 +依赖:Run 冻结 snapshot、ShippingNoticeDocument、document_layout.lifecycle、schema_mapping。 +逻辑:创建 Run 时不再等待布局终态,所以 Worker 执行单元时允许补读当前 ready layout; + 但正文、邮件上下文和其余输入仍严格来自 Run 冻结快照,避免退回到上传阶段的可变全量解析。 +""" + +from __future__ import annotations + +from typing import Any + +from app import db +from app.core.errors import ValidationError +from app.models import ShippingNoticeDocument +from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot +from app.services.shipping_notice.document_layout.schema_mapping import map_layout_document_to_schema +from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract + + +def _ready_layout(document: dict[str, Any]) -> dict[str, Any] | None: + """读取文档快照中的 ready layout;非 ready 一律视为缺失。""" + layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {} + return layout if layout.get('status') == 'ready' else None + + +def _runtime_layout_schema_candidates(*, run: Any, layout_snapshot: dict[str, Any]) -> list[dict[str, Any]]: + """基于当前 ready layout 重新计算冻结 Schema 的候选映射。""" + schema_snapshot = run.input_snapshot_json.get('schema') if isinstance(run.input_snapshot_json, dict) else {} + definition = schema_snapshot.get('definition') if isinstance(schema_snapshot.get('definition'), dict) else {} + contract = compile_table_header_contract(definition) + layout_candidate = ( + layout_snapshot.get('layout_candidate') + if isinstance(layout_snapshot.get('layout_candidate'), dict) + else None + ) + if layout_candidate is None: + return [] + try: + return map_layout_document_to_schema(layout_candidate, contract=contract) + except (TypeError, ValueError): + return [{ + 'mapping_status': 'failed', + 'issues': ['layout_schema_mapping_invalid'], + }] + + +def resolve_unit_runtime_snapshot(run: Any, unit: Any) -> tuple[dict[str, Any], dict[str, Any]]: + """ + 定位 Unit 对应的 Intake/Document,并在缺少 ready layout 时补读当前布局版本。 + + AI 触发时机:无需调用。Worker 进入单元执行前由 `order_extraction_workflow` 内部调用。 + 关键约束:只补读布局快照与其 Schema 映射;正文、邮件上下文、附件边界仍来自 Run 冻结 snapshot。 + """ + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + for intake in snapshot.get('intakes') or []: + if not isinstance(intake, dict) or int(intake.get('intake_id') or 0) != int(unit.intake_id): + continue + for raw_document in intake.get('documents') or []: + if not isinstance(raw_document, dict) or int(raw_document.get('document_id') or 0) != int(unit.document_id): + continue + document = dict(raw_document) + if _ready_layout(document) is not None: + return intake, document + persisted_document = db.session.get(ShippingNoticeDocument, int(unit.document_id)) + if persisted_document is None: + return intake, document + runtime_layout = current_layout_snapshot(persisted_document) + if not isinstance(runtime_layout, dict) or runtime_layout.get('status') != 'ready': + return intake, document + document['layout_snapshot'] = runtime_layout + document['layout_schema_candidates'] = _runtime_layout_schema_candidates( + run=run, + layout_snapshot=runtime_layout, + ) + return intake, document + raise ValidationError( + 'Extraction unit is absent from the frozen run snapshot', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE', + ) diff --git a/backend/app/services/shipping_notice/order_extraction_snapshot_selection.py b/backend/app/services/shipping_notice/order_extraction_snapshot_selection.py new file mode 100644 index 00000000..bf6662f2 --- /dev/null +++ b/backend/app/services/shipping_notice/order_extraction_snapshot_selection.py @@ -0,0 +1,67 @@ +""" +services/shipping_notice/order_extraction_snapshot_selection.py + +用途:把发送阶段的附件选择计划映射为 Run 冻结快照中的文档范围。 +依赖:仅依赖选择计划 JSON 和文档基础字段,不触碰 ORM、布局或 Provider 结果。 +逻辑:阶段 2 发送后,Run 只应冻结当前计划选中的附件文档;邮件正文补充事实保留, + 其余未选附件不得偷偷混入 snapshot/plan,避免“本批发送”误扩大成整封邮件全量执行。 +""" + +from __future__ import annotations + +from typing import Any + + +def selected_attachment_keys_by_intake( + selection_snapshot: dict[str, Any] | None, +) -> dict[str, set[str]]: + """把脱敏选择计划压缩为 intake_no -> attachment_key 集合。""" + snapshot = selection_snapshot if isinstance(selection_snapshot, dict) else {} + rows = snapshot.get('items') if isinstance(snapshot.get('items'), list) else [] + selected: dict[str, set[str]] = {} + for row in rows: + if not isinstance(row, dict) or not row.get('selected'): + continue + intake_no = str(row.get('intake_no') or '').strip().upper() + attachment_key = str(row.get('attachment_key') or '').strip() + if not intake_no or not attachment_key: + continue + selected.setdefault(intake_no, set()).add(attachment_key) + return selected + + +def has_attachment_catalog(selection_snapshot: dict[str, Any] | None) -> bool: + """是否存在 EML 附件目录;普通单文件场景不应用目录选择规则。""" + snapshot = selection_snapshot if isinstance(selection_snapshot, dict) else {} + return int(snapshot.get('total_attachment_count') or 0) > 0 + + +def has_selected_attachments(selection_snapshot: dict[str, Any] | None) -> bool: + """发送计划里是否至少选中一个附件。""" + snapshot = selection_snapshot if isinstance(selection_snapshot, dict) else {} + return int(snapshot.get('selected_attachment_count') or 0) > 0 + + +def should_include_snapshot_document( + *, + selection_snapshot: dict[str, Any] | None, + intake_no: str, + document_type: str, + attachment_key: str | None, +) -> bool: + """ + 判定某个冻结 Document 是否应进入 Run snapshot。 + + 核心逻辑: + 1. 邮件正文永远保留,供补充事实合并使用; + 2. 普通单文件没有附件目录时,仍保留全部附件 Document; + 3. EML 场景只保留本次选择计划选中的附件,未选附件不能进入执行快照。 + """ + if str(document_type or '') == 'email_body': + return True + if not has_attachment_catalog(selection_snapshot): + return True + selected = selected_attachment_keys_by_intake(selection_snapshot) + normalized_intake = str(intake_no or '').strip().upper() + normalized_key = str(attachment_key or '').strip() + return bool(normalized_intake and normalized_key and normalized_key in selected.get(normalized_intake, set())) diff --git a/backend/app/services/shipping_notice/order_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index 8dae4b4d..e7828e59 100644 --- a/backend/app/services/shipping_notice/order_extraction_workflow.py +++ b/backend/app/services/shipping_notice/order_extraction_workflow.py @@ -13,6 +13,9 @@ from dataclasses import dataclass from typing import Any, Literal from app.core.errors import ValidationError +from app.services.shipping_notice.order_extraction_runtime_snapshot import ( + resolve_unit_runtime_snapshot, +) from app.services.shipping_notice.document_layout.html_table import parse_html_grid from app.services.shipping_notice.document_layout.order_profile import ( OrderDocumentProfile, @@ -42,18 +45,8 @@ class DeterministicRouteResult: def _unit_snapshot(run: Any, unit: Any) -> tuple[dict[str, Any], dict[str, Any]]: - """从 Run 冻结快照定位一个单元的 Intake 与 Document,禁止回读可变正文。""" - snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} - for intake in snapshot.get('intakes') or []: - if not isinstance(intake, dict) or int(intake.get('intake_id') or 0) != int(unit.intake_id): - continue - for document in intake.get('documents') or []: - if isinstance(document, dict) and int(document.get('document_id') or 0) == int(unit.document_id): - return intake, document - raise ValidationError( - 'Extraction unit is absent from the frozen run snapshot', - code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE', - ) + """从 Run 快照定位单元,并在必要时补读当前 ready layout。""" + return resolve_unit_runtime_snapshot(run, unit) def build_order_extraction_execution_snapshot(run: Any, *, unit: Any) -> dict[str, str]: @@ -332,9 +325,12 @@ def _coordinate_v2_profile_rows( profile = _frozen_coordinate_profile(raw_profile) evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} + page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} - characters = tables.get(str(raw_table.get('table_id') or '')) - page_size = pages.get(str(raw_table.get('page_no') or '')) + page_no = int(raw_table.get('page_no') or 1) + # 整页坐标是 v2 区域的权威证据;检测表格漏掉续页时仍可读取该页模板区域。 + characters = page_glyphs.get(str(page_no)) or tables.get(str(raw_table.get('table_id') or '')) + page_size = pages.get(str(page_no)) if not isinstance(characters, list) or not isinstance(page_size, dict): return None try: @@ -347,7 +343,6 @@ def _coordinate_v2_profile_rows( return None rows: list[dict[str, Any]] = [] for region in profile.table_regions: - page_no = int(raw_table.get('page_no') or 1) if region.page_scope == 'first_page' and page_no != 1: continue if region.page_scope == 'continuation_pages' and page_no <= 1: @@ -510,7 +505,16 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]: issues: list[str] = [] matched_any = False cross_page_carries: dict[tuple[str, str], dict[str, Any]] = {} - for raw_table in sorted((item for item in layout.get('tables') or [] if isinstance(item, dict)), key=lambda item: (int(item.get('page_no') or 1), str(item.get('table_id') or ''))): + raw_tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)] + # 坐标模板按页执行,避免“模板两页、检测器只识别一张表”时续页被静默遗漏。 + if v2_profiles: + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} + raw_tables = [ + {'table_id': f'page-{page_no}', 'page_no': int(page_no)} + for page_no in sorted(pages, key=lambda value: int(value)) + ] + for raw_table in sorted(raw_tables, key=lambda item: (int(item.get('page_no') or 1), str(item.get('table_id') or ''))): if not isinstance(raw_table, dict): continue table_id = str(raw_table.get('table_id') or '') @@ -928,45 +932,77 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult 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) - approved_tables = [ - item for item in tables - if bool(item.get('auto_create_approved')) - ] # 文档出现多个模板表时不猜测其业务关系,即使其中一个模板已批准也必须人工复核。 if not tables: - decision['fallback_reason_codes'] = ['no_layout_table'] + decision['fallback_reason_codes'] = ['business_table_not_found'] return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision) if len(tables) != 1: - decision['fallback_reason_codes'] = ['multiple_tables_detected'] + decision['fallback_reason_codes'] = ['multiple_business_tables'] return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision) - if len(approved_tables) != 1: - decision['fallback_reason_codes'] = ['profile_not_auto_create_approved'] - return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision) - selected = approved_tables[0] + selected = tables[0] decision.update({ 'selected_profile_code': selected.get('profile_code'), 'selected_profile_id': selected.get('profile_id'), 'selected_profile_version': selected.get('profile_version'), 'selected_profile_checksum': selected.get('profile_checksum'), - 'auto_create_approved': True, + 'auto_create_approved': bool(selected.get('auto_create_approved')), 'business_table_count': 1, 'matched_table_count': 1, }) confirmed_order_fields = _confirmed_profile_order_fields(run, unit=unit) orders, reason_code = _build_approved_profile_order_result( - unit=unit, intake=intake, schema=schema, definition=definition, table=approved_tables[0], + unit=unit, intake=intake, schema=schema, definition=definition, table=selected, confirmed_order_fields=confirmed_order_fields, ) + if orders is None and reason_code in {'row_needs_review', 'required_field_missing'}: + # Keep the matched table as an editable candidate. Missing fields are then + # visible to the reviewer instead of discarding the entire PDF result. + orders, review_reason = _build_approved_profile_order_result( + unit=unit, intake=intake, schema=schema, definition=definition, table=selected, + confirmed_order_fields=confirmed_order_fields, allow_manual_review=True, + ) + 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) + reason_code = review_reason or reason_code if orders is None: - decision['fallback_reason_codes'] = [reason_code or 'no_parsed_lines'] + 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) decision['parsed_table_count'] = 1 decision['business_table_count'] = 1 decision['matched_table_count'] = 1 decision['document_table_count'] = len(tables) + if not bool(selected.get('auto_create_approved')): + # 模板匹配仍可提供给人工编辑,但永远不带自动接受标记或自动建单资格。 + for order in orders: + 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) +def _profile_row_review_details(table: dict[str, Any]) -> list[dict[str, Any]]: + """将本次模板行校验问题压缩为可展示、可定位的人工复核清单。""" + details: list[dict[str, Any]] = [] + for row_index, row in enumerate(table.get('rows') or [], 1): + if not isinstance(row, dict) or row.get('status') == 'parsed': + continue + for issue in row.get('issues') or []: + code = str(issue or '').strip() + if code.startswith('order_profile_field_invalid:'): + details.append({ + 'line_number': row_index, + 'field_code': code.rsplit(':', 1)[-1], + 'reason_code': 'invalid_value', + }) + else: + details.append({'line_number': row_index, 'field_code': None, 'reason_code': 'needs_review'}) + return details + + def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, Any]] | None: """兼容旧调用方:仅在结构化路由允许确定性解析时返回订单数组。""" result = route_deterministic_unit(run, unit=unit) @@ -976,14 +1012,14 @@ def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, An def _route_reason_for_issue(issue: str) -> str: """把内部解析问题收敛为管理员可长期依赖的稳定路由原因码。""" mapping = { - 'order_profile_evidence_insufficient': 'profile_evidence_insufficient', - 'order_profile_no_match': 'profile_no_match', + 'order_profile_evidence_insufficient': 'required_anchor_missing', + 'order_profile_no_match': 'profile_not_found', 'order_profile_ambiguous': 'profile_ambiguous', - 'order_profile_layout_drift': 'profile_layout_drift', - 'order_profile_snapshot_field_mismatch': 'profile_schema_field_mismatch', + 'order_profile_layout_drift': 'profile_drift_detected', + 'order_profile_snapshot_field_mismatch': 'required_field_missing', 'order_profile_multiple_matches': 'profile_ambiguous', } - return mapping.get(issue, 'profile_layout_drift') + return mapping.get(issue, 'profile_drift_detected') def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfileV2: @@ -999,6 +1035,7 @@ def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfileV2: def _build_approved_profile_order_result( *, unit: Any, intake: dict[str, Any], schema: dict[str, Any], definition: dict[str, Any], table: dict[str, Any], confirmed_order_fields: list[dict[str, Any]] | None = None, + allow_manual_review: bool = False, ) -> tuple[list[dict[str, Any]] | None, str | None]: """ 把已批准 Profile 本次实际解析的唯一完整表格转换为零 Provider 订单。 @@ -1026,12 +1063,15 @@ def _build_approved_profile_order_result( } line_groups: list[dict[str, Any]] = [] header_values: dict[str, list[dict[str, Any]]] = {} + has_review_rows = False for row in table.get('rows') or []: # Profile parser 已判定 deleted/invalid 行不可进入订单;禁止把部分解析结果当作完整订单。 if not isinstance(row, dict) or row.get('status') == 'deleted': continue if row.get('status') != 'parsed' or row.get('issues'): - return None, 'row_needs_review' + if not allow_manual_review: + return None, 'row_needs_review' + has_review_rows = True line_fields: list[dict[str, Any]] = [] for raw in row.get('fields') or []: if not isinstance(raw, dict): @@ -1058,8 +1098,8 @@ def _build_approved_profile_order_result( if len(unique) != 1: # Multiple document-level PO values cannot be attributed to individual lines. if field_id in po_field_ids: - return None, 'multiple_business_tables_ambiguous' - return None, 'header_value_conflict' + return None, 'multiple_po_detected' + return None, 'required_field_missing' header_fields.append({'field_id': field_id, 'observations': [observations[0]]}) present_header = {item['field_id'] for item in header_fields} for candidate in confirmed_order_fields or []: @@ -1068,7 +1108,7 @@ def _build_approved_profile_order_result( continue if field_id in present_header: # Header table evidence and independent order-field evidence must never silently compete. - return None, 'header_value_conflict' + return None, 'required_field_missing' header_fields.append({'field_id': field_id, '_hxops_order_field_evidence': True, 'observations': [{ 'value': candidate.get('value'), 'document_id': int(unit.document_id), 'quote': str(candidate.get('value') or '')[:1000], 'confidence': 1.0, @@ -1082,17 +1122,21 @@ def _build_approved_profile_order_result( }]}) present_header.add(field_id) if not line_groups: - return None, 'no_parsed_lines' + return None, 'business_table_not_found' for config in fields: if not config.get('required'): continue field_id = str(config.get('field_id') or '') + if allow_manual_review: + continue if config.get('scope') == 'header' and field_id not in present_header and field_id not in po_field_ids: - return None, 'required_header_missing' + if field_id in po_field_ids: + return None, 'po_missing' + return None, 'required_field_missing' if config.get('scope') == 'line' and any( field_id not in {item['field_id'] for item in group['fields']} for group in line_groups ): - return None, 'required_line_field_missing' + return None, 'required_field_missing' base_order = { 'schema_version_id': schema.get('schema_version_id'), 'schema_checksum': schema.get('checksum'), 'classification': 'shipping_request', 'classification_confidence': 1.0, @@ -1100,9 +1144,11 @@ def _build_approved_profile_order_result( 'primary_document_id': int(unit.document_id), 'header_fields': header_fields, 'lines': line_groups, 'conflicts': [], # Only this frozen approved-profile builder may add this internal marker. - '_hxops_acceptance': 'approved_deterministic_profile_v1', } - # A PDF can yield multiple Tasks only when every parsed line carries one explicit PO. + if not has_review_rows: + # Only this frozen approved-profile builder may add this internal marker. + base_order['_hxops_acceptance'] = 'approved_deterministic_profile_v1' + # 当前业务约束:一份 PDF 只能形成一个 PO;检测到多个 PO 必须整体拒识并转人工复核。 line_pos = [] for group in line_groups: matches = [field for field in group['fields'] if field.get('field_id') in po_field_ids] @@ -1123,29 +1169,7 @@ def _build_approved_profile_order_result( 'observations': [po_field.get('observations', [None])[0]], }) return [base_order], None - if len(line_pos) != len(line_groups): - return None, 'multiple_business_tables_ambiguous' - orders: list[dict[str, Any]] = [] - for value in sorted(distinct_pos): - po_lines = [] - po_field_id = None - po_observation = None - for line_value, group, po_field in line_pos: - if line_value != value: - continue - cloned = json.loads(json.dumps(group)) - cloned['fields'] = [field for field in cloned['fields'] if field.get('field_id') not in po_field_ids] - po_lines.append(cloned) - po_field_id = str(po_field.get('field_id') or '') - po_observation = po_field.get('observations', [None])[0] - if not po_field_id or not isinstance(po_observation, dict): - return None, 'required_header_missing' - order = json.loads(json.dumps(base_order)) - order['lines'] = po_lines - order['header_fields'] = [field for field in order['header_fields'] if field.get('field_id') not in po_field_ids] - order['header_fields'].append({'field_id': po_field_id, 'observations': [po_observation]}) - orders.append(order) - return orders, None + return None, 'multiple_po_detected' def _build_approved_profile_order( diff --git a/backend/app/services/shipping_notice/order_extraction_workspace_projection.py b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py new file mode 100644 index 00000000..cc5cce78 --- /dev/null +++ b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py @@ -0,0 +1,403 @@ +""" +backend/app/services/shipping_notice/order_extraction_workspace_projection.py + +用途:把订单抽取 Run/Unit 的数据库事实投影为工作台摘要和按 PDF 的详情列表。 +依赖:ShippingOrderExtractionRun/Unit/RouteDecision/ProgressEvent ORM、冻结 snapshot 和 Unit 结果 JSON。 +逻辑:只输出用户可理解的业务信息;文件名、原因码、模板摘要和可操作按钮都在这里统一裁剪与组装。 +""" + +from __future__ import annotations + +from collections import Counter +from typing import Any + +from app.models import ( + ShippingOrderExtractionProgressEvent, + ShippingOrderExtractionRouteDecision, + ShippingOrderExtractionRun, + ShippingOrderExtractionUnit, +) + +ACTIVE_UNIT_STATUSES = {'pending', 'routing', 'matching_profile', 'extracting', 'merging_supplement'} + + +def _safe_file_name(value: Any) -> str | None: + """只保留用户可见文件名,阻断路径片段进入工作台响应。""" + text = str(value or '').strip().replace('\\', '/') + if not text: + return None + name = text.split('/')[-1].strip() + return name[:255] or None + + +def _snapshot_documents(run: ShippingOrderExtractionRun) -> dict[int, dict[str, Any]]: + """按冻结快照读取文档元数据,避免为展示层回读可变附件记录。""" + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + items: dict[int, dict[str, Any]] = {} + for intake in snapshot.get('intakes') or []: + if not isinstance(intake, dict): + continue + intake_id = int(intake.get('intake_id') or 0) + for document in intake.get('documents') or []: + if not isinstance(document, dict): + continue + document_id = int(document.get('document_id') or 0) + if document_id <= 0: + continue + items[document_id] = { + 'document_id': document_id, + 'intake_id': intake_id, + 'file_name': _safe_file_name(document.get('filename')), + 'document_type': str(document.get('document_type') or ''), + } + return items + + +def _snapshot_profiles(run: ShippingOrderExtractionRun) -> dict[tuple[str, int], dict[str, Any]]: + """从冻结快照中读取模板展示信息,避免文档详情受后续模板修改影响。""" + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + profiles: dict[tuple[str, int], dict[str, Any]] = {} + for item in snapshot.get('order_document_profiles') or []: + if not isinstance(item, dict): + continue + code = str(item.get('profile_code') or '').strip() + version = int(item.get('version') or 0) + if not code or version <= 0: + continue + profiles[(code, version)] = { + 'code': code, + 'name': str(item.get('display_name') or item.get('profile_code') or '').strip() or None, + 'version': version, + } + return profiles + + +def _schema_field_codes(run: ShippingOrderExtractionRun) -> dict[str, str]: + """建立 field_id -> field_code 映射,供详情投影从订单快照中提取业务字段。""" + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {} + return { + str(field.get('field_id') or ''): str(field.get('field_code') or '') + for field in schema.get('definition', {}).get('fields') or [] + if isinstance(field, dict) and str(field.get('field_id') or '').strip() + } + + +def _field_values(fields: Any, *, field_codes: dict[str, str], targets: set[str]) -> list[str]: + """从候选订单字段中提取稳定业务值,不把坐标或证据细节暴露给工作台。""" + values: list[str] = [] + if not isinstance(fields, list): + return values + for item in fields: + if not isinstance(item, dict): + continue + if field_codes.get(str(item.get('field_id') or '')) not in targets: + continue + for observation in item.get('observations') or []: + if not isinstance(observation, dict): + continue + text = str(observation.get('value') or '').strip() + if text and text not in values: + values.append(text) + return values + + +def _orders_from_unit(unit: ShippingOrderExtractionUnit) -> list[dict[str, Any]]: + """读取单元最终候选订单列表;非成功单元返回空列表。""" + result = unit.result_json if isinstance(unit.result_json, dict) else {} + return [item for item in result.get('orders') or [] if isinstance(item, dict)] + + +def _candidate_count(unit: ShippingOrderExtractionUnit) -> int: + """统计单元可确认候选数;review_required 保留的中间结果不能算作成功候选。""" + if str(unit.status or '') != 'candidate_ready': + return 0 + return len(_orders_from_unit(unit)) + + +def _first_po_number(orders: list[dict[str, Any]], *, field_codes: dict[str, str]) -> str | None: + """提取单元最主要的 PO 号码;多值时取首个稳定顺序值用于列表摘要。""" + for order in orders: + values = _field_values( + order.get('header_fields'), + field_codes=field_codes, + targets={'customer_po_number', 'po_number'}, + ) + if values: + return values[0] + return None + + +def _line_count(orders: list[dict[str, Any]]) -> int: + """统计候选订单总行数。""" + return sum(len(order.get('lines') or []) for order in orders if isinstance(order, dict)) + + +def _line_field_has_value( + orders: list[dict[str, Any]], + *, + field_codes: dict[str, str], + target: str, +) -> bool: + """判断候选订单行内是否存在指定业务字段值。""" + for order in orders: + if not isinstance(order, dict): + continue + for line in order.get('lines') or []: + if not isinstance(line, dict): + continue + if _field_values(line.get('fields'), field_codes=field_codes, targets={target}): + return True + return False + + +def _latest_route_decisions(run: ShippingOrderExtractionRun) -> dict[int, ShippingOrderExtractionRouteDecision]: + """按单元读取最新路由决策,用于展示模板命中结果。""" + decisions: dict[int, ShippingOrderExtractionRouteDecision] = {} + rows = ( + ShippingOrderExtractionRouteDecision.query.filter_by(run_id=run.id) + .order_by(ShippingOrderExtractionRouteDecision.unit_id.asc(), ShippingOrderExtractionRouteDecision.id.asc()) + .all() + ) + for row in rows: + decisions[int(row.unit_id)] = row + return decisions + + +def _latest_progress_events(run: ShippingOrderExtractionRun) -> tuple[dict[tuple[int, str], ShippingOrderExtractionProgressEvent], ShippingOrderExtractionProgressEvent | None]: + """收集每个单元每类事件的最新记录,并找出当前活动事件。""" + events: dict[tuple[int, str], ShippingOrderExtractionProgressEvent] = {} + current: ShippingOrderExtractionProgressEvent | None = None + rows = ( + ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id, visibility='workspace') + .order_by(ShippingOrderExtractionProgressEvent.sequence_no.asc(), ShippingOrderExtractionProgressEvent.id.asc()) + .all() + ) + for row in rows: + unit_id = int(row.unit_id or 0) + if unit_id > 0: + events[(unit_id, str(row.event_code or ''))] = row + if str(row.event_code or '') != 'run_completed': + current = row + return events, current + + +def _current_activity_reason_codes(event: ShippingOrderExtractionProgressEvent | None) -> list[str]: + """归并当前事件的顶层 reason_code 与 summary.reason_codes,供聊天卡直接展示。""" + if event is None: + return [] + summary = event.summary_json if isinstance(event.summary_json, dict) else {} + codes = { + str(event.reason_code or '').strip(), + *[ + str(code or '').strip() + for code in (summary.get('reason_codes') or []) + ], + } + return sorted(code for code in codes if code) + + +def _run_available_actions(run: ShippingOrderExtractionRun, units: list[ShippingOrderExtractionUnit]) -> list[str]: + """根据 Run 与 Unit 事实返回用户可见操作,前端不得自行推断。""" + actions = ['view_details'] + if run.status in {'review_required', 'partially_completed'} or any(unit.status == 'review_required' for unit in units): + 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 _document_available_actions(unit: ShippingOrderExtractionUnit) -> list[str]: + """按单元状态返回详情项可见操作。""" + if unit.status == 'candidate_ready': + return ['view_evidence', 'review_candidate'] + if unit.status == 'review_required': + return ['view_evidence', 'manual_review'] + return [] + + +def _email_supplement_projection( + unit: ShippingOrderExtractionUnit, + event_map: dict[tuple[int, str], ShippingOrderExtractionProgressEvent], + *, + field_codes: dict[str, str], +) -> dict[str, Any]: + """汇总正文补充的业务结果,避免让前端重算冲突逻辑。""" + event = event_map.get((int(unit.id), 'email_supplement_merged')) + summary = event.summary_json if event is not None and isinstance(event.summary_json, dict) else {} + orders = _orders_from_unit(unit) + if summary: + relation_codes = list(summary.get('relation_codes') or []) + conflict_count = int(summary.get('conflict_count') or 0) + status = str(summary.get('status') or 'none') + else: + relation_codes = sorted({ + str(order.get('_hxops_email_supplement_relation') or '').strip() + for order in orders + if isinstance(order, dict) and str(order.get('_hxops_email_supplement_relation') or '').strip() + }) + conflict_count = sum( + 1 + for order in orders if isinstance(order, dict) + for conflict in order.get('conflicts') or [] if isinstance(conflict, dict) + if str(conflict.get('reason') or '').strip() == 'supplement_relation_ambiguous' + ) + status = 'conflict' if conflict_count > 0 else 'merged' if relation_codes else 'none' + + def field_status(target: str) -> str: + if conflict_count > 0: + return 'conflict' + if target not in field_codes.values(): + return 'unavailable' + if not relation_codes: + return 'none' + return 'merged' if _line_field_has_value(orders, field_codes=field_codes, target=target) else 'none' + + return { + 'status': status, + 'relation_codes': relation_codes, + 'conflict_count': conflict_count, + 'reservation_id_status': field_status('reservation_id'), + 'source_type_status': field_status('inventory_source_hint'), + } + + +def _profile_projection( + unit: ShippingOrderExtractionUnit, + *, + route_by_unit: dict[int, ShippingOrderExtractionRouteDecision], + profiles_by_key: dict[tuple[str, int], dict[str, Any]], +) -> dict[str, Any] | None: + """返回单元命中的模板摘要;未命中或需人工时返回空。""" + route = route_by_unit.get(int(unit.id)) + if route is None: + return None + code = str(route.selected_profile_code or '').strip() + version = int(route.selected_profile_version or 0) + if not code or version <= 0: + return None + return profiles_by_key.get((code, version), {'code': code, 'name': code, 'version': version}) + + +def serialize_workspace_run_documents(run: ShippingOrderExtractionRun) -> list[dict[str, Any]]: + """ + 构建工作台按 PDF 展示的详情列表。 + + AI 触发时机:当工作台详情抽屉或聊天卡需要回答“哪份 PDF 成功、用了什么模板、为什么失败”时使用。 + """ + units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else [] + documents = _snapshot_documents(run) + profiles_by_key = _snapshot_profiles(run) + field_codes = _schema_field_codes(run) + route_by_unit = _latest_route_decisions(run) + event_map, _ = _latest_progress_events(run) + items: list[dict[str, Any]] = [] + for unit in units: + orders = _orders_from_unit(unit) + document = documents.get(int(unit.document_id), {}) + items.append({ + 'unit_id': int(unit.id), + 'document_id': int(unit.document_id), + 'file_name': document.get('file_name'), + 'status': unit.status, + 'selection_batch': int(unit.selection_batch) if unit.selection_batch is not None else None, + 'group_key': str(unit.group_key or '').strip() or None, + 'retry_status': str(unit.retry_status or '').strip() or None, + 'technical_failure_reason_code': str(unit.technical_failure_reason_code or '').strip() or None, + 'budget_cost': dict(unit.budget_cost_json or {}) if isinstance(unit.budget_cost_json, dict) else None, + 'po_number': _first_po_number(orders, field_codes=field_codes), + '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), + 'review_details': list((unit.result_json or {}).get('review_details') or []), + 'available_actions': _document_available_actions(unit), + }) + return items + + +def serialize_workspace_run(run: ShippingOrderExtractionRun) -> dict[str, Any]: + """ + 构建工作台订单抽取摘要。 + + AI 触发时机:工作台 Run 列表、聊天卡恢复和详情按钮都应直接消费这个投影,而不是自己统计 Unit。 + """ + units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else [] + documents = _snapshot_documents(run) + _, current_event = _latest_progress_events(run) + status_counter = Counter(str(unit.status or '') for unit in units) + current_activity = None + if run.status in {'queued', 'processing'}: + if current_event is not None: + current_document = documents.get(int(current_event.document_id or 0), {}) if current_event.document_id is not None else {} + current_activity = { + 'unit_id': int(current_event.unit_id) if current_event.unit_id is not None else None, + 'file_name': current_document.get('file_name'), + 'event_code': current_event.event_code, + 'selection_batch': int(current_event.summary_json.get('selection_batch') or 0) or None + if isinstance(current_event.summary_json, dict) else None, + 'reason_codes': _current_activity_reason_codes(current_event), + } + else: + pending_unit = next((unit for unit in units if unit.status in ACTIVE_UNIT_STATUSES), None) + if pending_unit is not None: + pending_document = documents.get(int(pending_unit.document_id), {}) + current_activity = { + 'unit_id': int(pending_unit.id), + 'file_name': pending_document.get('file_name'), + 'event_code': 'document_queued' if run.status == 'queued' else pending_unit.status, + 'selection_batch': int(pending_unit.selection_batch or 0) or None, + 'reason_codes': [], + } + return { + 'summary': { + 'total_documents': len(units), + 'pending_documents': sum(status_counter.get(status, 0) for status in {'pending'}), + 'processing_documents': sum(status_counter.get(status, 0) for status in {'routing', 'matching_profile', 'extracting', 'merging_supplement'}), + 'completed_documents': status_counter.get('candidate_ready', 0), + 'review_required_documents': status_counter.get('review_required', 0), + 'failed_documents': status_counter.get('failed', 0), + 'candidate_count': sum(_candidate_count(unit) for unit in units), + }, + 'current_activity': current_activity, + 'available_actions': _run_available_actions(run, units), + } + + +def serialize_workspace_run_chat_state(run: ShippingOrderExtractionRun) -> dict[str, Any]: + """ + 构建聊天消息使用的订单抽取状态卡。 + + AI 触发时机:聊天历史恢复、Run 轮询和终态持久化都必须复用这份用户态投影, + 不能继续把 Workflow/health 等旧展示语义塞回消息 payload。 + """ + projection = serialize_workspace_run(run) + summary = projection['summary'] if isinstance(projection.get('summary'), dict) else {} + current_activity = projection['current_activity'] if isinstance(projection.get('current_activity'), dict) else None + return { + 'status': str(run.status or 'queued'), + 'summary': { + 'totalDocuments': int(summary.get('total_documents') or 0), + 'pendingDocuments': int(summary.get('pending_documents') or 0), + 'processingDocuments': int(summary.get('processing_documents') or 0), + 'completedDocuments': int(summary.get('completed_documents') or 0), + '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), + }, + 'currentActivity': ( + { + 'unitId': int(current_activity.get('unit_id') or 0), + 'fileName': current_activity.get('file_name'), + 'eventCode': str(current_activity.get('event_code') or ''), + 'selectionBatch': int(current_activity.get('selection_batch') or 0) or None, + 'reasonCodes': [str(code) for code in current_activity.get('reason_codes') or [] if str(code).strip()], + } + if current_activity else None + ), + 'availableActions': [str(action) for action in projection.get('available_actions') or []], + 'terminal': str(run.status or '') not in {'queued', 'processing'}, + 'errorCode': str(run.error_code or '') or None, + 'startedAt': run.started_at.isoformat() + 'Z' if run.started_at else None, + 'finishedAt': run.finished_at.isoformat() + 'Z' if run.finished_at else None, + } diff --git a/backend/app/services/shipping_notice/order_freeze_service.py b/backend/app/services/shipping_notice/order_freeze_service.py index fceec6cf..cedb8a17 100644 --- a/backend/app/services/shipping_notice/order_freeze_service.py +++ b/backend/app/services/shipping_notice/order_freeze_service.py @@ -58,9 +58,11 @@ DATE_FIELDS = frozenset({'order_date', 'required_date', 'requested_receipt_date' def freeze_order_snapshot( task: ShippingTask, *, - actor_id: int, + actor_id: int | None, expected_order_data_version: int, rule_versions: dict[str, Any] | None = None, + freeze_mode: str = 'manual', + auto_freeze_policy: dict[str, Any] | None = None, ) -> ShippingOrderSnapshot: """ 冻结指定任务的已接受解析为不可变履约订单。 @@ -69,9 +71,11 @@ def freeze_order_snapshot( Args: task: 必须是当前用户有权操作且尚未冻结的任务。 - actor_id: 执行冻结的用户 ID,不能为空。 + actor_id: 执行冻结的用户 ID;自动冻结允许为空并记为系统执行。 expected_order_data_version: 用户界面读取到的版本;不匹配时拒绝覆盖。 rule_versions: 已冻结的订单/客户规则版本审计数据。 + freeze_mode: `manual` 表示人工冻结;`auto` 表示消费 Run 自动冻结门禁。 + auto_freeze_policy: 自动冻结时传入的 Run 级门禁摘要;人工路径忽略。 Returns: ShippingOrderSnapshot: 已落库的不可变快照。 @@ -88,7 +92,7 @@ def freeze_order_snapshot( return snapshot raise ConflictError('Order snapshot reference is invalid', code='SHIPPING.ORDER_SNAPSHOT_FROZEN') task = locked_task - if not actor_id: + if str(freeze_mode or 'manual') == 'manual' and not actor_id: raise ValidationError('Snapshot freeze requires an operator', code='SHIPPING.ORDER_FREEZE_BLOCKED') actual_version = int(task.order_data_version or 1) if actual_version != int(expected_order_data_version): @@ -101,7 +105,14 @@ def freeze_order_snapshot( policy, configs = _policy_configs(extraction) customer_match = _confirmed_ordering_customer(extraction) from app.services.shipping_notice.freeze_readiness_service import assert_freeze_readiness - assert_freeze_readiness(task=task, extraction=extraction, policy=policy, configs=configs) + assert_freeze_readiness( + task=task, + extraction=extraction, + policy=policy, + configs=configs, + freeze_mode=freeze_mode, + auto_freeze_policy=auto_freeze_policy, + ) _assert_llm_review_gate(extraction, configs) header_values, line_values = _extraction_values(extraction, configs) diff --git a/backend/app/services/shipping_notice/preview_grant_store.py b/backend/app/services/shipping_notice/preview_grant_store.py new file mode 100644 index 00000000..ec166831 --- /dev/null +++ b/backend/app/services/shipping_notice/preview_grant_store.py @@ -0,0 +1,70 @@ +""" +backend/app/services/shipping_notice/preview_grant_store.py + +用途:为订单文档模板页预览令牌提供受控存储后端选择。 +依赖:Flask current_app、统一 Redis client。 +逻辑:生产默认强依赖 Redis;开发单进程可按配置回退到进程内一次性令牌存储。 +""" + +from __future__ import annotations + +import threading +import time +from typing import Any + +from flask import current_app + +from app.core.errors import ServiceUnavailableError +from app.services.redis_client import get_redis_client + + +class _MemoryGrantStore: + """为单进程开发环境提供最小 setex/getdel 语义,保持一次性令牌行为。""" + + def __init__(self) -> None: + self._lock = threading.Lock() + self._items: dict[str, tuple[float, str]] = {} + + def setex(self, key: str, ttl_seconds: int, value: str) -> None: + expires_at = time.time() + max(int(ttl_seconds), 1) + with self._lock: + self._items[key] = (expires_at, value) + + def getdel(self, key: str) -> str | None: + now = time.time() + with self._lock: + row = self._items.pop(key, None) + if row is None: + return None + expires_at, value = row + if expires_at <= now: + return None + return value + + +_memory_store = _MemoryGrantStore() + + +def _memory_fallback_allowed() -> bool: + """仅在显式允许时启用内存兜底,避免生产多 Worker 场景放松预览边界。""" + if not current_app: + return False + return bool(current_app.config.get('ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK', False)) + + +def preview_grant_store() -> Any: + """ + 返回模板预览授权存储。 + + AI/调用方触发时机:仅供订单文档模板预览接口内部使用。Redis 不可用时, + 只有启用了开发兜底配置,才允许退回进程内一次性 token 存储。 + """ + client = get_redis_client() + if client is not None: + return client + if _memory_fallback_allowed(): + return _memory_store + raise ServiceUnavailableError( + 'Order profile preview is temporarily unavailable', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE', + ) diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index 2da61ba6..1329a093 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -118,8 +118,8 @@ def recover_stale_shipping_notice_jobs() -> tuple[int, str]: """ 回收通用 jobs 表里超时的发货任务,并顺带消费 RPA callback cleanup 队列。 - 核心逻辑:单票编排与预解析分超时配置回收;预解析 Job 回收同事务同步 Intake, - 避免 Job 已 requeue/failed 而 Intake 永久 parsing。 + 核心逻辑:按 Job 类型分别回收单票编排、预解析、订单抽取与版面解析; + 预解析和订单抽取回收时同步领域状态,避免 Job 已 requeue/failed 而界面永久等待。 """ from app.jobs.queue import recover_stale_jobs from app.services.shipping_notice.intake_parse_workflow import ( @@ -146,6 +146,16 @@ def recover_stale_shipping_notice_jobs() -> tuple[int, str]: job_type=JobType.SHIPPING_NOTICE_PARSE, on_recovered=sync_intake_after_parse_job_recovery, ) + from app.services.shipping_notice.order_extraction_run_service import ( + sync_order_extraction_run_after_job_recovery, + ) + + extraction_count = recover_stale_jobs( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + timeout_seconds=run_timeout, + job_type=JobType.SHIPPING_ORDER_EXTRACTION, + on_recovered=sync_order_extraction_run_after_job_recovery, + ) from app.services.shipping_notice.document_layout.lifecycle import sync_layout_after_job_recovery layout_count = recover_stale_jobs( @@ -156,16 +166,17 @@ def recover_stale_shipping_notice_jobs() -> tuple[int, str]: job_type=JobType.SHIPPING_DOCUMENT_LAYOUT, on_recovered=sync_layout_after_job_recovery, ) - count = int(run_count) + int(parse_count) + int(layout_count) + count = int(run_count) + int(parse_count) + int(extraction_count) + int(layout_count) cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs() if cleanup_warnings: logger.warning('rpa callback cleanup warnings: %s', '; '.join(cleanup_warnings[:5])) if count: logger.warning( - 'recovered %s stale shipping_notice job(s) (run=%s parse=%s layout=%s)', + 'recovered %s stale shipping_notice job(s) (run=%s parse=%s extraction=%s layout=%s)', count, run_count, parse_count, + extraction_count, layout_count, ) if cleanup_count: diff --git a/backend/migrations/versions/0ab45c6d7e8f_rebuild_order_extraction_progress_facts.py b/backend/migrations/versions/0ab45c6d7e8f_rebuild_order_extraction_progress_facts.py new file mode 100644 index 00000000..5efb5f02 --- /dev/null +++ b/backend/migrations/versions/0ab45c6d7e8f_rebuild_order_extraction_progress_facts.py @@ -0,0 +1,228 @@ +"""rebuild order extraction progress facts + +Revision ID: 0ab45c6d7e8f +Revises: 09a23b4c5d6e +Create Date: 2026-07-28 15:30:00.000000 + +用途:重建订单解析 Run/Unit/Event 的确定性业务进度事实模型。 +依赖:shipping_order_extraction_runs、shipping_order_extraction_units、shipping_order_extraction_progress_events。 +逻辑:不做旧 Workflow 字段兼容,直接替换为 Run 汇总与 Unit 业务事件结构。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = '0ab45c6d7e8f' +down_revision = '09a23b4c5d6e' +branch_labels = None +depends_on = None + + +def _columns(inspector: sa.Inspector, table_name: str) -> set[str]: + return {column['name'] for column in inspector.get_columns(table_name)} + + +def _indexes(inspector: sa.Inspector, table_name: str) -> set[str]: + return {index['name'] for index in inspector.get_indexes(table_name)} + + +def _has_table(inspector: sa.Inspector, table_name: str) -> bool: + return table_name in inspector.get_table_names() + + +def _check_constraints(inspector: sa.Inspector, table_name: str) -> set[str]: + return { + constraint['name'] + for constraint in inspector.get_check_constraints(table_name) + if constraint.get('name') + } + + +def upgrade() -> None: + """切换到订单解析确定性业务状态、Unit 摘要字段和新事件表。""" + bind = op.get_bind() + inspector = sa.inspect(bind) + run_checks = _check_constraints(inspector, 'shipping_order_extraction_runs') + unit_checks = _check_constraints(inspector, 'shipping_order_extraction_units') + + if 'ck_shipping_order_extraction_runs_status' in run_checks: + op.drop_constraint('ck_shipping_order_extraction_runs_status', 'shipping_order_extraction_runs', type_='check') + if 'ck_shipping_order_extraction_units_status' in unit_checks: + op.drop_constraint('ck_shipping_order_extraction_units_status', 'shipping_order_extraction_units', type_='check') + + # 兼容历史运行状态,避免存量数据在新增约束时失败。 + op.execute( + sa.text( + """ + UPDATE shipping_order_extraction_runs + SET status = CASE status + WHEN 'running' THEN 'processing' + WHEN 'result_persisted' THEN 'completed' + WHEN 'needs_review' THEN 'review_required' + ELSE status + END + WHERE status IN ('running', 'result_persisted', 'needs_review') + """ + ) + ) + op.execute( + sa.text( + """ + UPDATE shipping_order_extraction_units + SET status = CASE status + WHEN 'running' THEN 'extracting' + WHEN 'succeeded' THEN 'candidate_ready' + WHEN 'skipped' THEN 'review_required' + ELSE status + END + WHERE status IN ('running', 'succeeded', 'skipped') + """ + ) + ) + + with op.batch_alter_table('shipping_order_extraction_runs') as batch: + batch.create_check_constraint( + 'ck_shipping_order_extraction_runs_status', + "status IN ('queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled')", + ) + for index_name in ('uq_shipping_order_extraction_runs_active_conversation',): + if index_name in _indexes(inspector, 'shipping_order_extraction_runs'): + op.drop_index(index_name, table_name='shipping_order_extraction_runs') + op.create_index( + 'uq_shipping_order_extraction_runs_active_conversation', + 'shipping_order_extraction_runs', + ['user_id', 'owner_agent_id', 'conversation_id'], + unique=True, + sqlite_where=sa.text("status IN ('queued', 'processing')"), + postgresql_where=sa.text("status IN ('queued', 'processing')"), + ) + + with op.batch_alter_table('shipping_order_extraction_units') as batch: + batch.create_check_constraint( + 'ck_shipping_order_extraction_units_status', + "status IN ('pending', 'routing', 'matching_profile', 'extracting', 'merging_supplement', 'candidate_ready', 'review_required', 'failed', 'cancelled')", + ) + existing_columns = _columns(inspector, 'shipping_order_extraction_units') + if 'reason_code' not in existing_columns: + batch.add_column(sa.Column('reason_code', sa.String(length=64), nullable=True)) + if 'summary_json' not in existing_columns: + batch.add_column(sa.Column('summary_json', sa.JSON(), nullable=True)) + if 'last_activity_at' not in existing_columns: + batch.add_column(sa.Column('last_activity_at', sa.DateTime(), nullable=True)) + + if _has_table(inspector, 'shipping_order_extraction_progress_events'): + op.drop_table('shipping_order_extraction_progress_events') + op.create_table( + 'shipping_order_extraction_progress_events', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('run_id', sa.Integer(), sa.ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'), nullable=False), + sa.Column('unit_id', sa.Integer(), sa.ForeignKey('shipping_order_extraction_units.id', ondelete='CASCADE'), nullable=True), + sa.Column('document_id', sa.Integer(), nullable=True), + sa.Column('job_id', sa.Integer(), sa.ForeignKey('jobs.id'), nullable=True), + sa.Column('attempt_count', sa.Integer(), nullable=True), + sa.Column('sequence_no', sa.Integer(), nullable=False), + sa.Column('visibility', sa.String(length=32), nullable=False, server_default='workspace'), + sa.Column('event_code', sa.String(length=64), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False, server_default='completed'), + sa.Column('occurred_at', sa.DateTime(), nullable=True), + sa.Column('reason_code', sa.String(length=64), nullable=True), + sa.Column('received_at', sa.DateTime(), nullable=False), + sa.Column('summary_json', sa.JSON(), nullable=True), + sa.Column('idempotency_key', sa.String(length=128), nullable=False), + sa.Column('mapping_version', sa.String(length=32), nullable=True), + sa.Column('expires_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('idempotency_key', name='uq_shipping_order_extraction_progress_event_key'), + sa.UniqueConstraint('run_id', 'sequence_no', name='uq_shipping_order_extraction_progress_event_sequence'), + ) + op.create_index( + 'ix_shipping_order_extraction_progress_events_run_sequence', + 'shipping_order_extraction_progress_events', + ['run_id', 'sequence_no'], + ) + op.create_index( + 'ix_shipping_order_extraction_progress_events_expires_id', + 'shipping_order_extraction_progress_events', + ['expires_at', 'id'], + ) + op.create_index( + 'ix_shipping_order_extraction_progress_events_run_visibility', + 'shipping_order_extraction_progress_events', + ['run_id', 'visibility', 'sequence_no'], + ) + + +def downgrade() -> None: + """恢复旧的 Workflow 观察器阶段结构,仅用于受控回滚。""" + bind = op.get_bind() + inspector = sa.inspect(bind) + + if _has_table(inspector, 'shipping_order_extraction_progress_events'): + op.drop_table('shipping_order_extraction_progress_events') + op.create_table( + 'shipping_order_extraction_progress_events', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('run_id', sa.Integer(), sa.ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'), nullable=False), + sa.Column('job_id', sa.Integer(), sa.ForeignKey('jobs.id'), nullable=True), + sa.Column('attempt_count', sa.Integer(), nullable=True), + sa.Column('workflow_run_id', sa.String(length=128), nullable=True), + sa.Column('node_execution_id', sa.String(length=128), nullable=True), + sa.Column('event_type', sa.String(length=64), nullable=False), + sa.Column('node_type', sa.String(length=64), nullable=True), + sa.Column('stage_code', sa.String(length=64), nullable=True), + sa.Column('event_status', sa.String(length=32), nullable=True), + sa.Column('provider_occurred_at', sa.DateTime(), nullable=True), + sa.Column('received_at', sa.DateTime(), nullable=False), + sa.Column('details_json', sa.JSON(), nullable=True), + sa.Column('idempotency_key', sa.String(length=128), nullable=False), + sa.Column('mapping_version', sa.String(length=32), nullable=True), + sa.Column('expires_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('idempotency_key', name='uq_shipping_order_extraction_progress_event_key'), + ) + op.create_index( + 'ix_shipping_order_extraction_progress_events_run_created', + 'shipping_order_extraction_progress_events', + ['run_id', 'created_at'], + ) + op.create_index( + 'ix_shipping_order_extraction_progress_events_expires_id', + 'shipping_order_extraction_progress_events', + ['expires_at', 'id'], + ) + op.create_index( + 'ix_shipping_order_extraction_progress_events_workflow_node', + 'shipping_order_extraction_progress_events', + ['workflow_run_id', 'node_execution_id'], + ) + + with op.batch_alter_table('shipping_order_extraction_units') as batch: + existing_columns = _columns(inspector, 'shipping_order_extraction_units') + for column_name in ('last_activity_at', 'summary_json', 'reason_code'): + if column_name in existing_columns: + batch.drop_column(column_name) + if 'ck_shipping_order_extraction_units_status' in _check_constraints(inspector, 'shipping_order_extraction_units'): + batch.drop_constraint('ck_shipping_order_extraction_units_status', type_='check') + batch.create_check_constraint( + 'ck_shipping_order_extraction_units_status', + "status IN ('pending', 'running', 'succeeded', 'failed', 'skipped')", + ) + + if 'uq_shipping_order_extraction_runs_active_conversation' in _indexes(inspector, 'shipping_order_extraction_runs'): + op.drop_index('uq_shipping_order_extraction_runs_active_conversation', table_name='shipping_order_extraction_runs') + op.create_index( + 'uq_shipping_order_extraction_runs_active_conversation', + 'shipping_order_extraction_runs', + ['user_id', 'owner_agent_id', 'conversation_id'], + unique=True, + sqlite_where=sa.text("status IN ('queued', 'running', 'result_persisted')"), + postgresql_where=sa.text("status IN ('queued', 'running', 'result_persisted')"), + ) + with op.batch_alter_table('shipping_order_extraction_runs') as batch: + if 'ck_shipping_order_extraction_runs_status' in _check_constraints(inspector, 'shipping_order_extraction_runs'): + batch.drop_constraint('ck_shipping_order_extraction_runs_status', type_='check') + batch.create_check_constraint( + 'ck_shipping_order_extraction_runs_status', + "status IN ('queued', 'running', 'result_persisted', 'completed', 'needs_review', 'failed', 'cancelled')", + ) diff --git a/backend/migrations/versions/0ac56d7e8f90_remove_internal_executor_runtime_bindings.py b/backend/migrations/versions/0ac56d7e8f90_remove_internal_executor_runtime_bindings.py new file mode 100644 index 00000000..c592a04b --- /dev/null +++ b/backend/migrations/versions/0ac56d7e8f90_remove_internal_executor_runtime_bindings.py @@ -0,0 +1,54 @@ +"""Remove obsolete internal executor configuration. + +Revision ID: 0ac56d7e8f90 +Revises: 1d2e3f4a5b6c, 3dd67e8f9a0b +Create Date: 2026-07-28 16:20:00.000000 + +Purpose: remove the retired internal executor and runtime binding data model. +Dependencies: agents and agent_runtime_bindings. +Logic: delete obsolete bindings, normalize retained Agent records, then remove the exposure column and binding table. +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = '0ac56d7e8f90' +down_revision = ('1d2e3f4a5b6c', '3dd67e8f9a0b') +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """Permanently remove internal-executor semantics and their obsolete bindings.""" + bind = op.get_bind() + inspector = sa.inspect(bind) + tables = set(inspector.get_table_names()) + if 'agent_runtime_bindings' in tables: + bind.execute(sa.text('DELETE FROM agent_runtime_bindings')) + + if 'agents' not in tables: + return + columns = {column['name'] for column in inspector.get_columns('agents')} + if 'exposure_mode' not in columns: + return + + # Retain Agent rows because chats, guides, and historical Runs may reference them. + # Removing the role column makes all retained records ordinary applications. + bind.execute(sa.text("UPDATE agents SET exposure_mode = 'workspace' WHERE exposure_mode = 'internal'")) + + inspector = sa.inspect(bind) + if 'agent_runtime_bindings' in set(inspector.get_table_names()): + op.drop_table('agent_runtime_bindings') + with op.batch_alter_table('agents') as batch: + constraints = {item['name'] for item in sa.inspect(bind).get_check_constraints('agents') if item.get('name')} + if 'ck_agents_exposure_mode' in constraints: + batch.drop_constraint('ck_agents_exposure_mode', type_='check') + batch.drop_column('exposure_mode') + + +def downgrade() -> None: + """This intentional destructive cleanup has no downgrade path.""" + raise RuntimeError('Internal executor removal cannot be downgraded') diff --git a/backend/migrations/versions/0bd56e7f8a91_align_order_route_decision_constraint.py b/backend/migrations/versions/0bd56e7f8a91_align_order_route_decision_constraint.py new file mode 100644 index 00000000..aefb64d8 --- /dev/null +++ b/backend/migrations/versions/0bd56e7f8a91_align_order_route_decision_constraint.py @@ -0,0 +1,55 @@ +"""align order route decision constraint + +Revision ID: 0bd56e7f8a91 +Revises: 0ac56d7e8f90 +Create Date: 2026-07-28 14:00:00.000000 + +用途:使数据库路由决策约束与确定性订单抽取模型一致。 +依赖:shipping_order_extraction_route_decisions、ShippingOrderExtractionRouteDecision。 +逻辑:替换历史 decision 枚举约束,允许 deterministic、review_required 与 skipped;不修改已有审计数据。 +""" + +from alembic import op + + +revision = '0bd56e7f8a91' +down_revision = '0ac56d7e8f90' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """替换遗留的路由 decision 检查约束,支持人工复核和跳过投影。""" + op.drop_constraint( + 'ck_shipping_order_extraction_route_decision', + 'shipping_order_extraction_route_decisions', + type_='check', + ) + # 历史 dify/blocked 仅是旧路由语义:分别映射为当前确定性/人工复核投影。 + op.execute( + "UPDATE shipping_order_extraction_route_decisions " + "SET decision = CASE decision " + "WHEN 'dify' THEN 'deterministic' " + "WHEN 'blocked' THEN 'review_required' " + "ELSE decision END " + "WHERE decision IN ('dify', 'blocked')" + ) + op.create_check_constraint( + 'ck_shipping_order_extraction_route_decision', + 'shipping_order_extraction_route_decisions', + "decision IN ('deterministic', 'review_required', 'skipped')", + ) + + +def downgrade() -> None: + """恢复历史枚举,回退前须确认不存在新 decision 值。""" + op.drop_constraint( + 'ck_shipping_order_extraction_route_decision', + 'shipping_order_extraction_route_decisions', + type_='check', + ) + op.create_check_constraint( + 'ck_shipping_order_extraction_route_decision', + 'shipping_order_extraction_route_decisions', + "decision IN ('deterministic', 'dify', 'blocked')", + ) diff --git a/backend/migrations/versions/0ce67f8a9b01_add_auto_freeze_scope_to_profile_qualification.py b/backend/migrations/versions/0ce67f8a9b01_add_auto_freeze_scope_to_profile_qualification.py new file mode 100644 index 00000000..aa63d04a --- /dev/null +++ b/backend/migrations/versions/0ce67f8a9b01_add_auto_freeze_scope_to_profile_qualification.py @@ -0,0 +1,48 @@ +"""add customer and scenario scope to profile auto-freeze qualifications + +Revision ID: 0ce67f8a9b01 +Revises: 0bd56e7f8a91 +Create Date: 2026-07-28 18:40:00.000000 + +用途:为模板版本级自动冻结资格补齐客户/业务场景授权范围。 +依赖:已存在的自动冻结资格表与用户表。 +逻辑:仅追加授权范围与配置审计字段,不改变既有资格状态。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = '0ce67f8a9b01' +down_revision = '0bd56e7f8a91' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """为资格表增加客户范围、业务场景和客户确认开关。""" + with op.batch_alter_table('shipping_document_profile_auto_freeze_qualifications', recreate='auto') as batch_op: + batch_op.add_column(sa.Column('customer_ids_json', sa.JSON(), nullable=True)) + batch_op.add_column(sa.Column('business_scenarios_json', sa.JSON(), nullable=True)) + batch_op.add_column( + sa.Column('requires_customer_confirmation', sa.Boolean(), nullable=False, server_default=sa.text('true')), + ) + batch_op.add_column(sa.Column('scope_updated_by_id', sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column('scope_updated_at', sa.DateTime(), nullable=True)) + batch_op.create_foreign_key( + 'fk_ship_doc_prof_auto_freeze_scope_updated_by_user', + 'users', + ['scope_updated_by_id'], + ['id'], + ) + + +def downgrade() -> None: + """移除资格范围字段,保留既有状态记录。""" + with op.batch_alter_table('shipping_document_profile_auto_freeze_qualifications', recreate='auto') as batch_op: + batch_op.drop_constraint('fk_ship_doc_prof_auto_freeze_scope_updated_by_user', type_='foreignkey') + batch_op.drop_column('scope_updated_at') + batch_op.drop_column('scope_updated_by_id') + batch_op.drop_column('requires_customer_confirmation') + batch_op.drop_column('business_scenarios_json') + batch_op.drop_column('customer_ids_json') diff --git a/backend/migrations/versions/0cf78a9b0c12_add_shipping_notice_upload_batch.py b/backend/migrations/versions/0cf78a9b0c12_add_shipping_notice_upload_batch.py new file mode 100644 index 00000000..d85b761f --- /dev/null +++ b/backend/migrations/versions/0cf78a9b0c12_add_shipping_notice_upload_batch.py @@ -0,0 +1,38 @@ +"""add upload batch to shipping notice intakes + +Revision ID: 0cf78a9b0c12 +Revises: 0ce67f8a9b01 +Create Date: 2026-07-28 20:10:00.000000 + +用途:为聊天输入框的一次文件选择持久化上传批次。 +依赖:shipping_notice_intakes。 +逻辑:Run 创建按 upload_batch_id 锁定当前发送附件,避免历史未发送 Intake 混入。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = '0cf78a9b0c12' +down_revision = '0ce67f8a9b01' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """新增上传批次与按用户批次查询索引;无历史兼容回填。""" + with op.batch_alter_table('shipping_notice_intakes', recreate='auto') as batch_op: + # 旧 Intake 不回填也不可发送;可空使已有生产表能够原地升级。 + batch_op.add_column(sa.Column('upload_batch_id', sa.String(length=36), nullable=True)) + batch_op.create_index( + 'ix_shipping_notice_intakes_user_upload_batch_created', + ['user_id', 'upload_batch_id', 'created_at'], + unique=False, + ) + + +def downgrade() -> None: + """移除输入框上传批次字段和索引。""" + with op.batch_alter_table('shipping_notice_intakes', recreate='auto') as batch_op: + batch_op.drop_index('ix_shipping_notice_intakes_user_upload_batch_created') + batch_op.drop_column('upload_batch_id') diff --git a/backend/migrations/versions/1c2d3e4f5a6b_add_order_extraction_unit_plan_metadata.py b/backend/migrations/versions/1c2d3e4f5a6b_add_order_extraction_unit_plan_metadata.py new file mode 100644 index 00000000..dfb2df25 --- /dev/null +++ b/backend/migrations/versions/1c2d3e4f5a6b_add_order_extraction_unit_plan_metadata.py @@ -0,0 +1,63 @@ +"""add order extraction unit plan metadata + +Revision ID: 1d2e3f4a5b6c +Revises: 0ab45c6d7e8f +Create Date: 2026-07-28 17:10:00.000000 + +用途:为订单抽取单元补充选择批次、分组键、预算、重试与技术失败事实。 +依赖:shipping_order_extraction_units。 +逻辑:阶段 2/4 直接在 Unit 层持久化计划与失败元数据,避免后续只能回读 snapshot 猜测。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = '1d2e3f4a5b6c' +down_revision = '0ab45c6d7e8f' +branch_labels = None +depends_on = None + + +def _columns(inspector: sa.Inspector, table_name: str) -> set[str]: + return {column['name'] for column in inspector.get_columns(table_name)} + + +def upgrade() -> None: + """为订单抽取单元添加阶段 2/4 所需的计划与失败元数据字段。""" + bind = op.get_bind() + inspector = sa.inspect(bind) + existing_columns = _columns(inspector, 'shipping_order_extraction_units') + + with op.batch_alter_table('shipping_order_extraction_units') as batch: + if 'selection_batch' not in existing_columns: + batch.add_column(sa.Column('selection_batch', sa.Integer(), nullable=True)) + if 'selection_reason_codes_json' not in existing_columns: + batch.add_column(sa.Column('selection_reason_codes_json', sa.JSON(), nullable=True)) + if 'group_key' not in existing_columns: + batch.add_column(sa.Column('group_key', sa.String(length=128), nullable=True)) + if 'budget_cost_json' not in existing_columns: + batch.add_column(sa.Column('budget_cost_json', sa.JSON(), nullable=True)) + if 'retry_status' not in existing_columns: + batch.add_column(sa.Column('retry_status', sa.String(length=32), nullable=True)) + if 'technical_failure_reason_code' not in existing_columns: + batch.add_column(sa.Column('technical_failure_reason_code', sa.String(length=64), nullable=True)) + + +def downgrade() -> None: + """移除订单抽取单元的计划与失败元数据字段。""" + bind = op.get_bind() + inspector = sa.inspect(bind) + existing_columns = _columns(inspector, 'shipping_order_extraction_units') + + with op.batch_alter_table('shipping_order_extraction_units') as batch: + for column_name in ( + 'technical_failure_reason_code', + 'retry_status', + 'budget_cost_json', + 'group_key', + 'selection_reason_codes_json', + 'selection_batch', + ): + if column_name in existing_columns: + batch.drop_column(column_name) diff --git a/backend/migrations/versions/2d3e4f5a6b7c_add_order_extraction_request_snapshot.py b/backend/migrations/versions/2d3e4f5a6b7c_add_order_extraction_request_snapshot.py new file mode 100644 index 00000000..b94edd59 --- /dev/null +++ b/backend/migrations/versions/2d3e4f5a6b7c_add_order_extraction_request_snapshot.py @@ -0,0 +1,33 @@ +"""add immutable request snapshot to order extraction run + +Revision ID: 2d3e4f5a6b7c +Revises: 0cf78a9b0c12 +Create Date: 2026-07-28 21:15:00.000000 + +用途:保留用户点击发送时的轻量请求快照,隔离 Worker 物化后的执行快照。 +依赖:shipping_order_extraction_runs。 +逻辑:请求快照稳定用于幂等和审计;input_snapshot_* 继续承载不可变执行证据。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = '2d3e4f5a6b7c' +down_revision = '0cf78a9b0c12' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """新增请求时冻结的哈希及 JSON 快照;旧记录保留为空。""" + with op.batch_alter_table('shipping_order_extraction_runs', recreate='auto') as batch_op: + batch_op.add_column(sa.Column('request_snapshot_hash', sa.String(length=64), nullable=True)) + batch_op.add_column(sa.Column('request_snapshot_json', sa.JSON(), nullable=True)) + + +def downgrade() -> None: + """移除请求快照字段。""" + with op.batch_alter_table('shipping_order_extraction_runs', recreate='auto') as batch_op: + batch_op.drop_column('request_snapshot_json') + batch_op.drop_column('request_snapshot_hash') diff --git a/backend/tests/services/admin/test_agent_service.py b/backend/tests/services/admin/test_agent_service.py index 454176df..f2864853 100644 --- a/backend/tests/services/admin/test_agent_service.py +++ b/backend/tests/services/admin/test_agent_service.py @@ -7,7 +7,7 @@ import pytest from app import db from app.core.errors import NotFoundError, ValidationError -from app.models import Agent, AgentRuntimeBinding, User +from app.models import Agent, User from app.services.admin import agent_service @@ -85,87 +85,6 @@ def test_update_agent_clears_handler_config_when_explicit_null(app): assert refreshed.handler_config is None -def test_create_agent_and_runtime_binding_are_atomic(app): - """创建货代 Agent 时绑定校验失败必须回滚 Agent,不能留下半配置入口。""" - with app.app_context(): - provider = Agent( - name='Invalid Chatflow Provider', - agent_code='generic', - runtime_provider='dify', - dify_app_type='chatflow', - exposure_mode='workspace', - dify_app_id='invalid-create-provider', - dify_api_key='sk-test', - api_base_url='http://dify.example/v1', - is_active=True, - ) - db.session.add(provider) - db.session.commit() - - with pytest.raises(ValidationError): - agent_service.create_agent({ - 'name': 'Atomic Shipping Create', - 'agent_code': 'shipping_notice', - 'runtime_provider': 'hybrid', - 'conversation_mode': 'task_chat', - 'dify_app_id': 'atomic-shipping-create', - 'dify_api_key': 'sk-test', - 'api_base_url': 'http://dify.example/v1', - 'order_extraction_runtime_binding': { - 'provider_agent_id': provider.id, - 'enabled': True, - 'config': {'timeout_seconds': 900, 'max_attempts': 3}, - }, - }) - db.session.rollback() - - assert Agent.query.filter_by(name='Atomic Shipping Create').count() == 0 - assert AgentRuntimeBinding.query.count() == 0 - - -def test_update_agent_and_runtime_binding_are_atomic(app): - """更新 Agent 时绑定校验失败必须回滚 Agent 字段,避免配置只保存一半。""" - with app.app_context(): - owner = Agent( - name='Atomic Shipping Update', - description='before', - agent_code='shipping_notice', - runtime_provider='hybrid', - conversation_mode='task_chat', - dify_app_id='atomic-shipping-update', - dify_api_key='sk-test', - api_base_url='http://dify.example/v1', - is_active=True, - ) - provider = Agent( - name='Invalid Update Provider', - agent_code='generic', - runtime_provider='dify', - dify_app_type='chatflow', - exposure_mode='workspace', - dify_app_id='invalid-update-provider', - dify_api_key='sk-test', - api_base_url='http://dify.example/v1', - is_active=True, - ) - db.session.add_all([owner, provider]) - db.session.commit() - - with pytest.raises(ValidationError): - agent_service.update_agent(owner.id, { - 'description': 'after', - 'order_extraction_runtime_binding': { - 'provider_agent_id': provider.id, - 'enabled': True, - 'config': {'timeout_seconds': 900, 'max_attempts': 3}, - }, - }) - db.session.rollback() - - assert db.session.get(Agent, owner.id).description == 'before' - assert AgentRuntimeBinding.query.filter_by(owner_agent_id=owner.id).count() == 0 - - def test_update_agent_permissions(app): with app.app_context(): agent = Agent( diff --git a/backend/tests/services/admin/test_permission_service.py b/backend/tests/services/admin/test_permission_service.py index 255af8ba..37df3b97 100644 --- a/backend/tests/services/admin/test_permission_service.py +++ b/backend/tests/services/admin/test_permission_service.py @@ -50,31 +50,6 @@ def test_batch_update_permissions_no_users(app): permission_service.batch_update_permissions({'user_ids': [], 'agent_ids': [1]}) -@pytest.mark.parametrize('operation', ['single', 'batch']) -def test_internal_executor_cannot_be_assigned_to_user(app, operation): - """授权服务必须在所有写入口拒绝 internal 执行器。""" - with app.app_context(): - executor = Agent( - name='internal-executor', type='api', dify_app_id='wf-internal', dify_api_key='key', - dify_app_type='workflow', runtime_provider='dify', exposure_mode='internal', - ) - user = User(username=f'internal-{operation}', email=f'internal-{operation}@example.com', role='user') - db.session.add_all([executor, user]) - db.session.commit() - - with pytest.raises(ValidationError) as caught: - if operation == 'single': - permission_service.update_user_permissions(user.id, {'agent_ids': [executor.id]}) - else: - permission_service.batch_update_permissions({ - 'user_ids': [user.id], 'agent_ids': [executor.id], 'action': 'add', - }) - - assert caught.value.code == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN' - db.session.refresh(user) - assert executor not in user.agents - - def test_permission_request_approve(app, monkeypatch): with app.app_context(): agent = Agent(name='req-agent', type='api', dify_app_id='app-r', dify_api_key='key-r') @@ -100,27 +75,3 @@ def test_permission_request_approve(app, monkeypatch): def test_permission_request_not_found(app): with app.app_context(): - with pytest.raises(NotFoundError): - permission_service.approve_permission_request(99999) - - -def test_internal_executor_permission_request_cannot_be_approved(app): - """历史或伪造的内部执行器权限申请不得转化为用户授权。""" - with app.app_context(): - executor = Agent( - name='request-executor', type='api', dify_app_id='wf-request', dify_api_key='key', - dify_app_type='workflow', runtime_provider='dify', exposure_mode='internal', - ) - user = User(username='request-internal', email='request-internal@example.com', role='user') - db.session.add_all([executor, user]) - db.session.flush() - req = PermissionRequest(user_id=user.id, agent_id=executor.id, reason='invalid', status='pending') - db.session.add(req) - db.session.commit() - - with pytest.raises(ForbiddenError) as caught: - permission_service.approve_permission_request(req.id) - - assert getattr(caught.value, 'code', None) == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN' - db.session.refresh(user) - assert executor not in user.agents diff --git a/backend/tests/services/admin/test_user_service.py b/backend/tests/services/admin/test_user_service.py index b05afb5b..c3745db5 100644 --- a/backend/tests/services/admin/test_user_service.py +++ b/backend/tests/services/admin/test_user_service.py @@ -54,23 +54,3 @@ def test_list_users_sort_by_username_and_department(app): assert depts == sorted(depts, reverse=True) fallback = user_service.resolve_users_order_by({'sort_by': 'role', 'sort_dir': 'asc'}) - assert len(fallback) == 1 - - -def test_update_user_rejects_internal_executor_permission(app): - """用户 CRUD 的 agent_ids 写入口不得绕过统一授权策略。""" - with app.app_context(): - user = User(username='crud-internal', email='crud-internal@example.com', role='user') - executor = Agent( - name='CRUD Executor', exposure_mode='internal', runtime_provider='dify', - dify_app_type='workflow', dify_app_id='crud-workflow', dify_api_key='key', - ) - db.session.add_all([user, executor]) - db.session.commit() - - with pytest.raises(ValidationError) as caught: - user_service.update_user(user.id, {'agent_ids': [executor.id]}) - - assert caught.value.code == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN' - db.session.refresh(user) - assert executor not in user.agents diff --git a/backend/tests/services/admin/test_wecom_admin_service.py b/backend/tests/services/admin/test_wecom_admin_service.py index 48cf9949..8e066c09 100644 --- a/backend/tests/services/admin/test_wecom_admin_service.py +++ b/backend/tests/services/admin/test_wecom_admin_service.py @@ -21,28 +21,3 @@ def test_binding_stats(app): stats = wecom_admin_service.binding_stats() assert stats['total_active'] == 2 assert stats['bound'] == 1 - assert stats['unbound'] == 1 - - -def test_provision_user_rejects_internal_executor_permission(app): - """企微开户/绑定不得把内部执行器写入用户授权关系。""" - with app.app_context(): - user = User(username='wecom-internal', email='wecom-internal@example.com', role='user') - executor = Agent( - name='WeCom Executor', exposure_mode='internal', runtime_provider='dify', - dify_app_type='workflow', dify_app_id='wecom-workflow', dify_api_key='key', - ) - db.session.add_all([user, executor]) - db.session.commit() - - with pytest.raises(ValidationError) as caught: - wecom_admin_service.provision_user({ - 'create_user': False, - 'user_id': user.id, - 'bind': {'wecom_userid': 'wx-internal'}, - 'agent_ids': [executor.id], - }) - - assert caught.value.code == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN' - db.session.refresh(user) - assert executor not in user.agents diff --git a/backend/tests/services/shipping_notice/test_shipping_order_snapshot.py b/backend/tests/services/shipping_notice/test_shipping_order_snapshot.py index a70cd79b..90a45a91 100644 --- a/backend/tests/services/shipping_notice/test_shipping_order_snapshot.py +++ b/backend/tests/services/shipping_notice/test_shipping_order_snapshot.py @@ -31,6 +31,8 @@ from app.models import ( ShippingTask, User, ) +from app.services.shipping_notice.freeze_readiness_service import assert_freeze_readiness +from app.services.shipping_notice.fulfillment_policy_registry import published_policy, required_field_configs from app.services.shipping_notice.order_freeze_service import ( HEADER_FIELD_PROJECTIONS, LINE_FIELD_PROJECTIONS, @@ -280,6 +282,47 @@ def test_freeze_rejects_open_conflict_and_missing_fulfillment_value(app): assert missing_error.value.code == 'SHIPPING.ORDER_FREEZE_BLOCKED' +def test_auto_freeze_readiness_fails_closed_with_run_policy_blockers(app): + """自动冻结模式必须消费 Run 级门禁摘要,并把阻断原因折叠为统一 freeze issues。""" + with app.app_context(): + task, _user = _build_accepted_order(suffix='auto-freeze-readiness') + extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) + assert extraction is not None + policy = published_policy() + definition = extraction.schema_version.definition_json or {} + configs = { + str(item.get('field_code') or ''): item + for item in definition.get('fields') or [] + if isinstance(item, dict) and item.get('enabled', True) + } + configs.update(required_field_configs(definition, policy)) + + with pytest.raises(ValidationError) as blocked_error: + assert_freeze_readiness( + task=task, + extraction=extraction, + policy=policy, + configs=configs, + freeze_mode='auto', + auto_freeze_policy={ + 'mode': 'manual_confirmation', + 'enabled': False, + 'qualification_status': 'auto_freeze_approved', + 'customer_scope_status': 'unconfigured', + 'blocking_reason_codes': [ + 'customer_scope_not_configured', + 'customer_confirmation_required', + ], + }, + ) + + assert blocked_error.value.code == 'SHIPPING.ORDER_FREEZE_BLOCKED' + issues = blocked_error.value.details['issues'] + assert {'reason': 'auto_freeze_blocked', 'blocking_reason_code': 'customer_scope_not_configured'} in issues + assert {'reason': 'auto_freeze_blocked', 'blocking_reason_code': 'customer_confirmation_required'} in issues + assert any(item['reason'] == 'auto_freeze_not_enabled' for item in issues) + + def test_freeze_is_idempotent_for_repeated_confirmation(app): """关键断言:用户重复确认冻结只返回同一 Snapshot,不产生第二份履约事实。""" with app.app_context(): diff --git a/backend/tests/test_agent_registry_catalog_validation.py b/backend/tests/test_agent_registry_catalog_validation.py index a89018eb..6f8065ae 100644 --- a/backend/tests/test_agent_registry_catalog_validation.py +++ b/backend/tests/test_agent_registry_catalog_validation.py @@ -40,74 +40,6 @@ def test_validate_agent_payload_parses_is_active_string_false(): assert normalized['is_active'] is False -def test_validate_agent_payload_restricts_new_internal_executor_to_workflow(): - """新建 internal Agent 只能登记为 Dify Workflow。""" - with pytest.raises(ValidationError, match='内部执行器'): - validate_agent_payload({ - 'name': 'Invalid Internal', - 'agent_code': 'generic', - 'runtime_provider': 'dify', - 'dify_app_type': 'chatflow', - 'exposure_mode': 'internal', - 'dify_app_id': 'app-1', - }) - - -def test_validate_agent_payload_rejects_moving_internal_to_workspace(): - """内部执行器的可见性不可改回 workspace。""" - from types import SimpleNamespace - - agent = SimpleNamespace( - agent_code='generic', runtime_provider='dify', conversation_mode='task_chat', - dify_app_type='workflow', exposure_mode='internal', - dify_app_id='app-1', bound_schedule_task_id=None, capabilities=None, handler_config=None, - suggested_questions_style='plain', suggested_questions=[], sort_order=0, - file_upload_policy=None, is_active=True, is_aggregate=False, - ) - with pytest.raises(ValidationError) as caught: - validate_agent_payload({ - 'name': 'Provider', 'exposure_mode': 'workspace', - }, agent=agent, provided_fields=frozenset({'name', 'exposure_mode'})) - assert caught.value.code == 'AGENT.EXPOSURE_ROLE_IMMUTABLE' - - -def test_validate_agent_payload_rejects_promoting_workspace_to_internal(): - """workspace Agent 不能通过编辑请求转换为 internal 执行器。""" - from types import SimpleNamespace - - agent = SimpleNamespace( - agent_code='generic', runtime_provider='dify', conversation_mode='chat', - dify_app_type='chatflow', exposure_mode='workspace', - dify_app_id='app-1', bound_schedule_task_id=None, capabilities=None, handler_config=None, - suggested_questions_style='plain', suggested_questions=[], sort_order=0, - file_upload_policy=None, is_active=True, is_aggregate=False, - ) - with pytest.raises(ValidationError) as caught: - validate_agent_payload({ - 'name': 'Promote Provider', 'exposure_mode': 'internal', - 'runtime_provider': 'dify', 'dify_app_type': 'workflow', - }, agent=agent, provided_fields=frozenset({'name', 'exposure_mode', 'runtime_provider', 'dify_app_type'})) - assert caught.value.code == 'AGENT.EXPOSURE_ROLE_IMMUTABLE' - - -def test_validate_agent_payload_keeps_internal_exposure_immutable(): - """已注册内部执行器不得通过编辑请求改成工作台应用。""" - from types import SimpleNamespace - - agent = SimpleNamespace( - agent_code='generic', runtime_provider='dify', conversation_mode='task_chat', - dify_app_type='workflow', exposure_mode='internal', - dify_app_id='app-1', bound_schedule_task_id=None, capabilities=None, handler_config=None, - suggested_questions_style='plain', suggested_questions=[], sort_order=0, - file_upload_policy=None, is_active=True, is_aggregate=False, - ) - with pytest.raises(ValidationError) as caught: - validate_agent_payload({ - 'name': 'Internal Provider', 'exposure_mode': 'workspace', - }, agent=agent, provided_fields=frozenset({'name', 'exposure_mode'})) - assert caught.value.code == 'AGENT.EXPOSURE_ROLE_IMMUTABLE' - - def test_validate_agent_payload_applies_forced_capabilities_from_manifest(): """validate_agent_payload 路径应合并 manifest forced_capabilities。""" normalized = validate_agent_payload({ diff --git a/backend/tests/test_agent_registry_resolver.py b/backend/tests/test_agent_registry_resolver.py index b419d9ee..162ae141 100644 --- a/backend/tests/test_agent_registry_resolver.py +++ b/backend/tests/test_agent_registry_resolver.py @@ -20,7 +20,6 @@ from app.services.agent_registry.resolver import ( resolve_agent_code, resolve_capabilities, resolve_conversation_mode, - resolve_effective_role, resolve_handler_key, resolve_intent_routes, resolve_progress_contract, @@ -102,13 +101,6 @@ def test_resolve_runtime_provider_reads_column_not_legacy_type(): assert resolve_runtime_provider(registered_iframe) == 'iframe' -def test_resolve_effective_role_derives_from_exposure_mode_only(): - """internal 仅派生为内部执行器;历史 conversation_mode 不影响角色。""" - assert resolve_effective_role(_agent(exposure_mode='internal', conversation_mode='task_chat')) == 'internal_executor' - assert resolve_effective_role(_agent(exposure_mode='workspace', conversation_mode='embedded')) == 'user_agent' - assert resolve_effective_role(SimpleNamespace()) == 'user_agent' - - def test_resolve_capabilities_normalizes_schema(): """capabilities 列 dict 应归一化为固定 schema 布尔键。""" agent = _agent( diff --git a/backend/tests/test_agent_registry_serialization.py b/backend/tests/test_agent_registry_serialization.py index 5844d0c3..561fa8af 100644 --- a/backend/tests/test_agent_registry_serialization.py +++ b/backend/tests/test_agent_registry_serialization.py @@ -35,7 +35,6 @@ def test_serialize_agent_for_admin_includes_api_key_for_admin_edit(): agent_code='generic', runtime_provider='dify', conversation_mode='chat', - exposure_mode='internal', dify_app_type='chatflow', iframe_url=None, category=None, @@ -52,7 +51,6 @@ def test_serialize_agent_for_admin_includes_api_key_for_admin_edit(): payload = serialize_agent_for_admin(agent) assert payload['dify_api_key'] == agent.dify_api_key assert payload['dify_api_key_masked'] == mask_dify_api_key(agent.dify_api_key) - assert payload['effective_role'] == 'internal_executor' def test_serialize_registry_fields_includes_progress_contract(): @@ -60,7 +58,6 @@ def test_serialize_registry_fields_includes_progress_contract(): agent_code='file_check', runtime_provider='dify', conversation_mode='task_chat', - exposure_mode='workspace', capabilities={'task_progress': True}, bound_schedule_task_id=42, handler_config={'poll_interval_seconds': 2, 'lock_input_when_running': True}, @@ -77,7 +74,6 @@ def test_serialize_registry_fields_includes_progress_contract(): payload = serialize_registry_fields(file_check) assert payload['progress_contract']['data_source']['type'] == 'schedule_run' assert payload['tool_run_progress']['schedule_task_id'] == 42 - assert payload['effective_role'] == 'user_agent' def test_build_tool_run_progress_view_skips_domain_state_contract(): diff --git a/backend/tests/test_agent_runtime_binding_migration.py b/backend/tests/test_agent_runtime_binding_migration.py deleted file mode 100644 index c288ebad..00000000 --- a/backend/tests/test_agent_runtime_binding_migration.py +++ /dev/null @@ -1,67 +0,0 @@ -""" -backend/tests/test_agent_runtime_binding_migration.py - -用途:隔离验证阶段 2 Agent 能力绑定迁移可往返执行。 -依赖:Alembic Operations、SQLAlchemy 内存数据库、c17c8d9e0f1a 增量迁移。 -逻辑:构造阶段 1 最小表,验证 exposure/binding/Run Provider/Job 唯一索引并完整回滚。 -""" - -from __future__ import annotations - -import importlib - -import sqlalchemy as sa -from alembic.migration import MigrationContext -from alembic.operations import Operations - - -def _pre_schema(engine: sa.Engine) -> None: - """创建阶段 2 迁移依赖的最小表结构。""" - metadata = sa.MetaData() - sa.Table('agents', metadata, sa.Column('id', sa.Integer(), primary_key=True)) - sa.Table( - 'jobs', metadata, - sa.Column('id', sa.Integer(), primary_key=True), - sa.Column('domain', sa.String(64)), - sa.Column('job_type', sa.String(64)), - sa.Column('business_ref', sa.String(128)), - sa.Column('status', sa.String(32)), - ) - sa.Table( - 'shipping_order_extraction_runs', metadata, - sa.Column('id', sa.Integer(), primary_key=True), - ) - metadata.create_all(engine) - - -def test_agent_runtime_binding_migration_round_trip(): - """迁移应创建全部阶段 2 列/表/索引,并可回到阶段 1 结构。""" - engine = sa.create_engine('sqlite:///:memory:') - _pre_schema(engine) - migration = importlib.import_module('migrations.versions.c17c8d9e0f1a_add_agent_runtime_bindings') - with engine.begin() as connection: - original_op = migration.op - migration.op = Operations(MigrationContext.configure(connection)) - try: - migration.upgrade() - inspector = sa.inspect(connection) - assert 'exposure_mode' in {item['name'] for item in inspector.get_columns('agents')} - assert 'agent_runtime_bindings' in inspector.get_table_names() - run_columns = {item['name'] for item in inspector.get_columns('shipping_order_extraction_runs')} - assert { - 'runtime_binding_id', 'provider_agent_id', 'provider_result_json', 'provider_completed_at', - } <= run_columns - assert 'provider_config_json' not in run_columns - assert 'provider_snapshot_json' not in run_columns - indexes = {item['name']: item for item in inspector.get_indexes('jobs')} - assert indexes['uq_jobs_shipping_order_extraction_active_ref']['unique'] == 1 - - migration.downgrade() - inspector = sa.inspect(connection) - assert 'exposure_mode' not in {item['name'] for item in inspector.get_columns('agents')} - assert 'agent_runtime_bindings' not in inspector.get_table_names() - run_columns = {item['name'] for item in inspector.get_columns('shipping_order_extraction_runs')} - assert 'runtime_binding_id' not in run_columns - assert 'provider_result_json' not in run_columns - finally: - migration.op = original_op diff --git a/backend/tests/test_agent_runtime_bindings.py b/backend/tests/test_agent_runtime_bindings.py deleted file mode 100644 index f88e4772..00000000 --- a/backend/tests/test_agent_runtime_bindings.py +++ /dev/null @@ -1,1531 +0,0 @@ -""" -backend/tests/test_agent_runtime_bindings.py - -用途:验证显式 Agent 能力绑定、内部 Provider 隐藏和订单抽取 Run/Job 执行闭环。 -依赖:Agent 管理 API、通用 Job Worker、Dify Workflow mock、订单抽取测试夹具。 -逻辑:覆盖无配置阻断、Provider 约束、管理端保存、用户列表隔离、Dify 成功结果缓存与 Run 单调状态。 -""" - -from __future__ import annotations - -import json -import logging -import threading -import time -from copy import deepcopy -from unittest.mock import patch -from datetime import datetime, timedelta - -import pytest -import requests - -from app import db -from app.core.auth.jwt import issue_local_access_token -from app.core.errors import ConflictError, ValidationError -from app.jobs.context import JobContext -from app.jobs.handlers.shipping_order_extraction import ( - _execute_dify_unit_with_retry, - run_shipping_order_extraction, -) -from app.jobs.queue import claim_next_job, recover_stale_jobs -from app.jobs.types import JobType -from app.models import ( - Agent, AgentRuntimeBinding, Job, ShippingNoticeCandidate, ShippingNoticeDocument, - ShippingOrderDocumentProfile, ShippingOrderExtraction, ShippingOrderExtractionRouteDecision, ShippingOrderExtractionRun, - ShippingOrderSchemaVersion, User, -) -from app.services.agent_runtime_binding_service import resolve_runtime_binding, save_runtime_binding -from app.services.admin.agent_service import update_agent_permissions -from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot -from app.services.admin.agent_service import list_agents -from app.services.shipping_notice.order_extraction_workflow import ( - _cross_page_anchor_matches, build_order_extraction_workflow_inputs, execute_order_extraction_workflow, - parse_order_extraction_workflow_result, validate_unit_orders, -) -from app.services.shipping_notice.order_extraction_run_service import ( - create_order_extraction_run, - retry_order_extraction_run, - sync_order_extraction_run_after_job_recovery, - transition_order_extraction_run, -) -from tests.test_shipping_order_extraction_runs import _seed_run_input - - -def test_cross_page_coordinate_continuation_requires_frozen_relation_anchor_and_region(): - """续页锚点须在声明区域命中;整页出现相同文本不足以授权跨页合并。""" - profile = {'definition': {'document_match': {'required_anchors': [{ - 'anchor_id': 'continued', 'text': 'CONTINUED', 'match_mode': 'exact', - 'region': {'x0': 0, 'y0': 0, 'x1': .5, 'y1': .5}, - }]}}} - layout = {'coordinate_evidence': { - 'tables': {'page-two': [ - {'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}} - for index, char in enumerate('CONTINUED') - ]}, - 'pages': {'2': {'width': 200, 'height': 200}}, - }} - assert _cross_page_anchor_matches( - raw_profile=profile, raw_table={'table_id': 'page-two', 'page_no': 2}, layout=layout, - anchor_ids=['continued'], - ) is True - - profile['definition']['document_match']['required_anchors'][0]['region'] = {'x0': .5, 'y0': .5, 'x1': 1, 'y1': 1} - assert _cross_page_anchor_matches( - raw_profile=profile, raw_table={'table_id': 'page-two', 'page_no': 2}, layout=layout, - anchor_ids=['continued'], - ) is False - - -def test_binding_rejects_non_internal_or_non_workflow_provider(app): - """订单抽取 Provider 必须是启用的 internal Dify Workflow,不能绑定普通 Chatflow。""" - with app.app_context(): - owner = Agent(name='Owner', agent_code='shipping_notice', runtime_provider='hybrid') - provider = Agent( - name='Bad Provider', agent_code='generic', runtime_provider='dify', - dify_app_type='chatflow', exposure_mode='workspace', dify_app_id='bad-provider', - dify_api_key='key', api_base_url='http://dify.example/v1', is_active=True, - ) - db.session.add_all([owner, provider]) - db.session.commit() - - with pytest.raises(ValidationError) as caught: - save_runtime_binding( - owner_agent_id=owner.id, - capability_code='shipping.order_extraction', - provider_agent_id=provider.id, - enabled=True, - config={}, - ) - - assert caught.value.code == 'AGENT.RUNTIME_PROVIDER_INVALID' - - -def test_binding_catalog_exposes_internal_executor_role_constraint(app): - """订单抽取能力目录必须明确要求 internal_executor,避免仅靠界面约定。""" - with app.app_context(): - owner = Agent(name='Owner', agent_code='shipping_notice', runtime_provider='hybrid') - provider = Agent( - name='Workflow Provider', agent_code='generic', runtime_provider='dify', - dify_app_type='workflow', exposure_mode='internal', dify_app_id='workflow-provider', - dify_api_key='key', api_base_url='http://dify.example/v1', is_active=True, - ) - db.session.add_all([owner, provider]) - db.session.commit() - - binding = save_runtime_binding( - owner_agent_id=owner.id, - capability_code='shipping.order_extraction', - provider_agent_id=provider.id, - enabled=True, - config={}, - ) - assert binding.provider_agent.exposure_mode == 'internal' - - -def test_binding_rejects_retired_workflow_contract_version(app): - """唯一协议不接受历史版本开关,防止运行时重新出现双格式分支。""" - with app.app_context(): - owner = Agent(name='Owner', agent_code='shipping_notice', runtime_provider='hybrid') - provider = Agent( - name='Workflow Provider', agent_code='generic', runtime_provider='dify', - dify_app_type='workflow', exposure_mode='internal', dify_app_id='workflow-provider', - dify_api_key='key', api_base_url='http://dify.example/v1', is_active=True, - ) - db.session.add_all([owner, provider]) - db.session.commit() - - with pytest.raises(ValidationError) as caught: - save_runtime_binding( - owner_agent_id=owner.id, capability_code='shipping.order_extraction', - provider_agent_id=provider.id, enabled=True, - config={'workflow_contract_version': 'latest'}, - ) - - assert caught.value.code == 'AGENT.RUNTIME_BINDING_CONFIG_INVALID' - - -def test_binding_rejects_retired_workflow_contract_version_with_auto_create(app): - """自动建单也不得通过历史版本配置绕过唯一协议约束。""" - with app.app_context(): - owner = Agent(name='Owner', agent_code='shipping_notice', runtime_provider='hybrid') - provider = Agent( - name='Workflow Provider', agent_code='generic', runtime_provider='dify', - dify_app_type='workflow', exposure_mode='internal', dify_app_id='workflow-provider', - dify_api_key='key', api_base_url='http://dify.example/v1', is_active=True, - ) - db.session.add_all([owner, provider]) - db.session.commit() - - with pytest.raises(ValidationError) as caught: - save_runtime_binding( - owner_agent_id=owner.id, capability_code='shipping.order_extraction', - provider_agent_id=provider.id, enabled=True, - config={'workflow_contract_version': 'legacy', 'auto_create_enabled': True}, - ) - - assert caught.value.code == 'AGENT.RUNTIME_BINDING_CONFIG_INVALID' - - -def test_internal_executor_cannot_receive_user_permissions(app): - """内部执行器只能被运行时绑定,不能进入用户授权关系。""" - with app.app_context(): - user = User(username='internal-permission-user', email='internal-permission@example.com', password_hash='x') - provider = Agent( - name='Internal Workflow', agent_code='generic', runtime_provider='dify', - dify_app_type='workflow', exposure_mode='internal', dify_app_id='provider', - dify_api_key='key', api_base_url='http://dify.example/v1', is_active=True, - ) - db.session.add_all([user, provider]) - db.session.commit() - with pytest.raises(ValidationError) as caught: - update_agent_permissions(provider.id, [user.id]) - assert caught.value.code == 'AGENT.INTERNAL_EXECUTOR_PERMISSION_FORBIDDEN' - - -def test_admin_agent_list_scopes_separate_applications_and_executors(app): - """管理页签后端列表必须按 workspace/internal 隔离。""" - with app.app_context(): - application = Agent(name='Workspace App', exposure_mode='workspace', agent_code='generic') - executor = Agent( - name='Internal Executor', exposure_mode='internal', - runtime_provider='dify', dify_app_type='workflow', dify_app_id='scope-provider', - dify_api_key='key', api_base_url='http://dify.example/v1', - ) - db.session.add_all([application, executor]) - db.session.commit() - assert {item['exposure_mode'] for item in list_agents(scope='applications')} == {'workspace'} - assert {item['exposure_mode'] for item in list_agents(scope='executors')} == {'internal'} - - -def test_run_creation_requires_explicit_binding(app): - """删除显式绑定后创建 Run 必须阻断,且不得产生 Run 或 Job。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input() - AgentRuntimeBinding.query.delete() - db.session.commit() - - with pytest.raises(ConflictError) as caught: - create_order_extraction_run( - user=user, - agent_id=agent.id, - conversation_id=session.session_id, - intake_nos=[intake.intake_no], - ) - - assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_NOT_CONFIGURED' - assert ShippingOrderExtractionRun.query.count() == 0 - assert Job.query.filter_by(job_type=JobType.SHIPPING_ORDER_EXTRACTION.value).count() == 0 - - -def test_runtime_binding_admin_api_and_internal_agent_hidden(app, client, admin_headers): - """管理员可显式保存绑定;internal Provider 不出现在普通用户 Agent 列表。""" - with app.app_context(): - admin = User(username='binding-admin', email='binding-admin@example.com', role='admin', password_hash='x') - owner = Agent( - name='Shipping Owner', agent_code='shipping_notice', runtime_provider='hybrid', - dify_app_id='owner-app', dify_api_key='owner-key', api_base_url='http://dify.example/v1', - exposure_mode='workspace', is_active=True, - ) - provider = Agent( - name='Internal Extraction', agent_code='generic', runtime_provider='dify', - dify_app_type='workflow', conversation_mode='task_chat', exposure_mode='internal', - dify_app_id='provider-app', dify_api_key='provider-key', api_base_url='http://dify.example/v1', - is_active=True, - ) - db.session.add_all([admin, owner, provider]) - db.session.commit() - token = issue_local_access_token(admin) - owner_id = owner.id - provider_id = provider.id - - auth = {'Authorization': f'Bearer {token}'} - saved = client.put( - f'/api/admin/agents/{owner_id}/runtime-bindings/shipping.order_extraction', - json={ - 'provider_agent_id': provider_id, - 'enabled': True, - 'config': {'timeout_seconds': 600, 'max_attempts': 2}, - }, - headers=auth, - ) - assert saved.status_code == 200 - assert saved.get_json()['data']['provider_agent_id'] == provider_id - assert saved.get_json()['data']['config'] == { - 'timeout_seconds': 600, - 'max_attempts': 2, - } - assert 'dify_api_key' not in saved.get_json()['data'] - - listed = client.get('/api/agents', headers=auth) - assert listed.status_code == 200 - assert {item['id'] for item in listed.get_json()} == {owner_id} - - -def test_worker_caches_provider_output_and_does_not_call_dify_twice(app, caplog): - """Provider 成功结果即使没有 run_id 也先保存;持久化失败重试不得再次调用 Dify。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input() - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - db.session.commit() - job = claim_next_job( - domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], worker_id='test-worker', - ) - assert job is not None - ctx = JobContext(config={}, logger=app.logger) - calls = {'dify': 0, 'persist': 0} - caplog.set_level(logging.INFO) - - def _execute(**_kwargs): - calls['dify'] += 1 - return [], {'workflow_run_id': None, 'poll_used': False, 'retry_count': 0, 'provider_status': 'succeeded'} - - def _persist(**_kwargs): - calls['persist'] += 1 - if calls['persist'] == 1: - raise RuntimeError('database temporarily unavailable') - return { - 'batch_no': None, 'created_count': 0, 'opened_existing_count': 0, - 'pending_count': 0, 'non_shipping_count': 1, - } - - with patch( - 'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow', - side_effect=_execute, - ), patch( - 'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result', - side_effect=_persist, - ): - with pytest.raises(RuntimeError): - run_shipping_order_extraction(ctx, {'job_id': job.id}) - db.session.expire_all() - retry_job = claim_next_job( - domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], worker_id='test-worker', - ) - assert retry_job is not None - run_shipping_order_extraction(ctx, {'job_id': retry_job.id}) - - db.session.expire_all() - finished = db.session.get(ShippingOrderExtractionRun, run.id) - assert calls == {'dify': 1, 'persist': 2} - assert finished.status == 'completed' - assert finished.dify_workflow_run_id is None - assert finished.provider_result_json['orders'] == [] - log_text = caplog.text - assert 'shipping_order_extraction_provider_completed' in log_text - assert 'shipping_order_extraction_attempt_failed' in log_text - assert 'database temporarily unavailable' not in log_text - assert str(run.input_snapshot_hash) not in log_text - assert 'provider_snapshot_json' not in log_text - assert db.session.get(Job, retry_job.id).status == 'success' - - -def test_resolve_binding_revalidates_disabled_provider(app): - """绑定保存后 Provider 被停用时,运行时必须阻断而不是继续使用旧凭据。""" - with app.app_context(): - _user, agent, _session, _intake, _document = _seed_run_input() - binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one() - binding.provider_agent.is_active = False - db.session.commit() - - with pytest.raises(ConflictError) as caught: - resolve_runtime_binding( - owner_agent_id=agent.id, - capability_code='shipping.order_extraction', - ) - - assert caught.value.code == 'AGENT.RUNTIME_PROVIDER_DISABLED' - - -def test_admin_can_disable_binding_when_provider_is_already_disabled(app): - """Provider 故障停用后管理员仍应能关闭绑定,避免配置陷入无法修改状态。""" - with app.app_context(): - _user, agent, _session, _intake, _document = _seed_run_input() - binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one() - binding.provider_agent.is_active = False - db.session.commit() - - saved = save_runtime_binding( - owner_agent_id=agent.id, - capability_code='shipping.order_extraction', - provider_agent_id=binding.provider_agent_id, - enabled=False, - config=binding.config_json, - ) - - assert saved.enabled is False - - -def test_stale_job_recovery_synchronizes_run_state(app): - """超时 Job 回到 queued 或最终 failed 时,领域 Run 必须同步离开 running。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input() - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - job = db.session.get(Job, run.current_job_id) - run.status = 'running' - run.phase = 'calling_provider' - job.status = 'running' - job.attempts = 1 - job.max_attempts = 2 - job.started_at = datetime.utcnow() - timedelta(minutes=30) - db.session.commit() - - recovered = recover_stale_jobs( - domain='shipping_notice', - timeout_seconds=60, - job_type=JobType.SHIPPING_ORDER_EXTRACTION, - on_recovered=sync_order_extraction_run_after_job_recovery, - ) - db.session.expire_all() - assert recovered == 1 - assert db.session.get(Job, job.id).status == 'queued' - assert db.session.get(ShippingOrderExtractionRun, run.id).status == 'queued' - - job = db.session.get(Job, job.id) - run = db.session.get(ShippingOrderExtractionRun, run.id) - run.status = 'running' - job.status = 'running' - job.attempts = 2 - job.started_at = datetime.utcnow() - timedelta(minutes=30) - db.session.commit() - recovered = recover_stale_jobs( - domain='shipping_notice', - timeout_seconds=60, - job_type=JobType.SHIPPING_ORDER_EXTRACTION, - on_recovered=sync_order_extraction_run_after_job_recovery, - ) - db.session.expire_all() - assert recovered == 1 - assert db.session.get(Job, job.id).status == 'failed' - assert db.session.get(ShippingOrderExtractionRun, run.id).status == 'failed' - - -def test_worker_rejects_provider_type_drift(app): - """Run 排队后 Provider 被改成 Chatflow 时必须失败,不能调用错误的 Dify API。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input() - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - provider = db.session.get(Agent, run.provider_agent_id) - provider.dify_app_type = 'chatflow' - db.session.commit() - job = claim_next_job( - domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], worker_id='test-worker', - ) - - with patch( - 'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow', - ) as execute: - run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id}) - - db.session.expire_all() - assert execute.call_count == 0 - assert db.session.get(Job, job.id).status == 'failed' - assert db.session.get(ShippingOrderExtractionRun, run.id).status == 'failed' - - -@pytest.mark.parametrize('changed_field', ['dify_app_id', 'api_base_url']) -def test_worker_rejects_provider_execution_identity_drift(app, changed_field): - """Run 冻结后 Provider App ID 或 Base URL 变化必须失败,避免调用到另一套 Workflow。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input() - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - provider = db.session.get(Agent, run.provider_agent_id) - setattr(provider, changed_field, f'changed-{changed_field}') - db.session.commit() - job = claim_next_job( - domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], worker_id='test-worker', - ) - - with patch( - 'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow', - ) as execute: - run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id}) - - db.session.expire_all() - assert execute.call_count == 0 - failed = db.session.get(ShippingOrderExtractionRun, run.id) - assert failed.status == 'failed' - assert failed.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_CHANGED' - - -def test_worker_allows_provider_api_key_rotation(app): - """API Key 不属于冻结执行身份;轮换后旧 Run 应使用新密钥继续执行。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input() - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - provider = db.session.get(Agent, run.provider_agent_id) - provider.dify_api_key = 'rotated-provider-key' - db.session.commit() - job = claim_next_job( - domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], worker_id='test-worker', - ) - - def _execute(*, provider, **_kwargs): - assert provider.dify_api_key == 'rotated-provider-key' - return [], {'workflow_run_id': 'wf-rotated', 'provider_status': 'succeeded'} - - with patch( - 'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow', - side_effect=_execute, - ): - run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id}) - - db.session.expire_all() - assert db.session.get(ShippingOrderExtractionRun, run.id).status == 'completed' - assert db.session.get(Job, job.id).status == 'success' - - -@pytest.mark.parametrize( - ('upstream_error', 'expected_code'), - [ - (requests.exceptions.ReadTimeout('slow workflow'), 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT'), - (requests.exceptions.ConnectionError('connection lost'), 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED'), - ], -) -def test_workflow_request_errors_are_classified(app, upstream_error, expected_code): - """Dify 超时与其他网络失败必须输出稳定错误码,供 Worker 重试和前端提示。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input() - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - provider = db.session.get(Agent, run.provider_agent_id) - unit = run.extraction_plan.units[0] - - with patch( - 'app.services.shipping_notice.order_extraction_workflow.DifyService.run_workflow_streaming', - side_effect=upstream_error, - ), pytest.raises(Exception) as caught: - execute_order_extraction_workflow(run=run, unit=unit, provider=provider, timeout_seconds=30) - - assert getattr(caught.value, 'code', None) == expected_code - assert getattr(caught.value, 'retryable', False) is True - - -@pytest.mark.parametrize( - 'workflow_result', - [ - None, - {'status': 'failed', 'error': 'inventory_source_hint must not be a line number'}, - {'status': 'succeeded', 'outputs': {'orders': 'not-json'}}, - ], -) -def test_workflow_terminal_or_output_contract_errors_are_not_retryable(workflow_result): - """Dify 已返回终态的画布/输出错误不得触发 Unit 重试或 Provider 熔断。""" - with pytest.raises(ValidationError) as caught: - parse_order_extraction_workflow_result(workflow_result) - - assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE' - assert caught.value.retryable is False - - -def test_dify_terminal_contract_error_does_not_retry_or_open_circuit(app): - """Dify 已返回画布校验失败时,同一 Unit 不重复调用且不累计 Provider 熔断失败。""" - error = ValidationError( - 'inventory_source_hint must not be a line number', - code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE', - ) - run_snapshot = { - 'id': 1, 'run_no': 'SNER-CONTRACT-ERROR', 'user_id': 1, - 'schema_version_id': 1, - 'input_snapshot_hash': 'a' * 64, 'input_snapshot_json': {}, - 'provider_config_json': {}, - } - unit_snapshot = { - 'id': 1, 'intake_id': 1, 'document_id': 1, - 'document_type': 'attachment', 'unit_type': 'document_extraction', - } - provider_snapshot = {'id': 998877, 'api_base_url': 'http://dify.example/v1', 'dify_api_key': 'key'} - - with patch( - 'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow', - side_effect=error, - ) as execute, patch( - 'app.jobs.handlers.shipping_order_extraction.record_provider_failure', - ) as record_failure, pytest.raises(ValidationError) as caught: - _execute_dify_unit_with_retry( - app=app, run_snapshot=run_snapshot, unit_snapshot=unit_snapshot, - provider_snapshot=provider_snapshot, timeout_seconds=30, - max_attempts=3, backoff_ms=1, job_id=1, job_attempt=1, - provider_max_concurrency=1, circuit_failure_threshold=2, - circuit_cooldown_seconds=60, - ) - - assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE' - assert execute.call_count == 1 - record_failure.assert_not_called() - - -def test_workflow_inputs_use_unique_extraction_contract_only(app): - """唯一 Workflow manifest 仅含冻结抽取契约与受控提示,完整定义不得旁路泄露。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input() - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - unit = run.extraction_plan.units[0] - inputs = build_order_extraction_workflow_inputs(run, unit=unit) - manifest = json.loads(inputs['execution_manifest']) - schema = manifest['extraction_contract'] - document = manifest['document'] - readonly_context = manifest['readonly_hints'] - - assert schema == run.input_snapshot_json['schema']['extraction_contract'] - assert 'contract_version' not in manifest - assert manifest['run']['run_no'] == run.run_no - assert manifest['unit']['unit_id'] == unit.id - assert manifest['unit']['document_id'] == unit.document_id - assert manifest['integrity']['input_snapshot_hash'] == run.input_snapshot_hash - assert 'definition' not in schema - assert schema['fields'][0]['field_id'] == 'qty-id' - assert document['document_id'] == unit.document_id - assert 'sales-' not in repr(document).lower() - assert readonly_context == [] - assert set(inputs) == {'execution_manifest'} - - -def test_workflow_execution_sends_only_versioned_manifest(app): - """Workflow 调用边界只能发送 execution_manifest,禁止回退到旧五变量契约。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input() - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - provider = db.session.get(Agent, run.provider_agent_id) - unit = run.extraction_plan.units[0] - - with patch( - 'app.services.shipping_notice.order_extraction_workflow.DifyService.run_workflow_streaming', - return_value={'status': 'succeeded', 'outputs': {'orders': []}, 'workflow_run_id': 'wf-manifest'}, - ) as mocked_run: - orders, metadata = execute_order_extraction_workflow( - run=run, unit=unit, provider=provider, timeout_seconds=30, - ) - - inputs = mocked_run.call_args.kwargs['inputs'] - manifest = json.loads(inputs['execution_manifest']) - assert set(inputs) == {'execution_manifest'} - assert 'contract_version' not in manifest - assert manifest['run']['run_no'] == run.run_no - assert manifest['unit']['unit_id'] == unit.id - assert manifest['integrity']['input_snapshot_hash'] == run.input_snapshot_hash - assert orders == [] - assert metadata['workflow_run_id'] == 'wf-manifest' - - -def test_unique_manifest_sends_compact_layout_candidates_only(app): - """唯一 Manifest 只发送紧凑字段候选,禁止泄漏 bbox、HTML、token、cell_id 或 field_code。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input(suffix='UNIT-V3') - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, - intake_nos=[intake.intake_no], - ) - unit = run.extraction_plan.units[0] - frozen = run.input_snapshot_json['intakes'][0]['documents'][0] - frozen['layout_snapshot'] = {'html': 'RAW-HTML', 'bbox': [1, 2, 3, 4]} - frozen['layout_schema_candidates'] = [{ - 'page_no': 2, 'table_id': 'table-1', 'mapping_status': 'candidate', - 'issues': ['layout_table_not_accepted'], - 'rows': [{ - 'row_index': 3, 'role': 'data', 'issues': [], - 'fields': [{ - 'field_id': 'qty-id', 'field_code': 'qty', 'value': 30, - 'quote': 'Qty 30', 'column_index': 4, 'cell_id': 'secret-cell', - 'token_ids': ['secret-token'], 'evidence_ref': 'secret-ref', - }], - }], - }] - - manifest = json.loads(build_order_extraction_workflow_inputs(run, unit=unit)['execution_manifest']) - - assert 'contract_version' not in manifest - assert manifest['structured_table_candidates'][0]['field_policy'] == 'suggested' - assert manifest['structured_table_candidates'][0]['rows'][0]['fields'] == [{ - 'column_index': 4, 'field_id': 'qty-id', 'value': 30, 'quote': 'Qty 30', - }] - assert 'documents' not in manifest - serialized = repr({ - 'document': manifest['document'], - 'structured_table_candidates': manifest['structured_table_candidates'], - }) - for forbidden in ('RAW-HTML', 'bbox', 'secret-cell', 'secret-token', 'secret-ref', 'field_code'): - assert forbidden not in serialized - - -def test_unique_manifest_prefers_mineru_pdf_text_and_table_grid(app): - """PDF 有 ready MinerU 快照时应向模型发送分页文本和 TSV 表格,替换旧拍平文本。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input(suffix='MINERU-TEXT') - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, - intake_nos=[intake.intake_no], - ) - unit = run.extraction_plan.units[0] - frozen = run.input_snapshot_json['intakes'][0]['documents'][0] - frozen['filename'] = 'order.pdf' - frozen['extracted_text'] = 'LEGACY-FLAT-TEXT' - frozen['layout_snapshot'] = { - 'status': 'ready', - 'text_blocks': [{ - 'page_no': 1, 'normalized_bbox': {'x0': 0.1, 'y0': 0.1}, - 'text': 'PO Number: 4518838154', - }], - 'tables': [{ - 'table_id': 'table-1', 'page_no': 1, - 'normalized_bbox': {'x0': 0.1, 'y0': 0.3}, - 'html': '' - '
ItemReservation ID
0002012345
', - }], - } - - manifest = json.loads(build_order_extraction_workflow_inputs(run, unit=unit)['execution_manifest']) - - document = manifest['document'] - assert document['text_source'] == 'mineru' - assert 'LEGACY-FLAT-TEXT' not in document['extracted_text'] - assert 'PO Number: 4518838154' in document['extracted_text'] - assert 'Item\tReservation ID' in document['extracted_text'] - assert '00020\t12345' in document['extracted_text'] - assert 'html' not in repr(document) - - -def test_unique_manifest_accepted_layout_fields_cannot_be_overridden(app): - """唯一 Manifest 模型可以补充候选,但 accepted 字段缺失或改值必须被后端拒绝。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input(suffix='LOCKED-FIELD') - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, - intake_nos=[intake.intake_no], - ) - unit = run.extraction_plan.units[0] - run.input_snapshot_json['intakes'][0]['documents'][0]['layout_schema_candidates'] = [{ - 'mapping_status': 'accepted', 'rows': [{ - 'role': 'data', 'fields': [{'field_id': 'qty-id', 'value': 30}], - }], - }] - invalid = [{ - 'source_intake_no': intake.intake_no, 'primary_document_id': unit.document_id, - 'header_fields': [], 'lines': [{'fields': [{ - 'field_id': 'qty-id', 'observations': [{ - 'value': 31, 'document_id': unit.document_id, - }], - }]}], - }] - - with pytest.raises(ValidationError) as caught: - validate_unit_orders(run, unit=unit, orders=invalid) - - assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE' - - -def test_accepted_layout_without_approved_profile_uses_provider(app): - """仅 L4 accepted 表格不是模板盲测凭证,未批准 Profile 仍必须走受控兜底。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input(suffix='LAYOUT-ZERO-PROVIDER') - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, - intake_nos=[intake.intake_no], - ) - unit = run.extraction_plan.units[0] - run.input_snapshot_json['intakes'][0]['documents'][0]['layout_schema_candidates'] = [{ - 'mapping_status': 'accepted', 'issues': [], - 'rows': [{ - 'role': 'data', 'fields': [{ - 'field_id': 'qty-id', 'value': 30, 'quote': 'Qty 30', - }], - }], - }] - from app.services.shipping_notice.order_extraction_workflow import build_deterministic_unit_orders - - orders = build_deterministic_unit_orders(run, unit=unit) - - assert orders is None - - -def test_approved_profile_builds_order_from_its_own_parsed_rows(app): - """关键断言:零 Provider 订单只能取已批准 Profile 的实际解析行,不能借用 L4 候选。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input(suffix='APPROVED-PROFILE') - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, - intake_nos=[intake.intake_no], - ) - unit = run.extraction_plan.units[0] - with patch( - 'app.services.shipping_notice.order_extraction_workflow._profile_table_candidates', - return_value={ - 'matched': True, 'blocking': False, 'issues': [], - 'tables': [{ - 'table_id': 'profile-table', 'auto_create_approved': True, - 'rows': [{ - 'row_index': 1, 'status': 'parsed', 'issues': [], - 'fields': [{'field_id': 'qty-id', 'field_code': 'qty', 'value': 30, 'quote': 'Qty 30'}], - }], - }], - }, - ): - from app.services.shipping_notice.order_extraction_workflow import build_deterministic_unit_orders - - orders = build_deterministic_unit_orders(run, unit=unit) - - assert orders is not None - assert orders[0]['lines'][0]['fields'][0]['observations'][0]['value'] == 30 - - -def test_coordinate_v2_profile_builds_from_frozen_coordinates_without_html(app): - """v2 运行只消费冻结 bbox/字符证据;MinerU HTML 缺失也不得回退为固定列解析。""" - with app.app_context(): - user, agent, session, intake, document = _seed_run_input(suffix='COORDINATE-V2') - version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() - version.definition_json = {'fields': [ - { - 'field_id': 'line-id', 'field_code': 'line_no', 'scope': 'line', 'value_type': 'string', - 'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': [], - }, - { - 'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', - 'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': [], - }, - { - 'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', - 'enabled': True, 'required': True, 'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'], - }, - { - 'field_id': 'uom-id', 'field_code': 'uom', 'scope': 'line', 'value_type': 'string', - 'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': [], - }, - ]} - - def glyphs() -> list[dict]: - values = [] - for text, x0 in [('00010', 10), ('PART-A', 90), ('3 EA', 210)]: - for offset, char in enumerate(text): - values.append({'text': char, 'bbox': { - 'x0': x0 + offset * 4, 'y0': 20, 'x1': x0 + offset * 4 + 3, 'y1': 30, - }}) - return values - - definition = { - 'contract_version': 'order_coordinate_profile.v2', - 'document_match': {'required_anchors': []}, - 'table_regions': [{ - 'region_id': 'main_lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, - 'header_layouts': [], 'termination_rules': [], 'exclusion_regions': [], - 'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []}, - 'line_layouts': [{ - 'layout_id': 'main', 'row_offset': 0, 'role': 'main', - 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, - 'field_regions': [ - {'field_id': 'line-id', 'field_code': 'line_no', 'target_fields': [{'field_id': 'line-id', 'field_code': 'line_no'}], 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}, - {'field_id': 'part-id', 'field_code': 'part_number', 'target_fields': [{'field_id': 'part-id', 'field_code': 'part_number'}], 'region': {'x0': .3, 'y0': 0, 'x1': .7, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}, - {'field_id': 'qty-id', 'field_code': 'qty', 'extractor_key': 'quantity_uom', 'target_fields': [{'field_id': 'qty-id', 'field_code': 'qty'}, {'field_id': 'uom-id', 'field_code': 'uom'}], 'region': {'x0': .7, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}, - ], 'continuation_conditions': [], 'required_fields': ['line_no', 'part_number', 'qty', 'uom'], 'allowed_empty_fields': [], - }], - }], - } - profile = ShippingOrderDocumentProfile( - profile_code='COORDINATE_V2', display_name='Coordinate v2', version=1, status='published', - schema_version_id=version.id, structure_fingerprint='c' * 64, checksum='d' * 64, - definition_json=definition, published_at=datetime.utcnow(), - ) - record_inline_layout_snapshot(document, { - 'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready', - 'tables': [{'table_id': 'coordinate-only', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 300, 'y1': 60}}], - 'coordinate_evidence': { - 'tables': {'coordinate-only': glyphs()}, - 'pages': {'1': {'width': 300, 'height': 60}}, - }, - }) - db.session.add(profile) - db.session.commit() - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - unit = run.extraction_plan.units[0] - run.input_snapshot_json['order_document_profiles'][0]['auto_create_approved'] = True - - from app.services.shipping_notice.order_extraction_workflow import ( - _build_approved_profile_order, - _profile_table_candidates, - build_deterministic_unit_orders, - ) - - candidates = _profile_table_candidates(run, unit=unit) - assert candidates['blocking'] is False, candidates - assert candidates['tables'] and candidates['tables'][0]['auto_create_approved'] is True, candidates - direct = _build_approved_profile_order( - unit=unit, intake=run.input_snapshot_json['intakes'][0], - schema=run.input_snapshot_json['schema']['extraction_contract'], - definition=run.input_snapshot_json['schema']['definition'], table=candidates['tables'][0], - ) - assert direct is not None, candidates - orders = build_deterministic_unit_orders(run, unit=unit) - assert orders is not None - fields = {field['field_id']: field['observations'][0]['value'] for field in orders[0]['lines'][0]['fields']} - assert fields == {'line-id': '00010', 'part-id': 'PART-A', 'qty-id': 3, 'uom-id': 'EA'} - - -def test_coordinate_v2_profile_uses_page_relative_regions_not_table_bbox(app): - """画布保存整页相对区域;运行时不得再按 MinerU 表格 bbox 二次缩放。""" - with app.app_context(): - user, agent, session, intake, document = _seed_run_input(suffix='COORDINATE-PAGE-SPACE') - version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() - version.definition_json = {'fields': [ - { - 'field_id': 'line-id', 'field_code': 'line_no', 'scope': 'line', 'value_type': 'string', - 'enabled': True, 'required': False, 'normalizer_key': 'trim', 'validator_keys': [], - }, - { - 'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', - 'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': [], - }, - ]} - profile = ShippingOrderDocumentProfile( - profile_code='COORDINATE_PAGE_SPACE', display_name='Coordinate page space', version=1, status='published', - schema_version_id=version.id, structure_fingerprint='e' * 64, checksum='f' * 64, - definition_json={ - 'contract_version': 'order_coordinate_profile.v2', 'document_match': {'required_anchors': []}, - 'table_regions': [{ - 'region_id': 'main_lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, - 'header_layouts': [], 'termination_rules': [], 'exclusion_regions': [], - 'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []}, - 'line_layouts': [{ - 'layout_id': 'main', 'row_offset': 0, 'role': 'main', - # This real canvas region is page-relative (x=20..80 on a 200pt page), - # while MinerU's table bbox begins at x=50 and must not offset it again. - 'region': {'x0': .1, 'y0': .4, 'x1': .4, 'y1': .6}, - 'field_regions': [ - {'field_id': 'line-id', 'field_code': 'line_no', 'target_fields': [{'field_id': 'line-id', 'field_code': 'line_no'}], 'region': {'x0': .1, 'y0': .4, 'x1': .2, 'y1': .6}, 'allowed_sources': ['pdf_coordinate']}, - {'field_id': 'part-id', 'field_code': 'part_number', 'target_fields': [{'field_id': 'part-id', 'field_code': 'part_number'}], 'region': {'x0': .2, 'y0': .4, 'x1': .4, 'y1': .6}, 'allowed_sources': ['pdf_coordinate']}, - ], 'continuation_conditions': [], 'required_fields': ['line_no', 'part_number'], 'allowed_empty_fields': [], - }], - }], - }, published_at=datetime.utcnow(), - ) - glyphs = [] - for text, x0 in [('00010', 22), ('PART-PAGE', 45)]: - for offset, char in enumerate(text): - glyphs.append({'text': char, 'bbox': {'x0': x0 + offset * 4, 'y0': 90, 'x1': x0 + offset * 4 + 3, 'y1': 100}}) - record_inline_layout_snapshot(document, { - 'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready', - 'tables': [{'table_id': 'offset-table', 'page_no': 1, 'bbox': {'x0': 50, 'y0': 70, 'x1': 160, 'y1': 140}}], - 'coordinate_evidence': {'tables': {'offset-table': glyphs}, 'pages': {'1': {'width': 200, 'height': 200}}}, - }) - db.session.add(profile) - db.session.commit() - run, _ = create_order_extraction_run(user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no]) - unit = run.extraction_plan.units[0] - run.input_snapshot_json['order_document_profiles'][0]['auto_create_approved'] = True - from app.services.shipping_notice.order_extraction_workflow import build_deterministic_unit_orders - orders = build_deterministic_unit_orders(run, unit=unit) - assert orders is not None - values = { - field['field_id']: field['observations'][0]['value'] - for field in orders[0]['lines'][0]['fields'] - } - assert values['part-id'] == 'PART-PAGE' - - -def test_plain_text_complete_table_still_uses_provider(app): - """纯文本表格即使字段齐全也不能零 Provider,防止 L7 恢复猜列运行路径。""" - with app.app_context(): - user, agent, session, intake, document = _seed_run_input(suffix='DETERMINISTIC') - version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() - version.definition_json = {'fields': [ - { - 'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', - 'value_type': 'string', 'enabled': True, 'required': True, - 'aliases': ['Part Number'], 'normalizer_key': 'trim', 'validator_keys': [], - }, - { - 'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', - 'value_type': 'decimal', 'enabled': True, 'required': True, - 'aliases': ['Qty'], 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal'], - }, - ]} - document.extracted_text = 'Part Number\tQty\nPN-001\t3' - db.session.commit() - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, - intake_nos=[intake.intake_no], - ) - db.session.commit() - job = claim_next_job( - domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], - worker_id='deterministic-worker', - ) - - with patch( - 'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow', - return_value=([], {'workflow_run_id': 'wf-plain-text', 'execution_mode': 'dify'}), - ) as execute, patch( - 'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result', - return_value={ - 'batch_no': None, 'created_count': 0, 'opened_existing_count': 0, - 'pending_count': 0, 'non_shipping_count': 0, - }, - ) as submit: - run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id}) - - db.session.expire_all() - finished = db.session.get(ShippingOrderExtractionRun, run.id) - unit = finished.extraction_plan.units[0] - assert execute.call_count == 1 - assert submit.call_args.kwargs['orders'] == [] - assert unit.status == 'succeeded' - assert unit.result_json['workflow']['execution_mode'] == 'dify' - assert finished.provider_result_json['workflow']['deterministic_unit_count'] == 0 - - -def test_profile_template_candidate_uses_provider_after_l7_cleanup(app): - """Profile 仍提供紧凑语义候选,但未获 accepted cell 前不能跳过 Provider。""" - with app.app_context(): - user, agent, session, intake, document = _seed_run_input(suffix='PROFILE-MAP') - version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() - version.definition_json = {'fields': [ - { - 'field_id': 'customer-id', 'field_code': 'customer_part_number', 'scope': 'line', - 'value_type': 'string', 'enabled': True, 'required': False, - 'normalizer_key': 'trim', 'validator_keys': [], - }, - { - 'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', - 'value_type': 'string', 'enabled': True, 'required': True, - 'normalizer_key': 'trim', 'validator_keys': [], - }, - { - 'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', - 'value_type': 'decimal', 'enabled': True, 'required': True, - 'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'], - }, - ]} - html = ( - '' - '' - '
LNPart NumberVendor Item#Qty
1CUSTOMER-1INTERNAL-13
2CUSTOMER-ZINTERNAL-Z0
' - ) - from app.services.shipping_notice.document_layout.html_table import parse_html_grid - from app.services.shipping_notice.document_layout.order_profile import order_profile_structure_fingerprint - - fingerprint = order_profile_structure_fingerprint(parse_html_grid(html, table_id='fixture'), header_row_index=0) - profile = ShippingOrderDocumentProfile( - profile_code='PO_312207', display_name='PO template', version=1, status='published', - schema_version_id=version.id, structure_fingerprint=fingerprint, checksum='e' * 64, - definition_json={ - 'contract_version': 'shipping_order_document_profile.v1', - 'structure_fingerprint': fingerprint, 'header_row_index': 0, - 'data_start_row_index': 1, 'row_structure': 'preserved', 'drop_zero_qty': True, - 'column_rules': [ - {'column_index': 1, 'extractor_key': 'direct', 'target_field_codes': ['customer_part_number'], - 'target_fields': [{'field_id': 'customer-id', 'field_code': 'customer_part_number'}]}, - {'column_index': 2, 'extractor_key': 'direct', 'target_field_codes': ['part_number'], - 'target_fields': [{'field_id': 'part-id', 'field_code': 'part_number'}]}, - {'column_index': 3, 'extractor_key': 'direct', 'target_field_codes': ['qty'], - 'target_fields': [{'field_id': 'qty-id', 'field_code': 'qty'}]}, - ], - }, published_at=datetime.utcnow(), - ) - record_inline_layout_snapshot(document, { - 'snapshot_version': 'shipping_document_table_snapshot.v1', - 'provider': 'mineru', 'backend': 'pipeline', 'status': 'ready', 'issues': [], - 'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': html}], - }) - db.session.add(profile) - db.session.commit() - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, - intake_nos=[intake.intake_no], - ) - db.session.commit() - job = claim_next_job( - domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], - worker_id='profile-worker', - ) - - with patch( - 'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow', - return_value=([], {'workflow_run_id': 'wf-profile', 'execution_mode': 'dify'}), - ) as execute, patch( - 'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result', - return_value={ - 'batch_no': None, 'created_count': 0, 'opened_existing_count': 0, - 'pending_count': 0, 'non_shipping_count': 0, - }, - ) as submit: - run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id}) - - execute.assert_called_once() - route_decision = ShippingOrderExtractionRouteDecision.query.filter_by(unit_id=run.extraction_plan.units[0].id).one() - # 关键断言:即使 Provider 成功或失败,进入 Dify 前的匹配与审批事实已经独立持久化。 - assert route_decision.decision == 'dify' - assert route_decision.match_status == 'unique_match' - assert route_decision.fallback_reason_codes_json == ['profile_not_auto_create_approved'] - manifest = json.loads(execute.call_args.kwargs['run'].input_snapshot_json and build_order_extraction_workflow_inputs( - run, unit=run.extraction_plan.units[0], - )['execution_manifest']) - assert manifest['structured_table_candidates'] == [] - assert submit.call_args.kwargs['orders'] == [] - - -def test_profile_layout_html_is_not_sent_to_dify(app): - """Profile 不完整而回退 Dify 时,Manifest 只能携带紧凑候选,不能含坐标或原始 HTML。""" - with app.app_context(): - user, agent, session, intake, document = _seed_run_input(suffix='PROFILE-TOKEN') - record_inline_layout_snapshot(document, { - 'snapshot_version': 'shipping_document_table_snapshot.v1', - 'provider': 'mineru', 'backend': 'pipeline', 'status': 'ready', 'issues': [], - 'tables': [{ - 'table_id': 'table-secret', 'page_no': 1, - 'bbox': {'x0': 1, 'y0': 2, 'x1': 3, 'y1': 4}, - 'html': '
RAW-LAYOUT-SECRET
', - }], - }) - db.session.commit() - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, - intake_nos=[intake.intake_no], - ) - unit = run.extraction_plan.units[0] - - manifest = json.loads(build_order_extraction_workflow_inputs(run, unit=unit)['execution_manifest']) - - assert 'layout_snapshot' not in manifest['document'] - assert 'layout_schema_candidates' not in manifest['document'] - # 表格文字可作为 TSV 上下文提供给 LLM;布局 HTML 与坐标/证据内部标识不得泄漏。 - assert 'RAW-LAYOUT-SECRET' in manifest['document']['extracted_text'] - assert '= 100 - - -def test_worker_persists_successful_units_when_one_unit_exhausts_retries(app): - """一个单元永久失败时,成功单元仍提交,Run 以 needs_review 收口。""" - with app.app_context(): - user, agent, session, intake, first = _seed_run_input(suffix='PARTIAL') - second = ShippingNoticeDocument( - intake_id=intake.id, document_type='attachment', attachment_key='partial-2.pdf', - content_hash='f' * 64, classification='order_notice', parse_status='parsed', - extracted_text='Second unstructured document', - ) - db.session.add(second) - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, - intake_nos=[intake.intake_no], - ) - db.session.commit() - job = claim_next_job( - domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], - worker_id='partial-worker', - ) - submitted = {} - - def execute(*, unit, **_kwargs): - if unit.document_id == second.id: - raise requests.exceptions.ReadTimeout('permanent unit timeout') - return [], {'workflow_run_id': f'wf-{first.id}', 'provider_status': 'succeeded'} - - def submit(*, orders, **_kwargs): - submitted['orders'] = orders - return { - 'batch_no': None, 'created_count': 0, 'opened_existing_count': 0, - 'pending_count': 0, 'non_shipping_count': 0, - } - - with patch( - 'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow', - side_effect=execute, - ), patch( - 'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result', - side_effect=submit, - ): - run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id}) - - db.session.expire_all() - finished = db.session.get(ShippingOrderExtractionRun, run.id) - statuses = {unit.document_id: unit.status for unit in finished.extraction_plan.units} - assert submitted['orders'] == [] - assert statuses[first.id] == 'succeeded' - assert statuses[second.id] == 'failed' - assert finished.status == 'needs_review' - assert finished.result_json['failed_unit_count'] == 1 - - -def test_worker_blocks_model_calls_when_frozen_unit_budget_is_exceeded(app): - """需要模型的文档数超过 Run 冻结预算时必须在发请求前阻断。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input(suffix='BUDGET') - db.session.add(ShippingNoticeDocument( - intake_id=intake.id, document_type='attachment', attachment_key='budget-2.pdf', - content_hash='9' * 64, classification='order_notice', parse_status='parsed', - extracted_text='Another unstructured document', - )) - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, - intake_nos=[intake.intake_no], - ) - run.provider_config_json = {**dict(run.provider_config_json or {}), 'max_model_units': 1} - db.session.commit() - job = claim_next_job( - domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], - worker_id='budget-worker', - ) - - with patch( - 'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow', - ) as execute: - run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id}) - - db.session.expire_all() - assert execute.call_count == 0 - failed = db.session.get(ShippingOrderExtractionRun, run.id) - assert failed.status == 'failed' - assert failed.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_MODEL_BUDGET_EXCEEDED' - - -@pytest.mark.parametrize( - 'orders_output', - [ - [{'classification': 'shipping_request'}], - json.dumps([{'classification': 'shipping_request'}]), - json.dumps(json.dumps([{'classification': 'shipping_request'}])), - json.dumps({'orders': [{'classification': 'shipping_request'}]}), - {'orders': json.dumps([{'classification': 'shipping_request'}])}, - ], -) -def test_workflow_result_accepts_dify_orders_serialization_variants(orders_output): - """Dify End 的数组和最多两层 String 包装均须还原为订单数组。""" - assert parse_order_extraction_workflow_result({ - 'status': 'succeeded', 'outputs': {'orders': orders_output}, - }) == [{'classification': 'shipping_request'}] - - -def test_workflow_readonly_context_uses_run_frozen_values(app): - """Intake 后续变化不得影响已创建 Run;Workflow 只能消费 Run 冻结的确定性值与策略。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input() - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - frozen = deepcopy(run.input_snapshot_json) - frozen['schema']['definition']['fields'].append({ - 'field_id': 'sender-id', 'field_code': 'sender_email', 'display_name': 'Sender email', - 'enabled': True, 'scope': 'header', 'collection_mode': 'deterministic_context', - 'dify_exposure_policy': 'confirmed_readonly', - 'context_source': {'provider_key': 'mail_header', 'option_key': 'from_email'}, - }) - frozen['intakes'][0]['deterministic_context'] = {'from_email': 'frozen@example.com'} - run.input_snapshot_json = frozen - intake.structured_result_json = {'email': {'from': 'changed@later.example'}} - db.session.commit() - - manifest = json.loads(build_order_extraction_workflow_inputs( - run, unit=run.extraction_plan.units[0], - )['execution_manifest']) - readonly_context = manifest['readonly_hints'] - - assert readonly_context[0]['fields'][0]['value'] == 'frozen@example.com' - assert 'changed@later.example' not in repr(readonly_context) - - -def test_worker_recovers_persisted_run_facts_without_duplicate_dify(app): - """Extraction/Candidate 已落库但 submission 缺失时,重试应从 run_id 恢复而非重复调用 Dify。""" - with app.app_context(): - user, agent, session, intake, document = _seed_run_input() - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - extraction = ShippingOrderExtraction( - run_id=run.id, - intake_id=intake.id, - schema_version_id=run.schema_version_id, - input_snapshot_hash=run.input_snapshot_hash, - input_snapshot_json=run.input_snapshot_json, - status='needs_review', - ) - db.session.add(extraction) - db.session.flush() - db.session.add(ShippingNoticeCandidate( - candidate_no='SNC-RUN-RECOVERY', - intake_id=intake.id, - primary_document_id=document.id, - candidate_key='run-recovery', - order_extraction_id=extraction.id, - order_extraction_run_id=run.id, - extraction_source='dify_workflow', - validation_status='needs_review', - selected=False, - )) - run.provider_result_json = {'orders': [], 'workflow': {'workflow_run_id': 'wf-recovery'}} - db.session.commit() - job = claim_next_job( - domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], worker_id='test-worker', - ) - - with patch( - 'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow', - ) as execute: - run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id}) - - db.session.expire_all() - assert execute.call_count == 0 - assert db.session.get(ShippingOrderExtractionRun, run.id).status == 'needs_review' - assert db.session.get(Job, job.id).status == 'success' - - -def test_manual_retry_reuses_cached_provider_result_without_duplicate_dify(app): - """失败卡片手工重试若已有 Provider 成功结果,只重跑 HXOPS 落库阶段。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input(suffix='MANUAL-RETRY-CACHE') - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - original_job = db.session.get(Job, run.current_job_id) - run.provider_result_json = {'orders': [], 'workflow': {'workflow_run_id': 'wf-manual-cache'}} - transition_order_extraction_run(run, target_status='running', phase='persisting_result') - transition_order_extraction_run(run, target_status='failed', error_message='database temporarily failed') - original_job.status = 'failed' - db.session.commit() - - retried, reused = retry_order_extraction_run(user_id=user.id, run_no=run.run_no) - db.session.commit() - assert reused is False - job = claim_next_job( - domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], worker_id='manual-retry-worker', - ) - assert job.id == retried.current_job_id - - with patch( - 'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow', - ) as execute, patch( - 'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result', - return_value={ - 'batch_no': None, - 'created_count': 0, - 'opened_existing_count': 0, - 'pending_count': 0, - 'non_shipping_count': 0, - }, - ): - run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id}) - - db.session.expire_all() - assert execute.call_count == 0 - assert db.session.get(ShippingOrderExtractionRun, run.id).status == 'completed' - assert db.session.get(Job, job.id).status == 'success' - - -def test_worker_recovers_consumed_empty_result_without_duplicate_dify(app): - """空订单/非发货结果已消费 Intake 后,重试应补 submission 并完成 Run。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input() - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - run.provider_result_json = {'orders': [], 'workflow': {'workflow_run_id': 'wf-empty'}} - intake.parse_status = 'consumed' - intake.consumed_at = datetime.utcnow() - db.session.commit() - job = claim_next_job( - domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], worker_id='test-worker', - ) - - with patch( - 'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow', - ) as execute: - run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id}) - - db.session.expire_all() - assert execute.call_count == 0 - assert db.session.get(ShippingOrderExtractionRun, run.id).status == 'completed' - assert db.session.get(Job, job.id).status == 'success' diff --git a/backend/tests/test_email_supplement_merge.py b/backend/tests/test_email_supplement_merge.py index 025f9a34..e97c23f4 100644 --- a/backend/tests/test_email_supplement_merge.py +++ b/backend/tests/test_email_supplement_merge.py @@ -6,7 +6,10 @@ from __future__ import annotations -from app.services.shipping_notice.email_allocation_table_parser import parse_email_allocation_tables +from app.services.shipping_notice.email_allocation_table_parser import ( + parse_email_allocation_tables, + parse_email_allocation_text, +) from app.services.shipping_notice.order_supplement_merge import merge_email_supplements @@ -69,3 +72,24 @@ def test_email_supplement_po_fallback_requires_one_reservation(): ]} result = merge_email_supplements(orders=[_order()], supplements_by_intake={1: ambiguous}, schema_definition=SCHEMA)[0] assert any(item.get('reason') == 'supplement_relation_ambiguous' for item in result['conflicts']) + + +def test_email_supplement_plain_text_vertical_table_is_parsed_without_guessing_body_text(): + """Outlook 展平的纵向表头可恢复补充行,尾部邮件正文不会被误当数据。""" + supplement = parse_email_allocation_text( + content_hash='b' * 64, + body_text='''Hello\nallocation_id\nreservation_id\nsource_from_party\nsource_type\nallocated_entity\nmpn\nallocated_qty\nPO#\nA-1\n2000484577\nWelltrust\nDSB CMH\nIEC-CJS\nD4-A08AR12000002\n30\n4518838152\nThank you''', + ) + assert supplement['rows'] == [{ + 'allocation_id': 'A-1', 'reservation_id': '2000484577', + 'source_from_party': 'Welltrust', 'source_type': 'DSB CMH', + 'allocated_entity': 'IEC-CJS', 'mpn': 'D4-A08AR12000002', + 'allocated_qty': '30', 'po_number': '4518838152', + 'evidence': supplement['rows'][0]['evidence'], 'table_index': None, 'row_index': 1, + }] + + +def test_email_supplement_plain_text_deduplicates_quoted_email_rows(): + """转发邮件重复同一正文表时只保留一个事实行,避免制造补充关联冲突。""" + body = '''allocation_id\nreservation_id\nsource_from_party\nsource_type\nallocated_entity\nmpn\nallocated_qty\nPO#\nA-1\n2000484577\nWelltrust\nDSB CMH\nIEC-CJS\nD4-A08AR12000002\n30\n4518838152\nA-1\n2000484577\nWelltrust\nDSB CMH\nIEC-CJS\nD4-A08AR12000002\n30\n4518838152''' + assert len(parse_email_allocation_text(body_text=body, content_hash='c' * 64)['rows']) == 1 diff --git a/backend/tests/test_internal_executor_user_isolation.py b/backend/tests/test_internal_executor_user_isolation.py deleted file mode 100644 index ca58cc99..00000000 --- a/backend/tests/test_internal_executor_user_isolation.py +++ /dev/null @@ -1,65 +0,0 @@ -""" -用途:验证内部执行器不会通过用户列表、详情、授权序列化或统一访问策略暴露。 -依赖:通用 app/client 测试夹具、JWT、本地 Agent/User 模型。 -""" - -import pytest - -from app import db -from app.core.auth.jwt import issue_local_access_token -from app.core.errors import ForbiddenError -from app.models import Agent, User -from app.services.admin.user_service import serialize_admin_user -from app.services.agent_user_access import require_user_application_access - - -def _seed_user_access_rows(): - """创建 workspace 应用、内部执行器及带历史脏授权的用户。""" - application = Agent(name='Visible Application', exposure_mode='workspace', is_active=True) - executor = Agent( - name='Hidden Executor', exposure_mode='internal', is_active=True, - runtime_provider='dify', dify_app_type='workflow', dify_app_id='hidden-workflow', - dify_api_key='key', - ) - user = User(username='isolated-user', email='isolated-user@example.com', role='user') - admin = User(username='isolated-admin', email='isolated-admin@example.com', role='admin') - user.agents.extend([application, executor]) - db.session.add_all([application, executor, user, admin]) - db.session.commit() - return application, executor, user, admin - - -def test_internal_executor_is_hidden_from_public_list_and_admin_user_detail(app, client): - """公开列表和管理员普通用户详情接口都不能暴露内部执行器。""" - with app.app_context(): - application, executor, _user, admin = _seed_user_access_rows() - admin_token = issue_local_access_token(admin) - executor_id = executor.id - application_id = application.id - - public_response = client.get('/api/agents/public') - assert public_response.status_code == 200 - assert {row['id'] for row in public_response.get_json()} == {application_id} - - detail_response = client.get( - f'/api/user/agents/{executor_id}', - headers={'Authorization': f'Bearer {admin_token}'}, - ) - assert detail_response.status_code == 403 - assert detail_response.get_json()['error']['code'] == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN' - - -def test_internal_executor_is_hidden_from_user_permission_serialization(app): - """历史脏授权关系不能返回权限矩阵或再次通过用户访问校验。""" - with app.app_context(): - application, executor, user, admin = _seed_user_access_rows() - - assert serialize_admin_user(user)['agent_ids'] == [application.id] - with pytest.raises(ForbiddenError) as user_error: - require_user_application_access(executor, user) - with pytest.raises(ForbiddenError) as admin_error: - require_user_application_access(executor, admin) - - assert user_error.value.code == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN' - assert admin_error.value.code == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN' - diff --git a/backend/tests/test_internal_executor_user_links_migration.py b/backend/tests/test_internal_executor_user_links_migration.py deleted file mode 100644 index a7c1c735..00000000 --- a/backend/tests/test_internal_executor_user_links_migration.py +++ /dev/null @@ -1,104 +0,0 @@ -""" -用途:验证内部执行器用户侧历史关系清理迁移的数据边界与幂等性。 -依赖:Alembic Operations、SQLite 临时数据库。 -""" - -import importlib - -import sqlalchemy as sa -from alembic.migration import MigrationContext -from alembic.operations import Operations - - -def test_internal_executor_user_links_cleanup_is_complete_and_idempotent(): - """迁移只清理 internal 用户关系,并保留 workspace 关系与历史权限申请。""" - engine = sa.create_engine('sqlite:///:memory:') - metadata = sa.MetaData() - agents = sa.Table( - 'agents', metadata, - sa.Column('id', sa.Integer, primary_key=True), - sa.Column('exposure_mode', sa.String(20), nullable=False), - ) - users = sa.Table( - 'users', metadata, - sa.Column('id', sa.Integer, primary_key=True), - sa.Column('default_agent_id', sa.Integer, nullable=True), - ) - permissions = sa.Table( - 'user_agent_permissions', metadata, - sa.Column('user_id', sa.Integer, primary_key=True), - sa.Column('agent_id', sa.Integer, primary_key=True), - ) - favorites = sa.Table( - 'user_favorite_agents', metadata, - sa.Column('user_id', sa.Integer, primary_key=True), - sa.Column('agent_id', sa.Integer, primary_key=True), - ) - defaults = sa.Table( - 'user_default_agents', metadata, - sa.Column('id', sa.Integer, primary_key=True), - sa.Column('user_id', sa.Integer, nullable=False), - sa.Column('agent_id', sa.Integer, nullable=False), - ) - requests = sa.Table( - 'permission_requests', metadata, - sa.Column('id', sa.Integer, primary_key=True), - sa.Column('agent_id', sa.Integer, nullable=False), - sa.Column('status', sa.String(20), nullable=False), - sa.Column('reviewed_at', sa.DateTime, nullable=True), - ) - metadata.create_all(engine) - - migration = importlib.import_module( - 'migrations.versions.a62b3c4d5e6f_remove_internal_executor_user_links' - ) - with engine.begin() as connection: - connection.execute(agents.insert(), [ - {'id': 1, 'exposure_mode': 'workspace'}, - {'id': 2, 'exposure_mode': 'internal'}, - ]) - connection.execute(users.insert(), [ - {'id': 10, 'default_agent_id': 1}, - {'id': 11, 'default_agent_id': 2}, - ]) - for table in (permissions, favorites): - connection.execute(table.insert(), [ - {'user_id': 10, 'agent_id': 1}, - {'user_id': 11, 'agent_id': 2}, - ]) - connection.execute(defaults.insert(), [ - {'id': 100, 'user_id': 10, 'agent_id': 1}, - {'id': 101, 'user_id': 11, 'agent_id': 2}, - ]) - connection.execute(requests.insert(), [ - {'id': 200, 'agent_id': 1, 'status': 'pending'}, - {'id': 201, 'agent_id': 2, 'status': 'pending'}, - {'id': 202, 'agent_id': 2, 'status': 'approved'}, - ]) - - original_op = migration.op - migration.op = Operations(MigrationContext.configure(connection)) - try: - migration.upgrade() - migration.upgrade() - finally: - migration.op = original_op - - assert connection.execute(sa.select(permissions)).mappings().all() == [ - {'user_id': 10, 'agent_id': 1} - ] - assert connection.execute(sa.select(favorites)).mappings().all() == [ - {'user_id': 10, 'agent_id': 1} - ] - assert connection.execute(sa.select(defaults)).mappings().all() == [ - {'id': 100, 'user_id': 10, 'agent_id': 1} - ] - user_rows = {row['id']: row for row in connection.execute(sa.select(users)).mappings()} - assert user_rows[10]['default_agent_id'] == 1 - assert user_rows[11]['default_agent_id'] is None - request_rows = {row['id']: row for row in connection.execute(sa.select(requests)).mappings()} - assert request_rows[200]['status'] == 'pending' - assert request_rows[201]['status'] == 'rejected' - assert request_rows[201]['reviewed_at'] is not None - assert request_rows[202]['status'] == 'approved' - diff --git a/backend/tests/test_order_extraction_pdf_po_split.py b/backend/tests/test_order_extraction_pdf_po_split.py index 6f726b74..b9a86f17 100644 --- a/backend/tests/test_order_extraction_pdf_po_split.py +++ b/backend/tests/test_order_extraction_pdf_po_split.py @@ -1,7 +1,7 @@ -"""验证已批准 PDF 模板的多 PO 拆分与严格拒识边界。 +"""验证已批准 PDF 模板的一单一 PO 约束与严格拒识边界。 依赖:确定性 Profile 订单构建器。 -逻辑:只有每行携带唯一 PO 证据时拆分;文档级多 PO 绝不猜测行归属。 +逻辑:一份 PDF 正常只允许一个 PO;检测到多个 PO 时必须整体拒识。 """ from __future__ import annotations @@ -27,15 +27,14 @@ def _row(po: str, part: str) -> dict: ]} -def test_approved_pdf_splits_explicit_line_pos_into_independent_orders(): - """同一 PDF 的两条明细各有 PO 时,必须生成两份独立订单。""" +def test_approved_pdf_rejects_multiple_pos_in_one_pdf(): + """同一 PDF 的两条明细各有 PO 时,必须整体拒识而不是拆成多单。""" orders, reason = _build_approved_profile_order_result( unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA, definition=DEFINITION, table={'rows': [_row('PO-1', 'P-1'), _row('PO-2', 'P-2')]}, ) - assert reason is None - assert len(orders or []) == 2 - assert [item['header_fields'][0]['observations'][0]['value'] for item in orders or []] == ['PO-1', 'PO-2'] + assert orders is None + assert reason == 'multiple_po_detected' def test_approved_pdf_keeps_one_order_when_only_one_po_is_proven(): diff --git a/backend/tests/test_order_extraction_progress_facts_migration.py b/backend/tests/test_order_extraction_progress_facts_migration.py new file mode 100644 index 00000000..600069da --- /dev/null +++ b/backend/tests/test_order_extraction_progress_facts_migration.py @@ -0,0 +1,102 @@ +"""验证订单解析确定性进度事实迁移可完整 upgrade/downgrade。 + +依赖:Alembic Operations、SQLite 内存数据库、0ab45c6d7e8f 迁移。 +逻辑:创建最小前置 Run/Unit/Job 结构,检查新状态约束与事件表字段,再验证受控回滚。 +""" + +from __future__ import annotations + +import importlib + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def _pre_migration_schema(engine: sa.Engine) -> None: + metadata = sa.MetaData() + sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table('agents', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table('jobs', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table( + 'shipping_order_extraction_runs', + metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('owner_agent_id', sa.Integer(), nullable=False), + sa.Column('conversation_id', sa.String(100), nullable=False), + sa.Column('status', sa.String(32), nullable=False), + ) + sa.Table( + 'shipping_order_extraction_units', + metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('plan_id', sa.Integer(), nullable=False), + sa.Column('intake_id', sa.Integer(), nullable=False), + sa.Column('document_id', sa.Integer(), nullable=False), + sa.Column('status', sa.String(32), nullable=False), + ) + sa.Table( + 'shipping_order_extraction_progress_events', + metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('run_id', sa.Integer(), nullable=False), + sa.Column('workflow_run_id', sa.String(128)), + sa.Column('node_execution_id', sa.String(128)), + sa.Column('event_type', sa.String(64), nullable=False), + sa.Column('node_type', sa.String(64)), + sa.Column('stage_code', sa.String(64)), + sa.Column('event_status', sa.String(32)), + sa.Column('provider_occurred_at', sa.DateTime()), + sa.Column('received_at', sa.DateTime(), nullable=False), + sa.Column('details_json', sa.JSON()), + sa.Column('idempotency_key', sa.String(128), nullable=False), + sa.Column('mapping_version', sa.String(32)), + sa.Column('expires_at', sa.DateTime()), + sa.Column('created_at', sa.DateTime(), nullable=False), + ) + metadata.create_all(engine) + + +def test_order_extraction_progress_facts_migration_round_trip(): + migration = importlib.import_module( + 'migrations.versions.0ab45c6d7e8f_rebuild_order_extraction_progress_facts' + ) + engine = sa.create_engine('sqlite:///:memory:') + _pre_migration_schema(engine) + + with engine.begin() as connection: + original_op = migration.op + migration.op = Operations(MigrationContext.configure(connection)) + try: + migration.upgrade() + inspector = sa.inspect(connection) + unit_columns = { + column['name'] for column in inspector.get_columns('shipping_order_extraction_units') + } + assert {'reason_code', 'summary_json', 'last_activity_at'} <= unit_columns + + event_columns = { + column['name'] for column in inspector.get_columns('shipping_order_extraction_progress_events') + } + assert { + 'run_id', 'unit_id', 'document_id', 'sequence_no', 'visibility', + 'event_code', 'status', 'occurred_at', 'reason_code', 'summary_json', + } <= event_columns + assert { + 'workflow_run_id', 'node_execution_id', 'event_type', 'node_type', + 'stage_code', 'event_status', 'provider_occurred_at', 'details_json', + }.isdisjoint(event_columns) + + migration.downgrade() + inspector = sa.inspect(connection) + reverted_event_columns = { + column['name'] for column in inspector.get_columns('shipping_order_extraction_progress_events') + } + assert {'workflow_run_id', 'node_execution_id', 'event_type', 'stage_code'} <= reverted_event_columns + reverted_unit_columns = { + column['name'] for column in inspector.get_columns('shipping_order_extraction_units') + } + assert {'reason_code', 'summary_json', 'last_activity_at'}.isdisjoint(reverted_unit_columns) + finally: + migration.op = original_op diff --git a/backend/tests/test_order_extraction_request_snapshot_migration.py b/backend/tests/test_order_extraction_request_snapshot_migration.py new file mode 100644 index 00000000..3d3ac57d --- /dev/null +++ b/backend/tests/test_order_extraction_request_snapshot_migration.py @@ -0,0 +1,47 @@ +"""验证订单抽取请求快照迁移的升级与回退契约。""" + +from __future__ import annotations + +import importlib + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def test_order_extraction_request_snapshot_migration_round_trip(): + """发送时审计锚点字段必须独立升级回退,不能与可变执行快照混淆。""" + migration = importlib.import_module( + 'migrations.versions.2d3e4f5a6b7c_add_order_extraction_request_snapshot' + ) + engine = sa.create_engine('sqlite://') + metadata = sa.MetaData() + sa.Table( + 'shipping_order_extraction_runs', + metadata, + sa.Column('id', sa.Integer, primary_key=True), + sa.Column('input_snapshot_hash', sa.String(length=64), nullable=False), + sa.Column('input_snapshot_json', sa.JSON(), nullable=False), + ) + metadata.create_all(engine) + + with engine.begin() as connection: + original_op = migration.op + migration.op = Operations(MigrationContext.configure(connection)) + try: + migration.upgrade() + columns = { + item['name'] + for item in sa.inspect(connection).get_columns('shipping_order_extraction_runs') + } + assert {'request_snapshot_hash', 'request_snapshot_json'} <= columns + + migration.downgrade() + downgraded = { + item['name'] + for item in sa.inspect(connection).get_columns('shipping_order_extraction_runs') + } + assert 'request_snapshot_hash' not in downgraded + assert 'request_snapshot_json' not in downgraded + finally: + migration.op = original_op diff --git a/backend/tests/test_profile_auto_freeze_scope_migration.py b/backend/tests/test_profile_auto_freeze_scope_migration.py new file mode 100644 index 00000000..2c173c4b --- /dev/null +++ b/backend/tests/test_profile_auto_freeze_scope_migration.py @@ -0,0 +1,42 @@ +"""验证自动冻结资格范围迁移的升级与回退契约。""" + +from __future__ import annotations + +import importlib + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def test_profile_auto_freeze_scope_migration_contract(): + """资格范围字段必须可升级回退,且不依赖业务表全量存在。""" + base = importlib.import_module('migrations.versions.0aa34b5c6d7e_add_profile_auto_freeze_qualifications') + migration = importlib.import_module('migrations.versions.0ce67f8a9b01_add_auto_freeze_scope_to_profile_qualification') + engine = sa.create_engine('sqlite://') + metadata = sa.MetaData() + for name in ('shipping_order_document_profiles', 'shipping_order_schema_versions', 'shipping_document_profile_test_suites', 'users'): + sa.Table(name, metadata, sa.Column('id', sa.Integer, primary_key=True)) + metadata.create_all(engine) + with engine.begin() as connection: + base.op = Operations(MigrationContext.configure(connection)) + base.upgrade() + migration.op = Operations(MigrationContext.configure(connection)) + migration.upgrade() + columns = { + item['name'] + for item in sa.inspect(connection).get_columns('shipping_document_profile_auto_freeze_qualifications') + } + assert { + 'customer_ids_json', + 'business_scenarios_json', + 'requires_customer_confirmation', + 'scope_updated_by_id', + 'scope_updated_at', + } <= columns + migration.downgrade() + columns_after_downgrade = { + item['name'] + for item in sa.inspect(connection).get_columns('shipping_document_profile_auto_freeze_qualifications') + } + assert 'customer_ids_json' not in columns_after_downgrade diff --git a/backend/tests/test_shipping_attachment_selection.py b/backend/tests/test_shipping_attachment_selection.py new file mode 100644 index 00000000..71590532 --- /dev/null +++ b/backend/tests/test_shipping_attachment_selection.py @@ -0,0 +1,641 @@ +""" +backend/tests/test_shipping_attachment_selection.py + +用途:验证发送阶段附件选择计划只依赖快览事实,并能把计划摘要投影到 Run 响应。 +依赖:pytest、纯函数 attachment_selection、订单抽取 Run 序列化服务。 +逻辑:覆盖评分/排除/去重/首轮预算,以及 Run API 的 selection_plan 摘要输出。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +from app.services.shipping_notice.attachment_selection import build_attachment_selection_snapshot +from app.services.shipping_notice.order_extraction_plan import ( + _snapshot_documents, + transition_order_extraction_unit, +) +from app.services.shipping_notice.order_extraction_runtime_snapshot import ( + resolve_unit_runtime_snapshot, +) +from app.services.shipping_notice.order_extraction_snapshot_selection import ( + has_attachment_catalog, + has_selected_attachments, + selected_attachment_keys_by_intake, + should_include_snapshot_document, +) +from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run +from app.services.shipping_notice.order_extraction_workspace_projection import ( + serialize_workspace_run_documents, +) + + +def _preview_intake(intake_no: str, attachments: list[dict], *, subject: str = '', body_text: str = ''): + """构造最小快览 Intake 假对象,避免测试选择计划时依赖数据库。""" + return SimpleNamespace( + intake_no=intake_no, + structured_result_json={ + 'email': { + 'subject': subject, + 'body_text': body_text, + 'body_html_tables': [], + }, + 'attachments': attachments, + }, + ) + + +def test_attachment_selection_snapshot_prefers_po_hints_and_skips_risky_duplicates(): + """首轮仅选 2 个高相关附件;后续候选进入未来批次,风险附件和重复哈希必须稳定跳过。""" + snapshot = build_attachment_selection_snapshot(intakes=[ + _preview_intake( + 'SNI-A', + [ + { + 'attachment_key': 'po-1.pdf', + 'filename': 'PO_451883815A.pdf', + 'mime_type': 'application/pdf', + 'size': 48000, + 'content_hash': 'a' * 64, + 'ready_for_extraction': True, + 'catalog_reason': 'ready_for_extraction', + }, + { + 'attachment_key': 'logo.png', + 'filename': 'customer-logo.png', + 'mime_type': 'image/png', + 'size': 4096, + 'content_hash': 'b' * 64, + 'ready_for_extraction': False, + 'is_inline_resource': True, + 'catalog_reason': 'inline_resource', + }, + { + 'attachment_key': 'archive.zip', + 'filename': 'orders.zip', + 'mime_type': 'application/zip', + 'size': 120000, + 'content_hash': 'c' * 64, + 'ready_for_extraction': False, + 'catalog_reason': 'archive', + }, + ], + subject='PO 451883815A and booking details', + ), + _preview_intake( + 'SNI-B', + [ + { + 'attachment_key': 'po-1-duplicate.pdf', + 'filename': 'PO_451883815A_copy.pdf', + 'mime_type': 'application/pdf', + 'size': 48000, + 'content_hash': 'a' * 64, + 'ready_for_extraction': True, + 'catalog_reason': 'ready_for_extraction', + }, + { + 'attachment_key': 'booking.xlsx', + 'filename': 'booking_451883816.xlsx', + 'mime_type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'size': 56000, + 'content_hash': 'd' * 64, + 'ready_for_extraction': True, + 'catalog_reason': 'ready_for_extraction', + }, + { + 'attachment_key': 'third.docx', + 'filename': 'order_notes.docx', + 'mime_type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'size': 42000, + 'content_hash': 'e' * 64, + 'ready_for_extraction': True, + 'catalog_reason': 'ready_for_extraction', + }, + ], + body_text='Please process PO 451883816 first.', + ), + ]) + + assert snapshot['selection_version'] == 'shipping_notice_attachment_selection.v1' + # 内嵌签名资源不属于业务附件,不计入选择计划数量。 + assert snapshot['total_attachment_count'] == 5 + assert snapshot['eligible_attachment_count'] == 3 + assert snapshot['selected_attachment_count'] == 2 + assert snapshot['planned_attachment_count'] == 3 + assert snapshot['pending_expansion_attachment_count'] == 1 + assert snapshot['pending_expansion_batches'] == {'2': 1} + selected = [item for item in snapshot['items'] if item['selected']] + assert [item['filename'] for item in selected] == ['PO_451883815A.pdf', 'booking_451883816.xlsx'] + + by_name = {item['filename']: item for item in snapshot['items']} + assert by_name['PO_451883815A_copy.pdf']['skip_reason_codes'] == ['duplicate_content_hash'] + assert 'customer-logo.png' not in by_name + assert by_name['orders.zip']['skip_reason_codes'] == ['catalog_reason:archive'] + assert by_name['order_notes.docx']['skip_reason_codes'] == [] + assert by_name['order_notes.docx']['planned_selection_batch'] == 2 + assert by_name['PO_451883815A.pdf']['group_key'] == '451883815A' + + +def test_attachment_selection_snapshot_stops_at_total_byte_budget(): + """累计深度解析字节超预算时,后续附件必须标记为预算停止而非静默扩批。""" + snapshot = build_attachment_selection_snapshot( + intakes=[_preview_intake('SNI-BYTE', [ + { + 'attachment_key': 'first.pdf', 'filename': 'first.pdf', 'mime_type': 'application/pdf', + 'size': 20, 'content_hash': 'a' * 64, 'ready_for_extraction': True, + 'catalog_reason': 'ready_for_extraction', + }, + { + 'attachment_key': 'second.pdf', 'filename': 'second.pdf', 'mime_type': 'application/pdf', + 'size': 20, 'content_hash': 'b' * 64, 'ready_for_extraction': True, + 'catalog_reason': 'ready_for_extraction', + }, + ])], + max_total_bytes=30, + ) + + by_name = {item['filename']: item for item in snapshot['items']} + assert snapshot['planned_total_bytes'] == 20 + assert by_name['first.pdf']['selected'] is True + assert by_name['second.pdf']['skip_reason_codes'] == ['budget_total_bytes'] + + +def test_attachment_selection_snapshot_excludes_inline_resources_from_counts(): + """邮件签名图不属于用户业务附件,不能占用识别计划的附件数量或预算。""" + snapshot = build_attachment_selection_snapshot(intakes=[ + _preview_intake( + 'SNI-A', + [ + { + 'attachment_key': 'signature.gif', + 'filename': 'signature.gif', + 'mime_type': 'image/gif', + 'size': 1024, + 'content_hash': 'a' * 64, + 'ready_for_extraction': False, + 'is_inline_resource': True, + 'catalog_reason': 'inline_resource', + }, + { + 'attachment_key': 'po-1.pdf', + 'filename': 'PO_4518838152.pdf', + 'mime_type': 'application/pdf', + 'size': 48000, + 'content_hash': 'b' * 64, + 'ready_for_extraction': True, + 'catalog_reason': 'ready_for_extraction', + }, + { + 'attachment_key': 'po-2.pdf', + 'filename': 'PO_4518838154.pdf', + 'mime_type': 'application/pdf', + 'size': 48000, + 'content_hash': 'c' * 64, + 'ready_for_extraction': True, + 'catalog_reason': 'ready_for_extraction', + }, + ], + ), + ]) + + assert snapshot['total_attachment_count'] == 2 + assert snapshot['eligible_attachment_count'] == 2 + assert snapshot['selected_attachment_count'] == 2 + assert [item['filename'] for item in snapshot['items']] == [ + 'PO_4518838152.pdf', 'PO_4518838154.pdf', + ] + + +def test_serialize_order_extraction_run_includes_selection_plan_summary(monkeypatch): + """Run 用户态响应应暴露计划摘要计数,但不能泄露具体正文或打分细节。""" + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workspace_projection.serialize_workspace_run', + lambda _run: { + 'summary': { + 'total_documents': 0, + 'pending_documents': 0, + 'processing_documents': 0, + 'completed_documents': 0, + 'review_required_documents': 0, + 'failed_documents': 0, + 'candidate_count': 0, + }, + 'current_activity': None, + 'available_actions': ['view_details'], + }, + ) + run = SimpleNamespace( + run_no='SNER-SELECTION', + owner_agent_id=1, + conversation_id='conv-selection', + status='queued', + phase='queued', + schema_version_id=1, + attempt_count=0, + reparse_source=None, + superseding_run=None, + reparse_reason=None, + superseded_at=None, + result_json=None, + error_code=None, + created_at=None, + updated_at=None, + started_at=None, + finished_at=None, + extraction_plan=SimpleNamespace(units=[ + SimpleNamespace( + selection_batch=1, + status='candidate_ready', + reason_code=None, + result_json={ + 'orders': [{ + 'lines': [{'fields': []}], + 'conflicts': [{'reason': 'supplement_relation_ambiguous'}], + }], + }, + retry_status='running', + technical_failure_reason_code=None, + ), + SimpleNamespace( + selection_batch=1, + status='failed', + reason_code=None, + result_json=None, + retry_status='failed', + technical_failure_reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT', + ), + SimpleNamespace( + selection_batch=2, + status='review_required', + reason_code='required_field_missing', + result_json={'orders': []}, + retry_status='review_required', + technical_failure_reason_code=None, + ), + ]), + input_snapshot_json={ + 'schema': { + 'version': 1, + 'checksum': 'a' * 64, + 'definition': { + 'fields': [{'field_code': 'reservation_id', 'field_id': 'reservation-id'}], + }, + }, + 'intakes': [{'intake_no': 'SNI-1'}], + 'attachment_selection': { + 'selection_version': 'shipping_notice_attachment_selection.v1', + 'max_initial_attachments': 2, + 'max_initial_concurrency': 2, + 'expansion_batch_size': 2, + 'max_total_attachments': 6, + 'total_attachment_count': 5, + 'eligible_attachment_count': 3, + 'selected_attachment_count': 2, + 'planned_attachment_count': 3, + 'pending_expansion_attachment_count': 1, + 'pending_expansion_batches': {'2': 1}, + 'group_count': 2, + 'items': [ + {'selected': True, 'selection_batch': 1, 'filename': 'must-not-leak.pdf', 'score': 999}, + {'selected': True, 'selection_batch': 1}, + {'selected': False, 'planned_selection_batch': 2, 'skip_reason_codes': []}, + {'selected': False, 'skip_reason_codes': ['duplicate_content_hash']}, + {'selected': False, 'skip_reason_codes': ['catalog_reason:inline_resource']}, + ], + }, + }, + ) + + payload = serialize_order_extraction_run(run) + + assert payload['selection_plan'] == { + 'selection_version': 'shipping_notice_attachment_selection.v1', + 'max_initial_attachments': 2, + 'max_initial_concurrency': 2, + 'expansion_batch_size': 2, + 'max_total_attachments': 6, + 'max_total_bytes': 0, + 'max_runtime_seconds': 0, + 'input_total_bytes': 0, + 'planned_total_bytes': 0, + 'total_attachment_count': 5, + 'eligible_attachment_count': 3, + 'selected_attachment_count': 2, + 'planned_attachment_count': 3, + 'pending_expansion_attachment_count': 1, + 'pending_expansion_batches': {'2': 1}, + 'skipped_attachment_count': 2, + 'duplicate_attachment_count': 1, + 'budget_limited_attachment_count': 0, + 'group_count': 2, + } + assert payload['unit_summary'] == { + 'total_units': 3, + 'selected_units': 3, + 'retrying_units': 1, + 'pending_retry_units': 0, + 'failed_units': 1, + 'review_required_units': 1, + 'succeeded_units': 0, + 'selection_batches': {'1': 2, '2': 1}, + 'review_required_reason_codes': ['required_field_missing'], + 'expansion_trigger_reason_codes': [ + 'missing_reservation_id', + 'required_field_missing', + 'supplement_relation_ambiguous', + ], + 'technical_failure_reason_codes': ['SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT'], + } + assert 'must-not-leak' not in str(payload) + + +def test_snapshot_selection_helpers_keep_only_selected_attachment_documents(): + """Run snapshot 应只包含本次计划选中的附件,正文补充事实必须保留。""" + selection_snapshot = { + 'total_attachment_count': 4, + 'selected_attachment_count': 2, + 'items': [ + {'intake_no': 'SNI-A', 'attachment_key': 'po-1.pdf', 'selected': True}, + {'intake_no': 'SNI-A', 'attachment_key': 'copy.pdf', 'selected': False}, + {'intake_no': 'SNI-B', 'attachment_key': 'booking.xlsx', 'selected': True}, + ], + } + + assert has_attachment_catalog(selection_snapshot) is True + assert has_selected_attachments(selection_snapshot) is True + assert selected_attachment_keys_by_intake(selection_snapshot) == { + 'SNI-A': {'po-1.pdf'}, + 'SNI-B': {'booking.xlsx'}, + } + assert should_include_snapshot_document( + selection_snapshot=selection_snapshot, + intake_no='SNI-A', + document_type='email_body', + attachment_key='body', + ) is True + assert should_include_snapshot_document( + selection_snapshot=selection_snapshot, + intake_no='SNI-A', + document_type='attachment', + attachment_key='po-1.pdf', + ) is True + assert should_include_snapshot_document( + selection_snapshot=selection_snapshot, + intake_no='SNI-A', + document_type='attachment', + attachment_key='copy.pdf', + ) is False + + +def test_snapshot_selection_helpers_fall_back_to_all_documents_for_non_catalog_inputs(): + """普通单文件没有附件目录时,不应误把唯一文档过滤掉。""" + selection_snapshot = {'total_attachment_count': 0, 'selected_attachment_count': 0, 'items': []} + + assert has_attachment_catalog(selection_snapshot) is False + assert has_selected_attachments(selection_snapshot) is False + assert should_include_snapshot_document( + selection_snapshot=selection_snapshot, + intake_no='SNI-FILE', + document_type='attachment', + attachment_key='file', + ) is True + + +def test_snapshot_documents_include_selection_metadata(): + """计划编译应把选择批次、原因码、分组键和预算摘要映射到附件单元。""" + run = SimpleNamespace( + input_snapshot_json={ + 'attachment_selection': { + 'max_initial_attachments': 2, + 'max_initial_concurrency': 2, + 'items': [ + { + 'intake_no': 'SNI-A', + 'attachment_key': 'po-1.pdf', + 'selected': True, + 'selection_batch': 1, + 'score_reasons': ['type_pdf', 'po_hint_detected'], + 'group_key': '451883815A', + }, + { + 'intake_no': 'SNI-A', + 'attachment_key': 'copy.pdf', + 'selected': False, + 'score_reasons': ['filename_copy_hint'], + 'group_key': '451883815A', + }, + ], + }, + 'intakes': [{ + 'intake_id': 11, + 'intake_no': 'SNI-A', + 'documents': [ + { + 'document_id': 101, + 'document_type': 'attachment', + 'attachment_key': 'po-1.pdf', + 'content_hash': 'a' * 64, + }, + { + 'document_id': 102, + 'document_type': 'attachment', + 'attachment_key': 'copy.pdf', + 'content_hash': 'b' * 64, + }, + ], + }], + }, + ) + + documents = _snapshot_documents(run) + + assert documents[0]['selection_batch'] == 1 + assert documents[0]['selection_reason_codes'] == ['type_pdf', 'po_hint_detected'] + assert documents[0]['group_key'] == '451883815A' + assert documents[0]['budget_cost'] == { + 'initial_attachment_budget': 2, + 'initial_concurrency_budget': 2, + 'expansion_batch_size': 0, + 'max_total_attachments': 0, + 'selected_in_batch': 1, + } + assert documents[1]['selection_batch'] is None + assert documents[1]['selection_reason_codes'] == ['filename_copy_hint'] + + +def test_transition_order_extraction_unit_tracks_retry_and_technical_failure(monkeypatch): + """附件单元失败与重试时应更新 retry_status 和 technical_failure_reason_code。""" + audit_calls: list[dict] = [] + monkeypatch.setattr( + 'app.services.shipping_notice.audit_service.append_shipping_audit_event', + lambda **kwargs: audit_calls.append(kwargs), + ) + plan = SimpleNamespace(units=[], run=SimpleNamespace(run_no='SNER-PLAN')) + unit = SimpleNamespace( + id=1, + status='pending', + attempt_count=0, + reason_code=None, + summary_json=None, + result_json=None, + error_code=None, + error_message=None, + last_activity_at=None, + started_at=None, + finished_at=None, + retry_status='not_started', + technical_failure_reason_code=None, + plan=plan, + ) + plan.units = [unit] + + transition_order_extraction_unit(unit, target_status='routing') + assert unit.retry_status == 'running' + assert unit.technical_failure_reason_code is None + + transition_order_extraction_unit( + unit, + target_status='failed', + error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT', + error_message='timeout', + ) + assert unit.retry_status == 'failed' + assert unit.technical_failure_reason_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT' + + transition_order_extraction_unit(unit, target_status='pending') + assert unit.retry_status == 'pending_retry' + assert unit.technical_failure_reason_code is None + assert audit_calls + + +def test_runtime_snapshot_keeps_frozen_ready_layout_without_db_lookup(monkeypatch): + """冻结快照已有 ready layout 时,Worker 不应回读当前 Document。""" + run = SimpleNamespace( + input_snapshot_json={ + 'intakes': [{ + 'intake_id': 11, + 'documents': [{ + 'document_id': 101, + 'layout_snapshot': {'status': 'ready', 'layout_candidate': {'pages': []}}, + 'layout_schema_candidates': [{'mapping_status': 'accepted'}], + }], + }], + }, + ) + unit = SimpleNamespace(intake_id=11, document_id=101) + monkeypatch.setattr('app.services.shipping_notice.order_extraction_runtime_snapshot.db.session.get', lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('should not query db'))) + + intake, document = resolve_unit_runtime_snapshot(run, unit) + + assert intake['intake_id'] == 11 + assert document['layout_snapshot']['status'] == 'ready' + assert document['layout_schema_candidates'] == [{'mapping_status': 'accepted'}] + + +def test_runtime_snapshot_hydrates_current_ready_layout_when_snapshot_is_stale(monkeypatch): + """Run 先创建后布局就绪时,Worker 应补读当前 ready layout 和 schema candidates。""" + run = SimpleNamespace( + input_snapshot_json={ + 'schema': {'definition': {'fields': []}}, + 'intakes': [{ + 'intake_id': 11, + 'documents': [{ + 'document_id': 101, + 'layout_snapshot': {'status': 'queued'}, + 'layout_schema_candidates': [], + }], + }], + }, + ) + unit = SimpleNamespace(intake_id=11, document_id=101) + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_runtime_snapshot.db.session.get', + lambda model, document_id: SimpleNamespace(id=document_id), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_runtime_snapshot.current_layout_snapshot', + lambda document: {'status': 'ready', 'layout_candidate': {'pages': [{'page_no': 1, 'tables': []}]}}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_runtime_snapshot.map_layout_document_to_schema', + lambda layout_candidate, contract: [{'mapping_status': 'accepted', 'issues': []}], + ) + + _intake, document = resolve_unit_runtime_snapshot(run, unit) + + assert document['layout_snapshot']['status'] == 'ready' + assert document['layout_schema_candidates'] == [{'mapping_status': 'accepted', 'issues': []}] + + +def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch): + """工作台文档详情应直接暴露单元选择、预算和失败事实。""" + run = SimpleNamespace( + id=1, + input_snapshot_json={ + 'schema': {'definition': {'fields': []}}, + 'intakes': [{ + 'intake_id': 11, + 'documents': [{ + 'document_id': 101, + 'document_type': 'attachment', + 'filename': 'po-1.pdf', + }], + }], + }, + extraction_plan=SimpleNamespace(units=[SimpleNamespace( + id=7, + document_id=101, + status='failed', + reason_code=None, + selection_batch=1, + group_key='451883815A', + retry_status='failed', + technical_failure_reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT', + budget_cost_json={ + 'initial_attachment_budget': 2, + 'initial_concurrency_budget': 2, + 'selected_in_batch': 1, + }, + result_json={}, + )]), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workspace_projection._latest_route_decisions', + lambda _run: {}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workspace_projection._latest_progress_events', + lambda _run: ({}, None), + ) + + items = serialize_workspace_run_documents(run) + + assert items == [{ + 'unit_id': 7, + 'document_id': 101, + 'file_name': 'po-1.pdf', + 'status': 'failed', + 'selection_batch': 1, + 'group_key': '451883815A', + 'retry_status': 'failed', + 'technical_failure_reason_code': 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT', + 'budget_cost': { + 'initial_attachment_budget': 2, + 'initial_concurrency_budget': 2, + 'selected_in_batch': 1, + }, + 'po_number': None, + 'line_count': 0, + 'profile': None, + 'email_supplement': { + 'status': 'none', + 'relation_codes': [], + 'conflict_count': 0, + 'reservation_id_status': 'unavailable', + 'source_type_status': 'unavailable', + }, + 'reason_code': 'technical_failure', + 'review_details': [], + 'available_actions': [], + }] diff --git a/backend/tests/test_shipping_document_profile_quality.py b/backend/tests/test_shipping_document_profile_quality.py index e619b21d..65d36d70 100644 --- a/backend/tests/test_shipping_document_profile_quality.py +++ b/backend/tests/test_shipping_document_profile_quality.py @@ -17,6 +17,7 @@ from app.models import ( FileAsset, ShippingNoticeDocument, ShippingNoticeIntake, + ShippingCustomer, ShippingOrderDocumentProfile, ShippingOrderDocumentProfileAudit, ShippingDocumentProfileTestSuite, @@ -136,8 +137,8 @@ def _publishable_v2_draft(profile: ShippingOrderDocumentProfile) -> None: } -def test_profile_blind_test_approval_does_not_enable_auto_freeze(app): - """关键断言:盲测批准与自动冻结资格独立,首版仍只能人工确认。""" +def test_profile_blind_test_approval_enables_current_auto_freeze_qualification(app): + """关键断言:盲测批准应升级当前模板版本资格,避免审批结果无法生效。""" with app.app_context(): profile, user, documents = _published_profile_with_samples() suite = quality.create_suite(profile_id=profile.id, actor_id=user.id) @@ -156,7 +157,12 @@ def test_profile_blind_test_approval_does_not_enable_auto_freeze(app): assert executed['latest_run']['status'] == 'passed' approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id) assert approved['status'] == 'approved' - assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum) + assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum) + qualification = quality.qualification_summary(profile) + assert qualification['status'] == 'auto_freeze_approved' + assert qualification['quality_suite_id'] == suite['id'] + # 盲测只批准解析质量,未配置范围时仍要求人工确认。 + assert qualification['requires_customer_confirmation'] is True with pytest.raises(Exception) as immutable: quality.add_sample( suite_id=suite['id'], document_id=documents[0].id, table_id='other', @@ -308,6 +314,41 @@ def test_profile_auto_freeze_qualification_can_be_suspended_independently(app): assert published['auto_freeze_qualification']['status'] == 'manual_confirmation' +def test_profile_auto_freeze_scope_can_be_configured_independently(app): + """关键断言:客户/业务场景授权范围可独立配置,并写入模板审计摘要。""" + from app.services.shipping_notice import order_document_profile_service as profiles + + with app.app_context(): + profile, user, _documents = _published_profile_with_samples() + _publishable_v2_draft(profile) + db.session.commit() + published = profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version) + customer = ShippingCustomer(standard_name='Scope Customer', short_code='SCOP') + db.session.add(customer) + db.session.commit() + + qualification = quality.configure_auto_freeze_qualification_scope( + profile_id=profile.id, + actor_id=user.id, + customer_ids=[customer.id], + business_scenarios=['shipping_notice_order'], + requires_customer_confirmation=False, + ) + + assert qualification.customer_ids_json == [customer.id] + assert qualification.business_scenarios_json == ['shipping_notice_order'] + assert qualification.requires_customer_confirmation is False + refreshed = profiles.payload(db.session.get(ShippingOrderDocumentProfile, profile.id)) + assert refreshed['auto_freeze_qualification']['customer_scope_configured'] is True + assert refreshed['auto_freeze_qualification']['business_scenario_scope_configured'] is True + assert refreshed['auto_freeze_qualification']['requires_customer_confirmation'] is False + assert published['auto_freeze_qualification']['status'] == 'manual_confirmation' + audit = ShippingOrderDocumentProfileAudit.query.filter_by(profile_id=profile.id).order_by( + ShippingOrderDocumentProfileAudit.id.desc(), + ).first() + assert audit.event_type == 'auto_freeze_scope_configured' + + def test_profile_change_supersedes_stale_draft_suite_and_creates_current_suite(app): """保存模板后必须建立新 checksum 的盲测集,旧草稿真值不得继续阻断或背书。""" with app.app_context(): diff --git a/backend/tests/test_shipping_notice_extract.py b/backend/tests/test_shipping_notice_extract.py index 5a3c3814..0918adea 100644 --- a/backend/tests/test_shipping_notice_extract.py +++ b/backend/tests/test_shipping_notice_extract.py @@ -1,5 +1,6 @@ from email.message import EmailMessage from pathlib import Path +from unittest.mock import patch import pytest @@ -93,6 +94,44 @@ def _minimal_pdf_bytes(marker: str) -> bytes: return bytes(out) +def test_extract_notice_text_preview_only_skips_pdf_loader_and_ocr(tmp_path): + """上传快览只返回普通文件元信息,绝不能同步调用 PDF Loader 或 OCR。""" + from app.services.shipping_notice.notice_upload import extract_notice_text + + path = tmp_path / "order.pdf" + path.write_bytes(_minimal_pdf_bytes("PREVIEW-ONLY")) + with patch('app.services.shipping_notice.notice_upload.loader_pdf.run') as pdf_loader, patch( + 'app.services.shipping_notice.notice_upload.ocr.run', + ) as ocr_loader: + text, meta = extract_notice_text(path, preview_only=True) + + assert text == "" + assert meta == { + 'warnings': [], + 'file_type': 'pdf', + 'content_mode': 'preview', + } + pdf_loader.assert_not_called() + ocr_loader.assert_not_called() + + +def test_extract_notice_text_preview_only_skips_plain_text_read(tmp_path): + """快览对文本文件也只返回目录元信息,不能读取或持久化正文。""" + from app.services.shipping_notice.notice_upload import extract_notice_text + + path = tmp_path / "order.txt" + path.write_text("PO Number: 4510039227", encoding="utf-8") + with patch.object(Path, "read_bytes", side_effect=AssertionError("preview must not read content")): + text, meta = extract_notice_text(path, preview_only=True) + + assert text == "" + assert meta == { + 'warnings': [], + 'file_type': 'txt', + 'content_mode': 'preview', + } + + _TINY_PNG = ( b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01" b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f\x00" @@ -290,6 +329,33 @@ def test_extract_eml_skips_signature_inline_image(tmp_path): assert "--- attachment: signature.png ---" not in text +def test_preview_eml_skips_signature_inline_image_from_attachment_count(tmp_path): + """签名图不计数,但快览和深度解析必须保留一致的业务附件键。""" + from app.services.shipping_notice.notice_upload import extract_notice_text + + raw = _build_eml( + subject="Two POs", + body="Body with two PO attachments.", + attachments=[ + ("order-1.pdf", "application/pdf", _minimal_pdf_bytes("PO-ONE")), + ("order-2.pdf", "application/pdf", _minimal_pdf_bytes("PO-TWO")), + ], + inline_images=[("signature.png", "", _TINY_PNG)], + ) + path = tmp_path / "preview-with-signature.eml" + path.write_bytes(raw) + + _, preview_meta = extract_notice_text(path, eml_attachment_mode="preview") + _, deep_meta = extract_notice_text(path) + + assert preview_meta["attachment_count"] == 2 + assert preview_meta["attachment_registered_count"] == 2 + assert [item["filename"] for item in preview_meta["attachments"]] == ["order-1.pdf", "order-2.pdf"] + assert [item["attachment_key"] for item in preview_meta["attachments"]] == ["att-002", "att-003"] + assert [item["attachment_key"] for item in deep_meta["attachments"]] == ["att-002", "att-003"] + assert any(str(w).startswith("eml_inline_resources_skipped:") for w in preview_meta["warnings"]) + + def test_extract_eml_duplicate_attachments(tmp_path): """同信内重复内容哈希的附件标记 duplicate,不重复抽取。""" from app.services.shipping_notice.notice_upload import extract_notice_text diff --git a/backend/tests/test_shipping_notice_intakes.py b/backend/tests/test_shipping_notice_intakes.py index d7eb1b42..e5a850ea 100644 --- a/backend/tests/test_shipping_notice_intakes.py +++ b/backend/tests/test_shipping_notice_intakes.py @@ -8,6 +8,8 @@ backend/tests/test_shipping_notice_intakes.py from __future__ import annotations +import threading +import time from datetime import datetime from unittest.mock import patch @@ -932,6 +934,186 @@ def _seed_parsed_intake(user_id: int, *, intake_no: str = 'SNI-TEST-0001', hash_ return asset, intake +def test_run_intake_parse_for_pdf_uses_preview_and_creates_no_documents(app, shipping_user, monkeypatch): + """普通文件上传只写快览,深度抽取与 Document 物化必须留给发送阶段。""" + from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + from app.services.shipping_notice.notice_upload import NoticeIntakeResult + + with app.app_context(): + asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PDF-PREVIEW') + asset.original_filename = 'order.pdf' + asset.mime_type = 'application/pdf' + intake.parse_status = 'parsing' + db.session.commit() + calls: list[dict] = [] + + def _preview_result(_asset, **kwargs): + calls.append(kwargs) + return NoticeIntakeResult( + filename='order.pdf', source_type='pdf', source_file_type='application/pdf', + text='', warnings=[], meta={'file_type': 'pdf', 'content_mode': 'preview'}, + content_hash=str(asset.content_hash), file_size=12, status='accepted', saved_path=None, + ) + + monkeypatch.setattr( + 'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset', + _preview_result, + ) + result = run_intake_parse(intake, asset) + + assert result['status'] == 'parsed' + assert calls == [{ + 'eml_attachment_mode': 'preview', 'retain_payloads': False, 'preview_only': True, + }] + assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake.id).count() == 0 + + +def test_materialize_single_file_reextracts_deeply_after_send(app, shipping_user, monkeypatch): + """发送阶段物化普通文件时必须重新走深度抽取,而不是复用上传快览空文本。""" + from app.services.shipping_notice.order_extraction_materialization import ( + ensure_order_extraction_input_documents, + ) + from app.services.shipping_notice.notice_upload import NoticeIntakeResult + + with app.app_context(): + asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PDF-MATERIALIZE') + asset.original_filename = 'order.pdf' + asset.mime_type = 'application/pdf' + db.session.commit() + calls: list[dict] = [] + + def _deep_result(_asset, **kwargs): + calls.append(kwargs) + return NoticeIntakeResult( + filename='order.pdf', source_type='pdf', source_file_type='application/pdf', + text='PO Number: 4510039227\\nSKU-A qty 1', warnings=[], meta={'file_type': 'pdf'}, + content_hash=str(asset.content_hash), file_size=12, status='accepted', saved_path=None, + ) + + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_materialization.extract_notice_from_asset', + _deep_result, + ) + persisted: list[NoticeIntakeResult] = [] + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_materialization.persist_intake_documents', + lambda **kwargs: persisted.append(kwargs['result']) or {'document_count': 1}, + ) + + ensure_order_extraction_input_documents( + intakes=[intake], attachment_selection={}, schema_definition={'fields': []}, + ) + + assert calls == [{'eml_attachment_mode': 'deep'}] + assert len(persisted) == 1 + assert persisted[0].text.startswith('PO Number:') + + +def test_selected_eml_attachments_use_bounded_parallel_deep_extraction(app, shipping_user, monkeypatch): + """首轮附件深度抽取最多并发 2,ORM 持久化仍留在调用线程处理。""" + from app.services.shipping_notice.notice_upload import NoticeIntakeResult + import app.services.shipping_notice.order_extraction_materialization as materialization + + with app.app_context(): + asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PARALLEL-MATERIALIZE') + asset.original_filename = 'orders.eml' + asset.mime_type = 'message/rfc822' + db.session.commit() + active = 0 + peak = 0 + lock = threading.Lock() + + def _preview_result(_asset, **kwargs): + assert kwargs == {'eml_attachment_mode': 'preview', 'retain_payloads': True} + return NoticeIntakeResult( + filename='orders.eml', source_type='email', source_file_type='message/rfc822', + text='mail preview', warnings=[], + meta={'attachments': [ + { + 'attachment_key': f'order-{index}.pdf', 'filename': f'order-{index}.pdf', + 'mime_type': 'application/pdf', '_payload_bytes': f'pdf-{index}'.encode(), + } + for index in range(3) + ]}, + content_hash=str(asset.content_hash), file_size=12, status='accepted', saved_path=None, + ) + + def _deep_extract(*, payload, filename, mime_type, flask_app): + nonlocal active, peak + assert flask_app is app + with lock: + active += 1 + peak = max(peak, active) + time.sleep(0.03) + with lock: + active -= 1 + return f'text:{filename}', {'warnings': []} + + monkeypatch.setattr(materialization, 'extract_notice_from_asset', _preview_result) + monkeypatch.setattr(materialization, '_parse_attachment_payload', _deep_extract) + + result = materialization._build_selected_eml_result( + intake=intake, + parent_asset=asset, + selected_attachment_keys={'order-0.pdf', 'order-1.pdf', 'order-2.pdf'}, + max_concurrency=2, + ) + + assert peak == 2 + assert [item['extracted_text'] for item in result.meta['attachments']] == [ + 'text:order-0.pdf', 'text:order-1.pdf', 'text:order-2.pdf', + ] + + +def test_selected_normal_files_use_global_bounded_parallel_extraction(app, shipping_user, monkeypatch): + """不同普通文件共享首轮并发预算,完成顺序不得改变主线程持久化顺序。""" + from app.services.shipping_notice.notice_upload import NoticeIntakeResult + import app.services.shipping_notice.order_extraction_materialization as materialization + + with app.app_context(): + first_asset, first_intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PARALLEL-PDF-1') + second_asset, second_intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PARALLEL-PDF-2') + first_asset.original_filename = 'first.pdf' + second_asset.original_filename = 'second.pdf' + first_asset.mime_type = second_asset.mime_type = 'application/pdf' + db.session.commit() + active = 0 + peak = 0 + lock = threading.Lock() + persisted: list[str] = [] + + def _deep_result(*, parent_asset, flask_app): + nonlocal active, peak + assert flask_app is app + with lock: + active += 1 + peak = max(peak, active) + time.sleep(0.03) + with lock: + active -= 1 + return NoticeIntakeResult( + filename=parent_asset.original_filename, source_type='pdf', source_file_type='application/pdf', + text='PO 4510000001', warnings=[], meta={}, content_hash=str(parent_asset.content_hash), + file_size=12, status='accepted', saved_path=None, + ) + + monkeypatch.setattr(materialization, '_build_single_file_result_in_thread', _deep_result) + monkeypatch.setattr( + materialization, + 'persist_intake_documents', + lambda **kwargs: persisted.append(kwargs['result'].filename) or {'document_count': 1}, + ) + + materialization.ensure_order_extraction_input_documents( + intakes=[first_intake, second_intake], + attachment_selection={'max_initial_concurrency': 2}, + schema_definition={'fields': []}, + ) + + assert peak == 2 + assert persisted == ['first.pdf', 'second.pdf'] + + def test_create_batch_from_intakes_marks_consumed_and_links_task(app, shipping_user, monkeypatch): with app.app_context(): asset, intake = _seed_parsed_intake(shipping_user.id) @@ -2461,6 +2643,51 @@ def test_recover_stale_parse_job_resets_stuck_parsing_intake(app, shipping_user) assert finished.status == 'success' +def test_recover_stale_order_extraction_job_requeues_run(app, shipping_user): + """订单抽取 Worker 退出后,超时回收须使 Job 和 Run 一起回到可重试状态。""" + with app.app_context(): + from datetime import timedelta + + from app.jobs.types import JobType + from app.models import Job, ShippingOrderExtractionRun + from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs + + run = ShippingOrderExtractionRun( + run_no='SNER-STALE-RECOVERY', + user_id=shipping_user.id, + owner_agent_id=shipping_user.id, + conversation_id='stale-recovery-test', + schema_version_id=1, + input_snapshot_hash='stale-recovery-hash', + input_snapshot_json={'intakes': []}, + idempotency_key='stale-recovery-idempotency-key', + status='processing', + phase='deterministic_parsing', + ) + db.session.add(run) + db.session.flush() + job = Job( + domain='shipping_notice', + job_type=JobType.SHIPPING_ORDER_EXTRACTION.value, + status='running', + business_ref=run.run_no, + payload_json={'run_no': run.run_no}, + attempts=1, + max_attempts=3, + started_at=datetime.utcnow() - timedelta(hours=1), + locked_at=datetime.utcnow() - timedelta(hours=1), + locked_by='dead-worker', + ) + db.session.add(job) + db.session.commit() + + count, _ = recover_stale_shipping_notice_jobs() + assert count >= 1 + db.session.expire_all() + assert db.session.get(Job, job.id).status == 'queued' + assert db.session.get(ShippingOrderExtractionRun, run.id).status == 'queued' + + def test_recover_exhausted_parse_job_marks_intake_parse_failed_and_clears_stage2( app, shipping_user, ): @@ -2775,7 +3002,7 @@ def test_stale_parse_lease_cannot_overwrite_after_recovery(app, shipping_user, m monkeypatch.setattr( 'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset', - lambda _asset: NoticeIntakeResult( + lambda _asset, **_kwargs: NoticeIntakeResult( filename='notice.txt', source_type='manual', source_file_type='text/plain', @@ -2952,7 +3179,7 @@ def test_parse_writeback_skips_cancel_during_extract(app, shipping_user, monkeyp monkeypatch.setattr( 'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset', - lambda _asset: NoticeIntakeResult( + lambda _asset, **_kwargs: NoticeIntakeResult( filename='notice.txt', source_type='manual', source_file_type='text/plain', @@ -2976,9 +3203,10 @@ def test_parse_writeback_skips_cancel_during_extract(app, shipping_user, monkeyp def test_run_intake_parse_persists_eml_attachment_texts(app, shipping_user, monkeypatch): """ - FileAsset → run_intake_parse → DB:EML 附件独立文本应持久化进 structured_result_json。 + FileAsset → run_intake_parse → DB:shipping_notice 用途的 EML 上传仅持久化附件目录。 - 核心逻辑:mock 读取资产字节为含文本附件的 EML,断言 attachment_count 与 extracted_text 落库。 + 核心逻辑:阶段 1 上传快览只保留邮件头/正文/附件目录,不得把附件全文、派生资产或 Document + 混入 Intake 摘要;详情接口也只能回放目录事实。 """ from email.message import EmailMessage @@ -3049,14 +3277,18 @@ def test_run_intake_parse_persists_eml_attachment_texts(app, shipping_user, monk assert structured.get('email', {}).get('subject') == 'Intake EML Persist' attachments = structured.get('attachments') or [] assert len(attachments) == 2 - texts = {row['filename']: row.get('extracted_text') for row in attachments} - assert 'PO-PERSIST-LINE-001' in str(texts.get('order-a.txt') or '') - assert 'PO-PERSIST-LINE-002' in str(texts.get('order-b.txt') or '') - assert 'PO-PERSIST-LINE-001' in str(refreshed.extracted_text or '') + by_name = {str(row.get('filename') or ''): row for row in attachments} + assert by_name['order-a.txt'].get('parse_status') == 'ready_for_extraction' + assert by_name['order-b.txt'].get('parse_status') == 'ready_for_extraction' + assert by_name['order-a.txt'].get('ready_for_extraction') is True + assert by_name['order-b.txt'].get('ready_for_extraction') is True + assert all('extracted_text' not in row for row in attachments) + assert 'PO-PERSIST-LINE-001' not in str(refreshed.extracted_text or '') expected_parser = str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6') assert refreshed.parser_version == expected_parser assert all('_payload_bytes' not in row for row in attachments) - assert all(row.get('asset_no') for row in attachments) + assert all(row.get('asset_no') is None for row in attachments) + assert all(row.get('document_id') is None for row in attachments) from app.services.shipping_notice.intake_service import serialize_intake @@ -3067,17 +3299,17 @@ def test_run_intake_parse_persists_eml_attachment_texts(app, shipping_user, monk full = serialize_intake(refreshed, asset=asset, include_parse_texts=True) full_atts = (full.get('parse_summary') or {}).get('attachments') or [] - assert 'PO-PERSIST-LINE-001' in str(full_atts[0].get('extracted_text') or '') + assert full_atts and 'extracted_text' not in full_atts[0] def test_run_intake_parse_persists_attached_multipart_and_detail_api( app, client, shipping_user, monkeypatch, ): """ - FileAsset → run_intake_parse → DB → 详情接口:附件型 multipart 独立文本与超深深 skipped 须落库返回。 + FileAsset → run_intake_parse → DB → 详情接口:上传快览只保留附件目录,不递归落 multipart 子内容。 - 核心逻辑:mixed 容器内 plain+html 均持久化;嵌套容器超限为 skipped 并带 depth warning; - status 瘦身、详情含全文。 + 核心逻辑:附件型 multipart 只作为单个目录项展示;嵌套内容和深度警告不应以附件全文形式写入 + shipping_notice Intake 的摘要或详情接口。 """ from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText @@ -3151,18 +3383,12 @@ def test_run_intake_parse_persists_attached_multipart_and_detail_api( for row in (structured.get('attachments') or []) } assert 'bundle-persist.mime' in by_name - assert 'inner-depth.mime' in by_name - bundle_text = str(by_name['bundle-persist.mime'].get('extracted_text') or '') - assert 'PLAIN-PO-101' in bundle_text - assert 'HTML-PO-202' in bundle_text - assert by_name['bundle-persist.mime'].get('parse_status') == 'parsed' - assert by_name['inner-depth.mime'].get('parse_status') == 'skipped' - warnings = list(structured.get('warnings') or []) + list( - by_name['inner-depth.mime'].get('warnings') or [] - ) - assert any(str(w).startswith('eml_nesting_depth_exceeded:') for w in warnings) - assert 'PLAIN-PO-101' in str(refreshed.extracted_text or '') - assert 'HTML-PO-202' in str(refreshed.extracted_text or '') + assert 'inner-depth.mime' not in by_name + assert by_name['bundle-persist.mime'].get('parse_status') == 'directory_only' + assert by_name['bundle-persist.mime'].get('ready_for_extraction') is False + assert by_name['bundle-persist.mime'].get('catalog_reason') == 'unknown_binary' + assert 'PLAIN-PO-101' not in str(refreshed.extracted_text or '') + assert 'HTML-PO-202' not in str(refreshed.extracted_text or '') lean = serialize_intake(refreshed, asset=asset, include_parse_texts=False) lean_bundle = next( @@ -3178,8 +3404,7 @@ def test_run_intake_parse_persists_attached_multipart_and_detail_api( for row in ((full.get('parse_summary') or {}).get('attachments') or []) if row.get('filename') == 'bundle-persist.mime' ) - assert 'PLAIN-PO-101' in str(full_bundle.get('extracted_text') or '') - assert 'HTML-PO-202' in str(full_bundle.get('extracted_text') or '') + assert 'extracted_text' not in full_bundle headers = {'Authorization': f'Bearer {issue_local_access_token(shipping_user)}'} @@ -3193,8 +3418,7 @@ def test_run_intake_parse_persists_attached_multipart_and_detail_api( status_atts = (status_item.get('parse_summary') or {}).get('attachments') or [] status_bundle = next(row for row in status_atts if row.get('filename') == 'bundle-persist.mime') assert 'extracted_text' not in status_bundle - status_inner = next(row for row in status_atts if row.get('filename') == 'inner-depth.mime') - assert status_inner.get('parse_status') == 'skipped' + assert all(row.get('filename') != 'inner-depth.mime' for row in status_atts) detail_res = client.get( '/api/workspace/shipping-notice/intakes/SNI-EML-MP-PERSIST-001', @@ -3203,10 +3427,8 @@ def test_run_intake_parse_persists_attached_multipart_and_detail_api( assert detail_res.status_code == 200 detail_atts = (detail_res.get_json()['data'].get('parse_summary') or {}).get('attachments') or [] detail_bundle = next(row for row in detail_atts if row.get('filename') == 'bundle-persist.mime') - assert 'PLAIN-PO-101' in str(detail_bundle.get('extracted_text') or '') - assert 'HTML-PO-202' in str(detail_bundle.get('extracted_text') or '') - detail_inner = next(row for row in detail_atts if row.get('filename') == 'inner-depth.mime') - assert detail_inner.get('parse_status') == 'skipped' + assert 'extracted_text' not in detail_bundle + assert all(row.get('filename') != 'inner-depth.mime' for row in detail_atts) def test_intake_status_api_strips_texts_detail_returns_full(app, client): @@ -3413,8 +3635,10 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid app, shipping_user, monkeypatch, ): """ - 上传预处理验收:3 个含真实 PO 的 PDF → 正文 Document(email_context) + 3 PDF Document; - 点击发送前不生成 Candidate;各 PDF 独立 FileAsset;重试不膨胀。 + 上传预处理验收:EML 快览阶段不创建附件 Document、派生资产或布局任务。 + + 核心逻辑:即使附件是可解析 PDF,shipping_notice 上传阶段也只登记目录与可解析标记; + 真正的 Document/资产/布局物化必须等到点击发送后的计划链路。 """ from email.message import EmailMessage @@ -3489,7 +3713,7 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid if str(w).startswith('document_candidate_persist_failed') ] assert not persist_warns, persist_warns - assert first.get('document_count') == 4, first + assert first.get('document_count') == 0, first docs = ( db.session.query(ShippingNoticeDocument) .filter_by(intake_id=refreshed_intake.id) @@ -3511,26 +3735,24 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid .all() ) - assert len(docs) == 4, (first, refreshed_intake.parse_warnings_json) - body_docs = [d for d in docs if d.document_type == 'email_body'] - assert len(body_docs) == 1 - assert body_docs[0].classification == 'email_context' - pdf_docs = [d for d in docs if d.document_type == 'attachment'] - assert len(pdf_docs) == 3 - assert all(d.classification == 'order_notice' for d in pdf_docs) - assert all(d.asset_id for d in pdf_docs) + assert len(docs) == 0, (first, refreshed_intake.parse_warnings_json) assert len(cands) == 0 - assert len(children) == 3 - assert len({c.content_hash for c in children}) == 3 + assert len(children) == 0 from app.models import Job, ShippingDocumentLayoutVersion - assert ShippingDocumentLayoutVersion.query.filter( - ShippingDocumentLayoutVersion.document_id.in_([item.id for item in pdf_docs]), - ).count() == 3 - assert Job.query.filter_by(job_type='shipping_document_layout').count() == 3 + assert ShippingDocumentLayoutVersion.query.count() == 0 + assert Job.query.filter_by(job_type='shipping_document_layout').count() == 0 + + structured = refreshed_intake.structured_result_json or {} + assert structured.get('attachment_count') == 3 + assert structured.get('ready_attachment_count') == 3 + rows = structured.get('attachments') or [] + assert {row.get('filename') for row in rows} == {f'{po}.pdf' for po in markers} + assert all(row.get('parse_status') == 'ready_for_extraction' for row in rows) + assert all('extracted_text' not in row for row in rows) detail = serialize_intake(refreshed_intake, asset=parent, include_parse_texts=True) - assert detail['document_count'] == 4 + assert detail['document_count'] == 0 assert detail['candidate_count'] == 0 intake2 = ( @@ -3549,22 +3771,22 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid .one() .id ) - assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake_id).count() == 4 + assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake_id).count() == 0 assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=intake_id).count() == 0 - assert ShippingDocumentLayoutVersion.query.count() == 3 - assert Job.query.filter_by(job_type='shipping_document_layout').count() == 3 + assert ShippingDocumentLayoutVersion.query.count() == 0 + assert Job.query.filter_by(job_type='shipping_document_layout').count() == 0 assert ( db.session.query(FileAsset) .filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None)) .count() - == 3 + == 0 ) def test_run_intake_parse_persists_sanitized_email_html_layout_without_meta_leak( app, shipping_user, monkeypatch, ): - """HTML 正文表格应生成独立布局版本,临时 HTML 不得进入 Intake 摘要或 Dify 文档正文。""" + """HTML 正文表格快览只保留脱敏摘要,不在上传阶段生成 Document 或布局版本。""" from email.message import EmailMessage from io import BytesIO @@ -3607,18 +3829,19 @@ def test_run_intake_parse_persists_sanitized_email_html_layout_without_meta_leak result = run_intake_parse(intake, parent) db.session.expire_all() - body = ShippingNoticeDocument.query.filter_by( - intake_id=intake.id, document_type='email_body', - ).one() - version = ShippingDocumentLayoutVersion.query.filter_by(document_id=body.id).one() structured = db.session.get(ShippingNoticeIntake, intake.id).structured_result_json assert result['status'] == 'parsed' - assert version.status == 'needs_review' - assert version.payload_json['layout_candidate']['parser']['name'] == 'eml-html-dom' - assert 'SECRET' not in repr(version.payload_json) - assert 'body_html_tables' not in repr(structured) - assert ' ShippingOrderDocumentProfile: + """构造最小 published Profile,供资格与 Run 门禁测试复用。""" + profile = ShippingOrderDocumentProfile( + profile_code=f'AF-{checksum[:6]}', + display_name='Auto freeze profile', + version=1, + status='published', + schema_version_id=schema_version_id, + structure_fingerprint='fp-' + checksum[:16], + checksum=checksum, + definition_json={'contract_version': 'order_coordinate_profile.v2', 'table_regions': []}, + published_at=datetime.utcnow(), + ) + db.session.add(profile) + db.session.flush() + return profile + + +def _confirm_run_customer(*, run_id: int, intake_id: int, schema_version_id: int, customer: ShippingCustomer) -> None: + """为 Run 构造一条已确认的 Bill-to 客户匹配,供范围门禁测试复用。""" + extraction = ShippingOrderExtraction( + run_id=run_id, + intake_id=intake_id, + schema_version_id=schema_version_id, + input_snapshot_hash=f'run-{run_id}-customer-{customer.id}', + input_snapshot_json={}, + status='accepted', + ) + db.session.add(extraction) + db.session.flush() + db.session.add(ShippingOrderCustomerMatch( + extraction_id=extraction.id, + role='bill_to', + identity_components_json={}, + status='confirmed', + customer_id=customer.id, + customer_name_snapshot=customer.standard_name, + customer_short_code_snapshot=customer.short_code, + identity_fingerprint=f'customer-{customer.id}', + identity_rule_version='customer-match.v1', + resolution_method='manual', + confirmed_at=datetime.utcnow(), + )) + + +def _materialize_run_plan(run) -> None: + """模拟 Worker 物化边界,为 Run 级门禁测试创建延迟生成的执行计划。""" + from app.services.shipping_notice.order_extraction_run_service import materialize_order_extraction_run_inputs + + with patch('app.services.shipping_notice.order_extraction_run_service.ensure_order_extraction_input_documents'): + materialize_order_extraction_run_inputs(run) + + +def test_evaluate_run_auto_freeze_policy_keeps_fail_closed_with_run_blockers(app): + """即使命中已批准模板,技术失败、预算停止与待处理订单仍必须阻断自动冻结。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-FREEZE-POLICY') + run, _ = create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + _materialize_run_plan(run) + plan = run.extraction_plan + unit = plan.units[0] + job = db.session.get(Job, run.current_job_id) + profile = _published_profile(schema_version_id=run.schema_version_id, checksum='a' * 64) + qualification = ShippingDocumentProfileAutoFreezeQualification( + profile_id=profile.id, + profile_version=profile.version, + profile_checksum=profile.checksum, + schema_version_id=run.schema_version_id, + parser_version='deterministic-order-parser.v1', + status='auto_freeze_approved', + ) + next_sequence_no = ( + db.session.query(ShippingOrderExtractionProgressEvent.sequence_no) + .filter_by(run_id=run.id) + .order_by(ShippingOrderExtractionProgressEvent.sequence_no.desc()) + .limit(1) + .scalar() + or 0 + ) + 1 + unit.technical_failure_reason_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT' + run.status = 'review_required' + db.session.add_all([ + qualification, + ShippingOrderExtractionRouteDecision( + run_id=run.id, + unit_id=unit.id, + job_id=job.id, + attempt_no=1, + decision='deterministic', + match_status='unique_match', + selected_profile_id=profile.id, + selected_profile_code=profile.profile_code, + selected_profile_version=profile.version, + selected_profile_checksum=profile.checksum, + auto_create_approved=True, + candidate_count=1, + table_count=1, + document_table_count=1, + business_table_count=1, + matched_table_count=1, + parsed_table_count=1, + approved_table_count=1, + candidate_summary_json=[], + fallback_reason_codes_json=[], + ), + ShippingOrderExtractionProgressEvent( + run_id=run.id, + sequence_no=next_sequence_no, + visibility='workspace', + event_code='budget_stopped', + status='completed', + occurred_at=datetime.utcnow(), + reason_code='budget_initial_limit', + idempotency_key=f'budget-stop-{run.id}', + summary_json={'reason_codes': ['budget_initial_limit']}, + ), + ]) + db.session.commit() + + policy = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 1}) + + assert policy['enabled'] is False + assert policy['selected_profile_id'] == profile.id + assert policy['qualification_id'] == qualification.id + assert policy['qualification_status'] == 'auto_freeze_approved' + assert set(policy['blocking_reason_codes']) >= { + 'technical_failure_present', + 'budget_stopped', + 'review_required', + 'pending_orders_present', + 'customer_scope_not_configured', + 'business_scenario_not_configured', + 'customer_confirmation_required', + } + + +def test_evaluate_run_auto_freeze_policy_blocks_suspended_profile(app): + """模板资格被暂停后,新 Run 即使命中该模板也必须继续人工确认。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-FREEZE-SUSPENDED') + run, _ = create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + _materialize_run_plan(run) + unit = run.extraction_plan.units[0] + job = db.session.get(Job, run.current_job_id) + profile = _published_profile(schema_version_id=run.schema_version_id, checksum='b' * 64) + qualification = ShippingDocumentProfileAutoFreezeQualification( + profile_id=profile.id, + profile_version=profile.version, + profile_checksum=profile.checksum, + schema_version_id=run.schema_version_id, + parser_version='deterministic-order-parser.v1', + status='auto_freeze_suspended', + ) + db.session.add_all([ + qualification, + ShippingOrderExtractionRouteDecision( + run_id=run.id, + unit_id=unit.id, + job_id=job.id, + attempt_no=1, + decision='deterministic', + match_status='unique_match', + selected_profile_id=profile.id, + selected_profile_code=profile.profile_code, + selected_profile_version=profile.version, + selected_profile_checksum=profile.checksum, + auto_create_approved=True, + candidate_count=1, + table_count=1, + document_table_count=1, + business_table_count=1, + matched_table_count=1, + parsed_table_count=1, + approved_table_count=1, + candidate_summary_json=[], + fallback_reason_codes_json=[], + ), + ]) + db.session.commit() + + policy = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 0}) + + assert policy['enabled'] is False + assert policy['qualification_status'] == 'auto_freeze_suspended' + assert 'profile_auto_freeze_suspended' in policy['blocking_reason_codes'] + assert 'customer_scope_not_configured' in policy['blocking_reason_codes'] + + +def test_evaluate_run_auto_freeze_policy_matches_customer_and_business_scope(app): + """客户和业务场景配置命中且无真实 pending 时,Run 可以进入自动冻结放行状态。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-FREEZE-SCOPE-MATCH') + run, _ = create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + _materialize_run_plan(run) + unit = run.extraction_plan.units[0] + job = db.session.get(Job, run.current_job_id) + profile = _published_profile(schema_version_id=run.schema_version_id, checksum='c' * 64) + customer = ShippingCustomer(standard_name='Matched Customer', short_code='MATCH') + db.session.add(customer) + db.session.flush() + _confirm_run_customer(run_id=run.id, intake_id=intake.id, schema_version_id=run.schema_version_id, customer=customer) + qualification = ShippingDocumentProfileAutoFreezeQualification( + profile_id=profile.id, + profile_version=profile.version, + profile_checksum=profile.checksum, + schema_version_id=run.schema_version_id, + parser_version='deterministic-order-parser.v1', + status='auto_freeze_approved', + customer_ids_json=[customer.id], + business_scenarios_json=['shipping_notice_order'], + requires_customer_confirmation=False, + ) + db.session.add_all([ + qualification, + ShippingOrderExtractionRouteDecision( + run_id=run.id, + unit_id=unit.id, + job_id=job.id, + attempt_no=1, + decision='deterministic', + match_status='unique_match', + selected_profile_id=profile.id, + selected_profile_code=profile.profile_code, + selected_profile_version=profile.version, + selected_profile_checksum=profile.checksum, + auto_create_approved=True, + candidate_count=1, + table_count=1, + document_table_count=1, + business_table_count=1, + matched_table_count=1, + parsed_table_count=1, + approved_table_count=1, + candidate_summary_json=[], + fallback_reason_codes_json=[], + ), + ]) + db.session.commit() + + policy = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 0}) + + assert policy['enabled'] is True + assert policy['customer_scope_status'] == 'matched' + assert policy['business_scenario_status'] == 'matched' + assert policy['confirmed_customer_ids'] == [customer.id] + assert policy['authorized_customer_ids'] == [customer.id] + assert policy['customer_confirmation_required'] is False + assert 'customer_scope_not_configured' not in policy['blocking_reason_codes'] + assert 'customer_scope_out_of_scope' not in policy['blocking_reason_codes'] + assert 'business_scenario_not_configured' not in policy['blocking_reason_codes'] + assert 'business_scenario_out_of_scope' not in policy['blocking_reason_codes'] + assert 'customer_confirmation_required' not in policy['blocking_reason_codes'] + + # Worker 提交本 Unit 的候选时,Run 可能尚未转为 review_required;Unit 事实必须先阻断副作用。 + unit.status = 'review_required' + run.status = 'processing' + db.session.flush() + blocked = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 0}) + + assert blocked['enabled'] is False + assert 'unit_review_required' in blocked['blocking_reason_codes'] + + +def test_evaluate_run_auto_freeze_policy_ignores_placeholder_pending_orders(app): + """仅因自动消费尚未执行而遗留的空原因 pending,不应继续阻断自动冻结。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-FREEZE-PENDING-PLACEHOLDER') + run, _ = create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + _materialize_run_plan(run) + unit = run.extraction_plan.units[0] + job = db.session.get(Job, run.current_job_id) + profile = _published_profile(schema_version_id=run.schema_version_id, checksum='d' * 64) + customer = ShippingCustomer(standard_name='Matched Customer 2', short_code='MAT') + db.session.add(customer) + db.session.flush() + _confirm_run_customer(run_id=run.id, intake_id=intake.id, schema_version_id=run.schema_version_id, customer=customer) + qualification = ShippingDocumentProfileAutoFreezeQualification( + profile_id=profile.id, + profile_version=profile.version, + profile_checksum=profile.checksum, + schema_version_id=run.schema_version_id, + parser_version='deterministic-order-parser.v1', + status='auto_freeze_approved', + customer_ids_json=[customer.id], + business_scenarios_json=['shipping_notice_order'], + requires_customer_confirmation=False, + ) + db.session.add_all([ + qualification, + ShippingOrderExtractionRouteDecision( + run_id=run.id, + unit_id=unit.id, + job_id=job.id, + attempt_no=1, + decision='deterministic', + match_status='unique_match', + selected_profile_id=profile.id, + selected_profile_code=profile.profile_code, + selected_profile_version=profile.version, + selected_profile_checksum=profile.checksum, + auto_create_approved=True, + candidate_count=1, + table_count=1, + document_table_count=1, + business_table_count=1, + matched_table_count=1, + parsed_table_count=1, + approved_table_count=1, + candidate_summary_json=[], + fallback_reason_codes_json=[], + ), + ]) + db.session.commit() + + policy = evaluate_run_auto_freeze_policy(run=run, submission_result={ + 'pending_count': 1, + 'pending_orders': [{ + 'candidate_no': 'SNC-PLACEHOLDER', + 'reasons': [], + 'missing_fields': [], + 'duplicate_status': None, + }], + }) + + assert policy['enabled'] is True + assert 'pending_orders_present' not in policy['blocking_reason_codes'] diff --git a/backend/tests/test_shipping_order_document_profile_service.py b/backend/tests/test_shipping_order_document_profile_service.py index b4f348b3..f35cefa0 100644 --- a/backend/tests/test_shipping_order_document_profile_service.py +++ b/backend/tests/test_shipping_order_document_profile_service.py @@ -14,6 +14,7 @@ from types import SimpleNamespace import numpy as np import pytest +import app.services.shipping_notice.preview_grant_store as preview_grant_store_service from app import db from app.models import ( ShippingOrderDocumentProfile, @@ -894,7 +895,8 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url( def test_profile_page_preview_fails_closed_without_redis_or_sample_binding(app, monkeypatch): """预览授权依赖 Redis 且只能读取 Profile 已绑定样本,不能降级为进程内或任意文档读取。""" with app.app_context(): - monkeypatch.setattr('app.services.redis_client.get_redis_client', lambda: None) + app.config['ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK'] = False + monkeypatch.setattr(preview_grant_store_service, 'get_redis_client', lambda: None) with pytest.raises(Exception) as unavailable: service._preview_grant_store() assert getattr(unavailable.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE' @@ -903,6 +905,17 @@ def test_profile_page_preview_fails_closed_without_redis_or_sample_binding(app, assert getattr(unbound.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND' +def test_profile_page_preview_uses_memory_fallback_in_development(app, monkeypatch): + """开发环境允许单进程内存兜底,仍需保持一次性令牌语义。""" + with app.app_context(): + app.config['ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK'] = True + monkeypatch.setattr(preview_grant_store_service, 'get_redis_client', lambda: None) + store = service._preview_grant_store() + store.setex('preview-token', 30, '{"page_no":1}') + assert store.getdel('preview-token') == '{"page_no":1}' + assert store.getdel('preview-token') is None + + def test_profile_region_preview_requires_a_bound_document(app, monkeypatch): """局部预览只能作用于当前模板样本,避免管理员接口被 document_id 枚举越权。""" with app.app_context(): diff --git a/backend/tests/test_shipping_order_extraction_progress.py b/backend/tests/test_shipping_order_extraction_progress.py index 5bdc3b4c..10f013fa 100644 --- a/backend/tests/test_shipping_order_extraction_progress.py +++ b/backend/tests/test_shipping_order_extraction_progress.py @@ -22,58 +22,57 @@ def _run() -> ShippingOrderExtractionRun: row = ShippingOrderExtractionRun( run_no='SNER-PROGRESS', user_id=1, owner_agent_id=1, conversation_id='progress-conv', schema_version_id=1, input_snapshot_hash='a' * 64, input_snapshot_json={}, idempotency_key='b' * 64, - status='running', phase='calling_provider', + status='processing', phase='deterministic_parsing', ) db.session.add(row) db.session.commit() return row -def test_progress_events_dedupe_parallel_stages_and_protect_hxops_persistence(app): - """重复SSE不重复落库;并行阶段合并,持久化阶段不被迟到Dify节点覆盖。""" +def test_progress_events_dedupe_sequence_and_protect_terminal_run(app): + """重复业务事件不重复落库;终态后迟到普通事件不能覆盖当前投影。""" with app.app_context(): run = _run() assert record_order_extraction_progress_event( run_no=run.run_no, - event={'event_type': 'workflow_started', 'workflow_run_id': 'wf-progress'}, + event={'event_code': 'document_queued', 'document_id': 11}, ) is True assert record_order_extraction_progress_event( run_no=run.run_no, - event={'event_type': 'node_started', 'workflow_run_id': 'wf-progress', 'node_execution_id': 'n1', 'node_type': 'document-extractor'}, + event={'event_code': 'profile_matching', 'unit_id': 7, 'document_id': 11}, ) is True assert record_order_extraction_progress_event( run_no=run.run_no, - event={'event_type': 'node_started', 'workflow_run_id': 'wf-progress', 'node_execution_id': 'n2', 'node_type': 'llm'}, + event={'event_code': 'profile_matched', 'unit_id': 7, 'document_id': 11, 'summary': {'profile_code': 'vendor_a'}}, ) is True assert record_order_extraction_progress_event( run_no=run.run_no, - event={'event_type': 'node_started', 'workflow_run_id': 'wf-progress', 'node_execution_id': 'n2', 'node_type': 'llm'}, + event={'event_code': 'profile_matched', 'unit_id': 7, 'document_id': 11, 'summary': {'profile_code': 'vendor_a'}}, ) is False db.session.expire_all() run = db.session.get(ShippingOrderExtractionRun, run.id) - assert run.current_stage_code == 'order_recognition' - assert set(run.active_stage_codes_json or []) == {'document_processing', 'order_recognition'} + assert run.current_stage_code == 'profile_matched' + assert list(run.active_stage_codes_json or []) == ['profile_matched'] assert record_order_extraction_progress_event( run_no=run.run_no, - event={'event_type': 'node_finished', 'workflow_run_id': 'wf-progress', 'node_execution_id': 'n2', 'node_type': 'llm'}, + event={'event_code': 'candidate_ready', 'unit_id': 7, 'document_id': 11}, ) is True db.session.expire_all() run = db.session.get(ShippingOrderExtractionRun, run.id) - assert run.current_stage_code == 'order_recognition' + assert run.current_stage_code == 'candidate_ready' + run.status = 'completed' + run.progress_version = 4 + db.session.commit() assert record_order_extraction_progress_event( run_no=run.run_no, - event={'event_type': 'hxops_persistence_started', 'job_id': 1, 'attempt_count': 1}, - ) is True - assert record_order_extraction_progress_event( - run_no=run.run_no, - event={'event_type': 'node_finished', 'workflow_run_id': 'wf-progress', 'node_execution_id': 'n1', 'node_type': 'document-extractor'}, - ) is True + event={'event_code': 'profile_matching', 'unit_id': 8, 'document_id': 12}, + ) is False db.session.expire_all() run = db.session.get(ShippingOrderExtractionRun, run.id) - assert run.current_stage_code == 'hxops_persistence' - assert ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).count() == 6 + assert run.current_stage_code == 'candidate_ready' + assert ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).count() == 4 def test_progress_mapping_version_fits_persisted_column(app): @@ -82,7 +81,7 @@ def test_progress_mapping_version_fits_persisted_column(app): run = _run() assert record_order_extraction_progress_event( run_no=run.run_no, - event={'event_type': 'workflow_started', 'workflow_run_id': 'wf-version'}, + event={'event_code': 'document_queued', 'document_id': 11}, ) is True db.session.expire_all() persisted = db.session.get(ShippingOrderExtractionRun, run.id) @@ -90,43 +89,115 @@ def test_progress_mapping_version_fits_persisted_column(app): assert persisted.progress_mapping_version == MAPPING_VERSION -def test_progress_event_discards_custom_node_title(app): - """自定义节点标题可能包含业务意图,诊断事件与幂等键均不得持久化该文本。""" +def test_progress_event_accepts_email_supplement_merge_summary(app): + """正文补充合并事件必须可持久化,并把当前投影推进到 supplement 合并阶段。""" + with app.app_context(): + run = _run() + assert record_order_extraction_progress_event( + run_no=run.run_no, + event={ + 'event_code': 'email_supplement_merged', + 'unit_id': 7, + 'document_id': 11, + 'summary': {'status': 'merged', 'relation_codes': ['po_mpn'], 'conflict_count': 0}, + }, + ) is True + db.session.expire_all() + run = db.session.get(ShippingOrderExtractionRun, run.id) + event = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).one() + assert run.current_stage_code == 'email_supplement_merged' + assert list(run.active_stage_codes_json or []) == ['email_supplement_merged'] + assert event.summary_json == {'conflict_count': 0, 'relation_codes': ['po_mpn'], 'status': 'merged'} + + +def test_progress_event_accepts_plan_expansion_and_budget_run_level_events(app): + """计划创建、扩批启动和预算停止必须作为 Run 级事实进入统一进度流。""" + with app.app_context(): + run = _run() + assert record_order_extraction_progress_event( + run_no=run.run_no, + event={ + 'event_code': 'plan_created', + 'summary': {'unit_count': 2, 'selection': {'selected_attachment_count': 2}}, + }, + ) is True + assert record_order_extraction_progress_event( + run_no=run.run_no, + event={ + 'event_code': 'initial_wave_started', + 'summary': {'selected_attachment_count': 2, 'max_initial_attachments': 2}, + }, + ) is True + assert record_order_extraction_progress_event( + run_no=run.run_no, + event={ + 'event_code': 'expansion_wave_started', + 'summary': {'selection_batch': 2, 'unit_count': 2, 'reason_codes': ['required_field_missing']}, + }, + ) is True + assert record_order_extraction_progress_event( + run_no=run.run_no, + event={ + 'event_code': 'budget_stopped', + 'reason_code': 'budget_initial_limit', + 'summary': {'budget_limited_attachment_count': 2}, + }, + ) is True + db.session.expire_all() + run = db.session.get(ShippingOrderExtractionRun, run.id) + events = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).order_by( + ShippingOrderExtractionProgressEvent.sequence_no.asc(), + ).all() + assert [row.event_code for row in events] == [ + 'plan_created', + 'initial_wave_started', + 'expansion_wave_started', + 'budget_stopped', + ] + assert events[2].summary_json == { + 'reason_codes': ['required_field_missing'], + 'selection_batch': 2, + 'unit_count': 2, + } + assert run.current_stage_code == 'budget_stopped' + assert list(run.active_stage_codes_json or []) == [] + + +def test_progress_event_discards_unstructured_payload(app): + """自定义非结构化文本不能进入新事件表摘要。""" with app.app_context(): run = _run() event = { - 'event_type': 'node_started', - 'workflow_run_id': 'wf-safe', - 'node_execution_id': 'node-safe', - 'node_type': 'llm', + 'event_code': 'profile_matching', + 'document_id': 11, 'node_title': '客户甲秘密订单识别', } assert record_order_extraction_progress_event(run_no=run.run_no, event=event) is True event['node_title'] = '另一个可能敏感的标题' assert record_order_extraction_progress_event(run_no=run.run_no, event=event) is False - row = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).one() - assert not hasattr(row, 'node_title') - assert '客户甲' not in str(row.details_json) + rows = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).order_by(ShippingOrderExtractionProgressEvent.id.asc()).all() + assert len(rows) == 1 + assert all('客户甲' not in str(row.summary_json) for row in rows) -def test_terminal_run_records_diagnostics_without_mutating_projection(app): - """终态后的迟到节点只保留管理员审计,绝不把用户状态改回运行中。""" +def test_terminal_run_rejects_late_workspace_event_without_mutating_projection(app): + """终态后的迟到普通事件直接忽略,绝不把用户状态改回处理中。""" with app.app_context(): run = _run() run.status = 'completed' - run.current_stage_code = 'hxops_persistence' + run.current_stage_code = 'candidate_ready' run.progress_version = 9 db.session.commit() assert record_order_extraction_progress_event( run_no=run.run_no, - event={'event_type': 'node_started', 'workflow_run_id': 'wf-late', 'node_execution_id': 'late-1', 'node_type': 'llm'}, - ) is True + event={'event_code': 'profile_matching', 'unit_id': 8, 'document_id': 12}, + ) is False db.session.expire_all() run = db.session.get(ShippingOrderExtractionRun, run.id) assert run.status == 'completed' - assert run.current_stage_code == 'hxops_persistence' + assert run.current_stage_code == 'candidate_ready' assert run.progress_version == 9 @@ -136,11 +207,11 @@ def test_progress_cleanup_deletes_only_expired_events_and_keeps_run(app): run = _run() now = datetime.utcnow() expired = ShippingOrderExtractionProgressEvent( - run_id=run.id, event_type='node_finished', stage_code='order_recognition', event_status='completed', + run_id=run.id, sequence_no=1, visibility='workspace', event_code='candidate_ready', status='completed', received_at=now - timedelta(days=91), idempotency_key='expired-progress-event', expires_at=now - timedelta(seconds=1), ) retained = ShippingOrderExtractionProgressEvent( - run_id=run.id, event_type='node_started', stage_code='document_processing', event_status='running', + run_id=run.id, sequence_no=2, visibility='workspace', event_code='profile_matching', status='completed', received_at=now, idempotency_key='retained-progress-event', expires_at=now + timedelta(days=1), ) db.session.add_all([expired, retained]) @@ -152,9 +223,9 @@ def test_progress_cleanup_deletes_only_expired_events_and_keeps_run(app): def test_user_slow_threshold_uses_p95_after_minimum_samples_and_is_capped(app): - """慢响应阈值不足20样本回退60秒,满足样本后按P95且上限300秒。""" + """慢响应阈值不足20样本回退180秒,满足样本后按P95且上限300秒。""" with app.app_context(): - assert get_order_extraction_user_slow_threshold_seconds() == 60 + assert get_order_extraction_user_slow_threshold_seconds() == 180 base = datetime.utcnow() - timedelta(minutes=10) for index in range(20): run = ShippingOrderExtractionRun( diff --git a/backend/tests/test_shipping_order_extraction_quality_gate.py b/backend/tests/test_shipping_order_extraction_quality_gate.py index 2aca1ee4..674c1d26 100644 --- a/backend/tests/test_shipping_order_extraction_quality_gate.py +++ b/backend/tests/test_shipping_order_extraction_quality_gate.py @@ -1,344 +1,65 @@ -""" -backend/tests/test_shipping_order_extraction_quality_gate.py - -用途:验证 L7 订单抽取双人影子标签、指标、双角色批准和 Runtime Binding 自动建单门禁。 -依赖:质量服务、Agent Runtime Binding、订单抽取 Run 测试夹具。 -逻辑:构造 100 个匿名一致样本达标批次,并覆盖分歧、权限边界和批准引用。 -""" - -from __future__ import annotations - -from datetime import datetime - -import pytest +"""Verify order extraction quality batches without runtime bindings.""" from app import db -from app.core.auth.jwt import issue_local_access_token -from app.core.errors import ConflictError, ValidationError -from app.jobs.context import JobContext -from app.jobs.handlers.shipping_order_extraction import run_shipping_order_extraction -from app.jobs.queue import claim_next_job -from app.jobs.types import JobType -from app.models import ( - Agent, - AgentRuntimeBinding, - ShippingOrderSchema, - ShippingOrderExtractionQualityBatch, - ShippingOrderExtractionQualityLabel, - ShippingOrderExtractionRun, - User, -) -from app.services.agent_runtime_binding_service import save_runtime_binding -from app.services.shipping_notice.order_extraction_quality_service import ( - approve_quality_batch, - list_approved_quality_batches, - quality_metrics, - require_approved_quality_batch, - save_quality_label, -) -from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run +from app.models import ShippingOrderExtractionQualityBatch, ShippingOrderExtractionQualityLabel, ShippingOrderExtractionRun, User +from app.services.shipping_notice.order_extraction_quality_service import quality_metrics, save_quality_label from tests.test_shipping_order_extraction_runs import _seed_run_input -from tests.conftest import parse_api_data - - -def _quality_batch(owner: Agent, schema_version_id: int, creator: User) -> ShippingOrderExtractionQualityBatch: - """建立 collecting 批次,供服务级测试批量注入匿名标签。""" - batch = ShippingOrderExtractionQualityBatch( - batch_no=f'SOQ-TEST-{owner.id}', owner_agent_id=owner.id, - schema_version_id=schema_version_id, - threshold_version='l7.v1', status='collecting', created_by_id=creator.id, - ) - db.session.add(batch) - db.session.flush() - return batch - - -def _add_agreed_samples( - batch: ShippingOrderExtractionQualityBatch, runs: list[ShippingOrderExtractionRun], - first: User, second: User, -) -> None: - """为每个 Run 写入两份完全一致且无错误的匿名标签。""" - for run in runs: - for reviewer in (first, second): - db.session.add(ShippingOrderExtractionQualityLabel( - batch_id=batch.id, run_id=run.id, reviewer_id=reviewer.id, - core_expected_count=4, core_extracted_count=4, core_correct_count=4, - wrong_merge=False, wrong_split=False, wrong_auto_create=False, - )) - db.session.flush() def test_quality_metrics_require_two_matching_reviews(app): - """单人和分歧标签不计样本;100 个一致样本才通过固定阈值。""" + """Only matching reviews count toward quality eligibility metrics.""" with app.app_context(): - user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-METRICS') - second = User(username='quality-second', email='quality-second@example.com', role='admin', password_hash='x') - db.session.add(second) + user, owner, session, _intake, _document = _seed_run_input(suffix='QUALITY-METRICS') + reviewer = User(username='quality-reviewer', email='quality-reviewer@example.com', role='admin', password_hash='x') + db.session.add(reviewer) db.session.flush() - batch = _quality_batch(owner, 1, user) - runs = [] - for index in range(100): - run = ShippingOrderExtractionRun( - run_no=f'SNER-QUALITY-{index:03d}', user_id=user.id, owner_agent_id=owner.id, - conversation_id=f'quality-{index}', schema_version_id=batch.schema_version_id, - input_snapshot_hash=f'{index:064x}'[-64:], input_snapshot_json={}, - idempotency_key=f'{index + 1000:064x}'[-64:], status='completed', phase='completed', - provider_config_json={'auto_create_enabled': False}, - ) - db.session.add(run) - runs.append(run) + batch = ShippingOrderExtractionQualityBatch( + batch_no='SOQ-QUALITY-METRICS', owner_agent_id=owner.id, schema_version_id=1, + threshold_version='l7.v1', status='collecting', created_by_id=user.id, + ) + run = ShippingOrderExtractionRun( + run_no='SNER-QUALITY-METRICS', user_id=user.id, owner_agent_id=owner.id, + conversation_id=session.session_id, schema_version_id=1, + input_snapshot_hash='a' * 64, input_snapshot_json={}, idempotency_key='b' * 64, + status='completed', phase='completed', auto_freeze_policy_json={'enabled': False}, + ) + db.session.add_all([batch, run]) + db.session.flush() + for actor in (user, reviewer): + db.session.add(ShippingOrderExtractionQualityLabel( + batch_id=batch.id, run_id=run.id, reviewer_id=actor.id, + core_expected_count=4, core_extracted_count=4, core_correct_count=4, + wrong_merge=False, wrong_split=False, wrong_auto_create=False, + )) db.session.flush() - _add_agreed_samples(batch, runs, user, second) - metrics = quality_metrics(batch) - - assert metrics['eligible'] is True - assert metrics['agreed_sample_count'] == 100 - assert metrics['precision'] == 1.0 - assert metrics['recall'] == 1.0 + assert quality_metrics(batch)['agreed_sample_count'] == 1 -def test_quality_label_rejects_wrong_owner_or_auto_create_run(app): - """标签只能引用同 Owner/Schema 的终态 unit.v3 影子 Run,不能标生产自动建单结果。""" +def test_quality_label_rejects_auto_creation_run(app): + """Production auto-creation Runs cannot become quality samples.""" with app.app_context(): - user, owner, session, intake, _document = _seed_run_input(suffix='QUALITY-LABEL') + user, owner, session, _intake, _document = _seed_run_input(suffix='QUALITY-INVALID') user.role = 'admin' - batch = _quality_batch(owner, 1, user) + batch = ShippingOrderExtractionQualityBatch( + batch_no='SOQ-QUALITY-INVALID', owner_agent_id=owner.id, schema_version_id=1, + threshold_version='l7.v1', status='collecting', created_by_id=user.id, + ) run = ShippingOrderExtractionRun( run_no='SNER-QUALITY-INVALID', user_id=user.id, owner_agent_id=owner.id, - conversation_id=session.session_id, schema_version_id=batch.schema_version_id, - input_snapshot_hash='a' * 64, input_snapshot_json={}, idempotency_key='b' * 64, - status='completed', phase='completed', - provider_config_json={'auto_create_enabled': True}, + conversation_id=session.session_id, schema_version_id=1, + input_snapshot_hash='c' * 64, input_snapshot_json={}, idempotency_key='d' * 64, + status='completed', phase='completed', auto_freeze_policy_json={'enabled': True}, ) - db.session.add(run) - db.session.flush() + db.session.add_all([batch, run]) + db.session.commit() - with pytest.raises(ValidationError) as caught: + try: save_quality_label( batch_id=batch.id, run_no=run.run_no, actor_id=user.id, payload={'core_expected_count': 4, 'core_extracted_count': 4, 'core_correct_count': 4}, ) - - assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_RUN_INVALID' - - -def test_approved_quality_batch_is_required_for_auto_create_binding(app): - """unit.v3 自动建单必须引用同 Owner、当前阈值、双人批准且仍达标的批次。""" - with app.app_context(): - user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-BINDING') - business = User(username='quality-business', email='quality-business@example.com', role='admin', password_hash='x') - technical = User(username='quality-technical', email='quality-technical@example.com', role='admin', password_hash='x') - db.session.add_all([business, technical]) - db.session.flush() - batch = _quality_batch(owner, 1, user) - runs = [] - for index in range(100): - run = ShippingOrderExtractionRun( - run_no=f'SNER-APPROVE-{index:03d}', user_id=user.id, owner_agent_id=owner.id, - conversation_id=f'approve-{index}', schema_version_id=batch.schema_version_id, - input_snapshot_hash=f'{index + 2000:064x}'[-64:], input_snapshot_json={}, - idempotency_key=f'{index + 3000:064x}'[-64:], status='completed', phase='completed', - provider_config_json={'auto_create_enabled': False}, - ) - db.session.add(run) - runs.append(run) - db.session.flush() - _add_agreed_samples(batch, runs, business, technical) - batch.status = 'ready' - db.session.flush() - approve_quality_batch(batch_id=batch.id, role='business', actor_id=business.id) - approve_quality_batch(batch_id=batch.id, role='technical', actor_id=technical.id) - provider = Agent.query.filter_by(exposure_mode='internal').first() - - approved = require_approved_quality_batch( - batch_id=batch.id, owner_agent_id=owner.id, schema_version_id=batch.schema_version_id, - ) - binding = save_runtime_binding( - owner_agent_id=owner.id, capability_code='shipping.order_extraction', - provider_agent_id=provider.id, enabled=True, quality_batch_id=batch.id, - config={'auto_create_enabled': True}, - ) - - assert approved.status == 'approved' - assert binding.quality_batch_id == batch.id - - -def test_same_admin_cannot_approve_both_roles(app): - """业务和技术批准必须由不同管理员完成。""" - with app.app_context(): - user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-APPROVERS') - user.role = 'admin' - batch = _quality_batch(owner, 1, user) - batch.status = 'ready' - batch.business_approved_by_id = user.id - batch.business_approved_at = datetime.utcnow() - db.session.flush() - - with pytest.raises(ConflictError): - require_approved_quality_batch( - batch_id=batch.id, owner_agent_id=owner.id, schema_version_id=batch.schema_version_id, - ) - with pytest.raises(ConflictError): - approve_quality_batch(batch_id=batch.id, role='technical', actor_id=user.id) - - -def test_first_approval_freezes_labels_and_schema_mismatch_blocks_release(app): - """任一角色批准后标签不可变化,且旧 Schema 批次不能给新 Schema 的执行放行。""" - with app.app_context(): - user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-FREEZE') - user.role = 'admin' - second = User(username='quality-freeze-second', email='quality-freeze-second@example.com', role='admin', password_hash='x') - db.session.add(second) - db.session.flush() - batch = _quality_batch(owner, 1, user) - runs = [] - for index in range(100): - run = ShippingOrderExtractionRun( - run_no=f'SNER-FREEZE-{index:03d}', user_id=user.id, owner_agent_id=owner.id, - conversation_id=f'freeze-{index}', schema_version_id=batch.schema_version_id, - input_snapshot_hash=f'{index + 4000:064x}'[-64:], input_snapshot_json={}, - idempotency_key=f'{index + 5000:064x}'[-64:], status='completed', phase='completed', - provider_config_json={'auto_create_enabled': False}, - ) - db.session.add(run) - runs.append(run) - db.session.flush() - _add_agreed_samples(batch, runs, user, second) - batch.status = 'ready' - db.session.flush() - approve_quality_batch(batch_id=batch.id, role='business', actor_id=user.id) - - with pytest.raises(ConflictError) as frozen: - save_quality_label( - batch_id=batch.id, run_no=runs[0].run_no, actor_id=second.id, - payload={'core_expected_count': 5, 'core_extracted_count': 5, 'core_correct_count': 5}, - ) - with pytest.raises(ConflictError): - require_approved_quality_batch( - batch_id=batch.id, owner_agent_id=owner.id, - schema_version_id=batch.schema_version_id + 1, - ) - - assert frozen.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_IMMUTABLE' - - -def test_approved_batch_is_listed_and_frozen_on_run(app): - """管理端候选只含当前 Schema 已批准批次,启用后 Run 必须冻结相同批次。""" - with app.app_context(): - user, owner, session, intake, _document = _seed_run_input(suffix='QUALITY-RUN') - business = User(username='quality-run-business', email='quality-run-business@example.com', role='admin', password_hash='x') - technical = User(username='quality-run-technical', email='quality-run-technical@example.com', role='admin', password_hash='x') - db.session.add_all([business, technical]) - db.session.flush() - batch = _quality_batch(owner, 1, user) - runs = [] - for index in range(100): - run = ShippingOrderExtractionRun( - run_no=f'SNER-RUN-GATE-{index:03d}', user_id=user.id, owner_agent_id=owner.id, - conversation_id=f'run-gate-{index}', schema_version_id=batch.schema_version_id, - input_snapshot_hash=f'{index + 6000:064x}'[-64:], input_snapshot_json={}, - idempotency_key=f'{index + 7000:064x}'[-64:], status='completed', phase='completed', - provider_config_json={'auto_create_enabled': False}, - ) - db.session.add(run) - runs.append(run) - db.session.flush() - _add_agreed_samples(batch, runs, business, technical) - batch.status = 'ready' - db.session.flush() - approve_quality_batch(batch_id=batch.id, role='business', actor_id=business.id) - approve_quality_batch(batch_id=batch.id, role='technical', actor_id=technical.id) - binding = Agent.query.filter_by(exposure_mode='internal').first() - save_runtime_binding( - owner_agent_id=owner.id, capability_code='shipping.order_extraction', - provider_agent_id=binding.id, enabled=True, quality_batch_id=batch.id, - config={'auto_create_enabled': True}, - ) - schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one() - schema.auto_creation_policy_json = {'enabled': True} - db.session.commit() - - listed = list_approved_quality_batches(owner_agent_id=owner.id) - run, reused = create_order_extraction_run( - user=user, agent_id=owner.id, conversation_id=session.session_id, - intake_nos=[intake.intake_no], - ) - - assert reused is False - assert [item['id'] for item in listed] == [batch.id] - assert run.quality_batch_id == batch.id - assert run.provider_config_json['auto_create_enabled'] is True - - db.session.commit() - batch.threshold_version = 'obsolete-threshold' - db.session.commit() - job = claim_next_job( - domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], - worker_id='quality-gate-worker', - ) - run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id}) - - db.session.refresh(run) - assert run.status == 'failed' - assert run.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_GATE_BLOCKED' - - -def test_disabled_schema_keeps_runtime_auto_create_binding_in_shadow_mode(app): - """质量批次已配置时,Schema 总开关关闭仍可创建影子 Run,且不得触发自动建单。""" - with app.app_context(): - user, owner, session, intake, _document = _seed_run_input(suffix='QUALITY-SHADOW') - provider = Agent.query.filter_by(exposure_mode='internal').first() - binding = AgentRuntimeBinding.query.filter_by( - owner_agent_id=owner.id, capability_code='shipping.order_extraction', - ).one() - binding.config_json = {'timeout_seconds': 900, 'max_attempts': 3, 'auto_create_enabled': True} - binding.provider_agent_id = provider.id - # The missing quality batch is intentional: schema-disabled execution is shadow-only. - binding.quality_batch_id = None - db.session.commit() - - run, reused = create_order_extraction_run( - user=user, agent_id=owner.id, conversation_id=session.session_id, - intake_nos=[intake.intake_no], - ) - - assert reused is False - assert run.provider_config_json['auto_create_enabled'] is False - assert run.input_snapshot_json['auto_creation_policy']['schema_enabled'] is False - assert run.input_snapshot_json['auto_creation_policy']['runtime_binding_enabled'] is True - -def test_quality_batch_admin_api_is_protected_and_returns_safe_summary(app, client): - """质量批次列表仅管理员可读,且响应不暴露 Run、字段值、引文或单条标签。""" - with app.app_context(): - user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-API') - user.role = 'admin' - db.session.flush() - token = issue_local_access_token(user) - db.session.commit() - owner_id = owner.id - admin_username = user.username - - forbidden = client.get( - f'/api/admin/shipping-notice/order-extraction-quality-batches?owner_agent_id={owner_id}', - headers={'X-Username': 'missing-quality-user', 'X-Role': 'user'}, - ) - auth = {'Authorization': f'Bearer {token}'} - created = client.post( - '/api/admin/shipping-notice/order-extraction-quality-batches', - json={'owner_agent_id': owner_id, 'schema_version_id': 1}, - headers=auth, - ) - listed = client.get( - f'/api/admin/shipping-notice/order-extraction-quality-batches?owner_agent_id={owner_id}', - headers=auth, - ) - - assert forbidden.status_code in {401, 403} - assert created.status_code == 201 - created_data = parse_api_data(created.get_json()) - assert created_data['status'] == 'collecting' - assert listed.status_code == 200 - assert parse_api_data(listed.get_json()) == [] - serialized = str(created.get_json()).lower() - assert all(key not in serialized for key in ('document', 'quote', 'orders', 'evidence_ref', 'cell_id', 'labels')) + except Exception as exc: + assert getattr(exc, 'code', None) == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_RUN_INVALID' + else: + raise AssertionError('auto-creation run must be rejected') diff --git a/backend/tests/test_shipping_order_extraction_quality_migration.py b/backend/tests/test_shipping_order_extraction_quality_migration.py index 66ee0631..7774d235 100644 --- a/backend/tests/test_shipping_order_extraction_quality_migration.py +++ b/backend/tests/test_shipping_order_extraction_quality_migration.py @@ -1,9 +1,9 @@ """ backend/tests/test_shipping_order_extraction_quality_migration.py -用途:验证 L7 质量批次/标签和 Runtime Binding 引用迁移可完整往返。 +用途:验证 L7 质量批次/标签迁移可完整往返。 依赖:Alembic Operations、SQLite 内存数据库、a71f8091a2b7 迁移。 -逻辑:构造最小父表,升级检查表/列/索引,降级确认完全移除。 +逻辑:构造最小父表,升级检查表/索引,降级确认完全移除。 """ from __future__ import annotations @@ -16,7 +16,7 @@ from alembic.operations import Operations def test_order_extraction_quality_migration_round_trip(monkeypatch): - """质量表和 Binding 外键必须可独立升级、写入并完整降级。""" + """质量表必须可独立升级、写入并完整降级。""" migration = importlib.import_module( 'migrations.versions.a71f8091a2b7_add_order_extraction_quality_gate', ) @@ -24,11 +24,6 @@ def test_order_extraction_quality_migration_round_trip(monkeypatch): metadata = sa.MetaData() for name in ('agents', 'users', 'shipping_order_schema_versions', 'shipping_order_extraction_runs'): sa.Table(name, metadata, sa.Column('id', sa.Integer(), primary_key=True)) - sa.Table( - 'agent_runtime_bindings', metadata, - sa.Column('id', sa.Integer(), primary_key=True), - sa.Column('owner_agent_id', sa.Integer()), - ) metadata.create_all(engine) with engine.begin() as connection: operations = Operations(MigrationContext.configure(connection)) @@ -38,14 +33,8 @@ def test_order_extraction_quality_migration_round_trip(monkeypatch): inspector = sa.inspect(connection) assert 'shipping_order_extraction_quality_batches' in inspector.get_table_names() assert 'shipping_order_extraction_quality_labels' in inspector.get_table_names() - assert 'quality_batch_id' in { - item['name'] for item in inspector.get_columns('agent_runtime_bindings') - } migration.downgrade() inspector = sa.inspect(connection) assert 'shipping_order_extraction_quality_batches' not in inspector.get_table_names() assert 'shipping_order_extraction_quality_labels' not in inspector.get_table_names() - assert 'quality_batch_id' not in { - item['name'] for item in inspector.get_columns('agent_runtime_bindings') - } diff --git a/backend/tests/test_shipping_order_extraction_run_quality_migration.py b/backend/tests/test_shipping_order_extraction_run_quality_migration.py index ec2e4722..a5744b42 100644 --- a/backend/tests/test_shipping_order_extraction_run_quality_migration.py +++ b/backend/tests/test_shipping_order_extraction_run_quality_migration.py @@ -46,42 +46,3 @@ def test_order_extraction_run_quality_migration_round_trip(monkeypatch): migration.downgrade() inspector = sa.inspect(connection) - assert 'quality_batch_id' not in { - item['name'] for item in inspector.get_columns('shipping_order_extraction_runs') - } - - -def test_quality_binding_migration_round_trip(monkeypatch): - """Binding 与 Run 的质量批次引用必须一起升级和完整降级。""" - migration = importlib.import_module( - 'migrations.versions.a77f8091a2c3_add_order_extraction_quality_binding', - ) - engine = sa.create_engine('sqlite:///:memory:') - metadata = sa.MetaData() - sa.Table( - 'shipping_order_extraction_quality_batches', metadata, - sa.Column('id', sa.Integer(), primary_key=True), - ) - for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'): - sa.Table(table_name, metadata, sa.Column('id', sa.Integer(), primary_key=True)) - metadata.create_all(engine) - with engine.begin() as connection: - operations = Operations(MigrationContext.configure(connection)) - monkeypatch.setattr(migration, 'op', operations) - - migration.upgrade() - inspector = sa.inspect(connection) - for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'): - assert 'quality_batch_id' in { - item['name'] for item in inspector.get_columns(table_name) - } - assert f'ix_{table_name}_quality_batch_id' in { - item['name'] for item in inspector.get_indexes(table_name) - } - - migration.downgrade() - inspector = sa.inspect(connection) - for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'): - assert 'quality_batch_id' not in { - item['name'] for item in inspector.get_columns(table_name) - } diff --git a/backend/tests/test_shipping_order_extraction_runs.py b/backend/tests/test_shipping_order_extraction_runs.py index dcabcd4e..0bcaffc2 100644 --- a/backend/tests/test_shipping_order_extraction_runs.py +++ b/backend/tests/test_shipping_order_extraction_runs.py @@ -12,6 +12,7 @@ from datetime import datetime, timedelta from unittest.mock import patch import pytest +from sqlalchemy.orm.attributes import flag_modified from app import db from app.core.auth.jwt import issue_local_access_token @@ -24,14 +25,17 @@ from app.models import ( ShippingNoticeDocument, ShippingNoticeIntake, ShippingNoticeCandidate, + ShippingTask, ShippingDocumentLayoutVersion, Job, ShippingOrderExtraction, ShippingOrderFieldObservation, ShippingOrderExtractionDiagnosticAudit, ShippingOrderExtractionPlan, + ShippingOrderExtractionProgressEvent, ShippingOrderExtractionRouteDecision, ShippingOrderExtractionRun, + ShippingOrderExtractionRunIntake, ShippingOrderExtractionUnit, ShippingOrderDocumentProfile, ShippingOrderSchema, @@ -50,7 +54,9 @@ from app.services.shipping_notice.order_extraction_run_service import ( ) from app.services.shipping_notice.order_extraction import submit_order_extraction_run_result from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit +from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan_batch from app.services.shipping_notice.order_extraction_workflow import route_deterministic_unit +from tests.test_shipping_notice_order_extraction import _ensure_order_schema, _order def test_route_decision_is_immutable_per_unit_job_attempt_and_cascades_with_run(app): @@ -204,16 +210,22 @@ def _seed_run_input( return user, agent, session, intake, document -def test_create_run_freezes_document_and_schema_and_is_idempotent(app): - """相同业务输入重复创建只产生一个 queued Run,且快照包含正文和 Schema checksum。""" +def test_create_run_freezes_lightweight_input_without_sync_materialization(app): + """点击发送只冻结快览计划并入队,绝不能在 HTTP 请求内读取附件或创建 Document。""" with app.app_context(): user, agent, session, intake, document = _seed_run_input() - run, reused = create_order_extraction_run( - user=user, - agent_id=agent.id, - conversation_id=session.session_id, - intake_nos=[intake.intake_no], - ) + db.session.delete(document) + db.session.commit() + with patch( + 'app.services.shipping_notice.order_extraction_run_service.ensure_order_extraction_input_documents', + ) as materialize: + run, reused = create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + materialize.assert_not_called() db.session.commit() assert reused is False @@ -222,21 +234,148 @@ def test_create_run_freezes_document_and_schema_and_is_idempotent(app): assert intake.order_extraction_status == 'extracting' assert run.input_snapshot_json['schema']['checksum'] == 'a' * 64 assert run.input_snapshot_json['schema']['extraction_contract']['fields'][0]['field_id'] == 'qty-id' - assert run.input_snapshot_json['snapshot_version'] == 3 - assert run.input_snapshot_json['intakes'][0]['documents'][0]['document_id'] == document.id - assert run.input_snapshot_json['intakes'][0]['documents'][0]['extracted_text'] == 'PO 451883815A QTY 30 EA' + assert run.input_snapshot_json['intakes'][0]['documents'] == [] + # 请求锚点在入队后保持轻量快照,Worker 物化执行证据不能改变其幂等与审计含义。 + assert run.request_snapshot_hash == run.input_snapshot_hash + assert run.request_snapshot_json == run.input_snapshot_json # 确定性上下文保留在HXOPS冻结快照;Workflow编译时才从documents强制剔除。 assert run.input_snapshot_json['intakes'][0]['deterministic_context'] == { 'from_email': 'sales-a@example.com', 'from_domain': 'example.com', } + + +def test_worker_materialization_preserves_request_snapshot_on_retry(app): + """Worker 重试可复用执行计划,但不得改写发送时的请求快照与幂等审计锚点。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='REQUEST-SNAPSHOT') + run, _ = create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + request_hash = run.request_snapshot_hash + request_snapshot = dict(run.request_snapshot_json or {}) + + from app.services.shipping_notice.order_extraction_run_service import materialize_order_extraction_run_inputs + + with patch('app.services.shipping_notice.order_extraction_run_service.ensure_order_extraction_input_documents'): + first_plan = materialize_order_extraction_run_inputs(run) + second_plan = materialize_order_extraction_run_inputs(run) + + assert first_plan.id == second_plan.id + assert run.request_snapshot_hash == request_hash + assert run.request_snapshot_json == request_snapshot + + +def test_create_run_rejects_an_intake_from_another_upload_batch(app): + """服务端必须拒绝伪造的跨批次 Intake 清单,不能依赖前端筛选。""" + with app.app_context(): + user, agent, session, first, _ = _seed_run_input(suffix='BATCH-FIRST') + second_asset = FileAsset( + asset_no='FA-RUN-BATCH-SECOND', owner_user_id=user.id, + original_filename='orders-second.pdf', storage_provider='minio', storage_bucket='test', + storage_key=f'temporary/{user.id}/orders-second.pdf', content_hash='b' * 64, + file_size=100, mime_type='application/pdf', upload_status='ready', lifecycle_status='temporary', + ) + db.session.add(second_asset) + db.session.flush() + second = ShippingNoticeIntake( + intake_no='SNI-RUN-BATCH-SECOND', asset_id=second_asset.id, user_id=user.id, + conversation_id=session.session_id, purpose='shipping_notice', parse_status='parsed', + parser_version='v6', extracted_text='second batch', expires_at=datetime.utcnow() + timedelta(hours=1), + ) + second.upload_batch_id = 'batch-second' + first.upload_batch_id = 'batch-first' + db.session.add(second) + db.session.commit() + + with pytest.raises(NotFoundError) as exc_info: + create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[first.intake_no, second.intake_no], + upload_batch_id='batch-first', + ) + + assert exc_info.value.code == 'SHIPPING_NOTICE.INTAKE_NOT_FOUND' + + +def test_create_run_rejects_input_larger_than_byte_budget(app): + """30MB 总预算按用户原始上传资产计费,发送前直接拒绝超额输入。""" + with app.app_context(): + user, agent, session, intake, _ = _seed_run_input(suffix='BYTE-BUDGET') + intake.upload_batch_id = 'byte-budget' + asset = db.session.get(FileAsset, intake.asset_id) + asset.file_size = 31 + db.session.commit() + app.config['SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_BYTES'] = 30 + + with pytest.raises(ConflictError) as exc_info: + create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, + intake_nos=[intake.intake_no], upload_batch_id='byte-budget', + ) + + assert exc_info.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_BUDGET_EXCEEDED' + + +def test_create_run_scopes_to_selected_intakes_only(app): + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='BATCH-A') + _, _agent2, _session2, intake2, _document2 = _seed_run_input( + suffix='BATCH-B', + agent_code='shipping_notice_batch_b', + ) + intake2.user_id = user.id + intake2.conversation_id = session.session_id + intake2.parse_status = 'parsed' + db.session.commit() + + run, _ = create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + db.session.commit() + + assert [item['intake_no'] for item in (run.input_snapshot_json.get('intakes') or [])] == [ + intake.intake_no, + ] + assert str(intake2.order_extraction_status or '').strip().lower() != 'extracting' plan = ShippingOrderExtractionPlan.query.filter_by(run_id=run.id).one() assert plan.plan_version == 'shipping_order_extraction.plan.v1' assert len(plan.plan_version) == 33 assert plan.input_snapshot_hash == run.input_snapshot_hash assert plan.status == 'planned' assert plan.unit_count == 1 + plan_event = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id, event_code='plan_created').one() + assert plan_event.summary_json == { + 'plan_version': 'shipping_order_extraction.plan.v1', + 'selection': { + 'budget_limited_attachment_count': 0, + 'duplicate_attachment_count': 0, + 'eligible_attachment_count': 0, + 'expansion_batch_size': 2, + 'group_count': 0, + 'max_initial_attachments': 2, + 'max_initial_concurrency': 2, + 'max_total_attachments': 6, + 'pending_expansion_attachment_count': 0, + 'pending_expansion_batches': {}, + 'planned_attachment_count': 0, + 'selected_attachment_count': 0, + 'selection_version': 'shipping_notice_attachment_selection.v1', + 'skipped_attachment_count': 0, + 'total_attachment_count': 0, + }, + 'unit_count': 1, + } unit = ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id).one() - assert unit.document_id == document.id + assert unit.document_id == frozen_document['document_id'] + assert unit.document_id != document.id assert unit.intake_id == intake.id assert unit.unit_type == 'document_extraction' assert unit.status == 'pending' @@ -255,8 +394,8 @@ def test_create_run_freezes_document_and_schema_and_is_idempotent(app): @pytest.mark.parametrize('layout_status', ['queued', 'running']) -def test_create_run_waits_for_active_document_layout_before_freezing_snapshot(app, layout_status): - """未终态 Layout 必须先完成,避免新 Run 永久冻结空快照而错过确定性模板。""" +def test_create_run_allows_active_document_layout_and_defers_runtime_fallback(app, layout_status): + """布局未 ready 时仍允许建 Run;冻结快照保持空 layout,执行期再补读当前 ready 版本。""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix=f'LAYOUT-{layout_status.upper()}') db.session.add(ShippingDocumentLayoutVersion( @@ -271,14 +410,16 @@ def test_create_run_waits_for_active_document_layout_before_freezing_snapshot(ap )) db.session.commit() - with pytest.raises(ConflictError) as exc_info: - create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, - intake_nos=[intake.intake_no.upper()], - ) + run, reused = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, + intake_nos=[intake.intake_no.upper()], + ) + db.session.commit() - assert exc_info.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PENDING' - assert ShippingOrderExtractionRun.query.count() == 0 + assert reused is False + assert run.status == 'queued' + assert run.input_snapshot_json['intakes'][0]['documents'][0]['layout_snapshot'] is None + assert ShippingOrderExtractionRun.query.count() == 1 def test_deterministic_route_reports_no_layout_table_not_multiple_tables(app): @@ -293,7 +434,7 @@ def test_deterministic_route_reports_no_layout_table_not_multiple_tables(app): route = route_deterministic_unit(run, unit=run.extraction_plan.units[0]) assert route.execution_mode == 'review_required' - assert route.decision['fallback_reason_codes'] == ['no_layout_table'] + assert route.decision['fallback_reason_codes'] == ['business_table_not_found'] def test_run_freezes_manual_auto_freeze_policy(app): @@ -446,12 +587,10 @@ def test_run_plan_creates_only_attachment_units_and_keeps_email_as_frozen_supple units = ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id).order_by( ShippingOrderExtractionUnit.position.asc() ).all() - assert [unit.document_id for unit in units] == [attachment.id] - assert {unit.document_id: unit.unit_type for unit in units} == { - attachment.id: 'document_extraction', - } + assert len(units) == 1 + assert units[0].document_id != body.id + assert units[0].unit_type == 'document_extraction' assert plan.unit_count == 1 - assert any(item['document_id'] == body.id for item in run.input_snapshot_json['intakes'][0]['documents']) assert all(unit.result_json is None and unit.error_code is None for unit in units) @@ -478,27 +617,117 @@ def test_plan_unit_state_machine_is_local_and_rolls_up_partial_failure(app): plan = ShippingOrderExtractionPlan.query.filter_by(run_id=run.id).one() units = list(plan.units) - transition_order_extraction_unit(units[0], target_status='running') + transition_order_extraction_unit(units[0], target_status='routing') + transition_order_extraction_unit(units[0], target_status='matching_profile') + transition_order_extraction_unit(units[0], target_status='extracting') transition_order_extraction_unit( - units[0], target_status='succeeded', result={'orders': [{'key': 'A'}]}, + units[0], target_status='candidate_ready', result={'orders': [{'key': 'A'}]}, ) - transition_order_extraction_unit(units[1], target_status='running') + transition_order_extraction_unit(units[1], target_status='routing') transition_order_extraction_unit( units[1], target_status='failed', error_code='UNIT_TIMEOUT', error_message='timeout', ) assert plan.status == 'partial_failed' assert units[0].result_json == {'orders': [{'key': 'A'}]} - assert units[0].status == 'succeeded' - assert units[1].status == 'failed' - assert units[1].error_code == 'UNIT_TIMEOUT' - with pytest.raises(ConflictError) as caught: - transition_order_extraction_unit(units[0], target_status='running') - assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_TRANSITION_INVALID' + assert units[0].status == 'candidate_ready' - transition_order_extraction_unit(units[1], target_status='pending') - assert plan.status == 'running' - assert units[0].result_json == {'orders': [{'key': 'A'}]} + +def test_plan_can_append_future_selection_batch_units_idempotently(app): + """未来批次附件完成物化后,可按冻结选择计划追加 unit,且重复追加不重复建单元。""" + with app.app_context(): + user, agent, session, intake, first_document = _seed_run_input(suffix='BATCH2') + first_document.attachment_key = 'att-1' + second_document = ShippingNoticeDocument( + intake_id=intake.id, + document_type='attachment', + attachment_key='att-2', + filename='orders-batch-2.pdf', + content_hash='d' * 64, + classification='order_notice', + parse_status='parsed', + extracted_text='PO 451883816 BATCH TWO', + ) + db.session.add(second_document) + db.session.flush() + + schema_version = ShippingOrderSchemaVersion.query.filter_by(status='published').first() + run = ShippingOrderExtractionRun( + run_no='SNER-BATCH2', + user_id=user.id, + owner_agent_id=agent.id, + conversation_id=session.session_id, + schema_version_id=schema_version.id, + input_snapshot_hash='f' * 64, + idempotency_key='batch2-idempotency', + input_snapshot_json={ + 'snapshot_version': 3, + 'schema': {'definition': schema_version.definition_json, 'checksum': schema_version.checksum}, + 'intakes': [{ + 'intake_id': intake.id, + 'intake_no': intake.intake_no, + 'documents': [{ + 'document_id': first_document.id, + 'document_type': first_document.document_type, + 'attachment_key': 'att-1', + 'content_hash': first_document.content_hash, + }], + }], + 'attachment_selection': { + 'max_initial_attachments': 2, + 'max_initial_concurrency': 2, + 'expansion_batch_size': 2, + 'max_total_attachments': 6, + 'items': [ + { + 'intake_no': intake.intake_no, + 'attachment_key': 'att-1', + 'selected': True, + 'selection_batch': 1, + 'score_reasons': ['filename_po_hint'], + 'group_key': '451883815A', + }, + { + 'intake_no': intake.intake_no, + 'attachment_key': 'att-2', + 'selected': False, + 'planned_selection_batch': 2, + 'score_reasons': ['filename_po_hint'], + 'group_key': '451883816', + }, + ], + }, + }, + status='queued', + phase='queued', + ) + db.session.add(run) + db.session.flush() + db.session.add(ShippingOrderExtractionRunIntake(run_id=run.id, intake_id=intake.id, position=0)) + db.session.commit() + + plan = ShippingOrderExtractionPlan.query.filter_by(run_id=run.id).first() + if plan is None: + from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan + plan = ensure_order_extraction_plan(run) + db.session.commit() + + created = ensure_order_extraction_plan_batch(run, selection_batch=2) + db.session.commit() + + assert len(created) == 1 + plan = ShippingOrderExtractionPlan.query.filter_by(run_id=run.id).one() + units = ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id).order_by(ShippingOrderExtractionUnit.position.asc()).all() + assert [unit.selection_batch for unit in units] == [1, 2] + assert units[1].document_id == second_document.id + assert units[1].group_key == '451883816' + assert units[1].budget_cost_json['expansion_batch_size'] == 2 + assert units[1].budget_cost_json['selected_in_batch'] == 1 + + repeated = ensure_order_extraction_plan_batch(run, selection_batch=2) + db.session.commit() + assert repeated == [] + assert ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id).count() == 2 def test_run_submission_rejects_changed_frozen_mail_context(app): @@ -518,6 +747,149 @@ def test_run_submission_rejects_changed_frozen_mail_context(app): assert caught.value.code == 'SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED' +def test_run_submission_auto_freezes_qualified_tasks(app): + """Run 命中已授权模板后,应自动消费 accepted Candidate 并冻结为履约 Snapshot。""" + with app.app_context(): + from app.models import ShippingCustomer, ShippingDocumentProfileAutoFreezeQualification, ShippingOrderCustomerMatch + from app.services.shipping_notice.fulfillment_policy_registry import create_draft, publish + from tests.test_shipping_order_auto_freeze_policy import _published_profile + + fields = _ensure_order_schema() + user, agent, session, intake, document = _seed_run_input(suffix='AUTO-FREEZE-EXEC') + document.extracted_text = 'PO 4510000001 SKU SKU-A QTY 10 1000140351 AWS Dublin' + db.session.commit() + run, _ = create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + # 发送仅创建轻量 Run;深度证据与执行计划必须在 Worker 生命周期中物化。 + from app.services.shipping_notice.order_extraction_run_service import materialize_order_extraction_run_inputs + + with patch( + 'app.services.shipping_notice.order_extraction_run_service.ensure_order_extraction_input_documents', + ): + materialize_order_extraction_run_inputs(run) + frozen_document_payload = run.input_snapshot_json['intakes'][0]['documents'][0] + frozen_document = db.session.get(ShippingNoticeDocument, int(frozen_document_payload['document_id'])) + assert frozen_document is not None + # 该用例直接验证自动冻结闭环;显式把冻结快照证据文本对齐到本次提交的结构化订单引用。 + frozen_document.extracted_text = document.extracted_text + frozen_document.classification = 'order_notice' + frozen_document_payload['extracted_text'] = document.extracted_text + frozen_document_payload['classification'] = 'order_notice' + flag_modified(run, 'input_snapshot_json') + db.session.commit() + unit = run.extraction_plan.units[0] + job = db.session.get(Job, run.current_job_id) + profile = _published_profile(schema_version_id=run.schema_version_id, checksum='e' * 64) + policy_draft = create_draft({ + 'field_bindings': [ + {'capability_code': 'fulfillment.reservation_identity', 'field_id': fields['reservation_id']}, + {'capability_code': 'fulfillment.part_number', 'field_id': fields['part_number']}, + {'capability_code': 'fulfillment.quantity', 'field_id': fields['qty']}, + {'capability_code': 'routing.inventory_source_hint', 'field_id': fields['inventory_source_hint']}, + ], + }, actor_id=None) + publish(policy_draft['id'], actor_id=None, expected_lock_version=policy_draft['lock_version']) + customer = ShippingCustomer(standard_name='Freeze Customer', short_code='FRZ') + db.session.add(customer) + db.session.flush() + extraction = ShippingOrderExtraction( + run_id=run.id, + intake_id=intake.id, + schema_version_id=run.schema_version_id, + input_snapshot_hash=f'run-{run.id}-customer-{customer.id}', + input_snapshot_json={}, + status='accepted', + ) + db.session.add(extraction) + db.session.flush() + db.session.add(ShippingOrderCustomerMatch( + extraction_id=extraction.id, + role='bill_to', + identity_components_json={}, + status='confirmed', + customer_id=customer.id, + customer_name_snapshot=customer.standard_name, + customer_short_code_snapshot=customer.short_code, + identity_fingerprint=f'customer-{customer.id}', + identity_rule_version='customer-match.v1', + resolution_method='manual', + confirmed_at=datetime.utcnow(), + )) + db.session.add_all([ + ShippingDocumentProfileAutoFreezeQualification( + profile_id=profile.id, + profile_version=profile.version, + profile_checksum=profile.checksum, + schema_version_id=run.schema_version_id, + parser_version='deterministic-order-parser.v1', + status='auto_freeze_approved', + customer_ids_json=[customer.id], + business_scenarios_json=['shipping_notice_order'], + requires_customer_confirmation=False, + ), + ShippingOrderExtractionRouteDecision( + run_id=run.id, + unit_id=unit.id, + job_id=job.id, + attempt_no=1, + decision='deterministic', + match_status='unique_match', + selected_profile_id=profile.id, + selected_profile_code=profile.profile_code, + selected_profile_version=profile.version, + selected_profile_checksum=profile.checksum, + auto_create_approved=True, + candidate_count=1, + table_count=1, + document_table_count=1, + business_table_count=1, + matched_table_count=1, + parsed_table_count=1, + approved_table_count=1, + candidate_summary_json=[], + fallback_reason_codes_json=[], + ), + ]) + db.session.commit() + + order = _order( + intake_no=intake.intake_no, + document_id=int(frozen_document.id), + po_number='4510000001', + part_number='SKU-A', + qty=10, + include_process_fields=True, + ) + order['_hxops_acceptance'] = 'approved_deterministic_profile_v1' + order['header_fields'] = [{ + 'field_id': fields['po_number'], + 'observations': [{ + 'value': '4510000001', + 'quote': 'PO 4510000001', + 'document_id': int(frozen_document.id), + 'confidence': 0.99, + }], + }] + + result = submit_order_extraction_run_result(run=run, orders=[order]) + + candidate = ShippingNoticeCandidate.query.filter_by(order_extraction_run_id=int(run.id)).one() + task = db.session.get(ShippingTask, int(candidate.consumed_task_id)) + db.session.refresh(run) + + assert result['created_count'] == 1 + assert result['pending_count'] == 0 + assert result['auto_freeze']['enabled'] is True + assert result['auto_freeze']['blocked_tasks'] == [] + assert task is not None + assert task.order_snapshot_id is not None + assert run.auto_freeze_policy_json['enabled'] is True + + def test_active_run_blocks_different_snapshot_for_same_intake(app): """文档变化导致幂等键变化时,同一 Intake 的未释放 Run 仍必须阻断第二次创建。""" with app.app_context(): @@ -541,7 +913,7 @@ def test_active_run_blocks_different_intake_in_same_conversation(app): """同一会话只能有一个活动 Run,防止不同附件的状态卡和工作台事实并行串扰。""" with app.app_context(): user, agent, session, intake, _document = _seed_run_input(suffix='CONV-A') - _, _, _, second_intake, _ = _seed_run_input(suffix='CONV-B') + _, _, _, second_intake, _ = _seed_run_input(suffix='CONV-B', agent_code='shipping_notice_conv_b') second_intake.user_id = user.id second_intake.conversation_id = session.session_id db.session.commit() @@ -679,25 +1051,39 @@ def test_run_api_create_get_list_and_user_isolation(app, client): agent_id = agent.id session_id = session.session_id intake_no = intake.intake_no + intake.upload_batch_id = 'api-batch-a' + db.session.commit() response = client.post( '/api/workspace/shipping-notice/order-extraction-runs', - json={'agent_id': agent_id, 'conversation_id': session_id, 'intake_nos': [intake_no]}, + json={ + 'agent_id': agent_id, + 'conversation_id': session_id, + 'intake_nos': [intake_no], + 'upload_batch_id': 'api-batch-a', + }, headers={'Authorization': f'Bearer {owner_token}'}, ) assert response.status_code == 202 payload = response.get_json()['data'] assert payload['reused'] is False assert payload['run']['status'] == 'queued' - assert payload['run']['progress'] == { - 'version': 1, - 'current_stage_code': 'queued', - 'active_stage_codes': [], - 'completed_stage_codes': [], - 'message_code': None, - 'health': 'normal', - 'last_activity_at': None, + assert payload['run']['summary'] == { + 'total_documents': 1, + 'pending_documents': 1, + 'processing_documents': 0, + 'completed_documents': 0, + 'review_required_documents': 0, + 'failed_documents': 0, + 'candidate_count': 0, } + assert payload['run']['current_activity'] == { + 'unit_id': payload['run']['current_activity']['unit_id'], + 'file_name': 'orders-A.pdf', + 'event_code': 'document_queued', + } + assert payload['run']['available_actions'] == ['view_details'] + assert 'progress' not in payload['run'] assert 'input_snapshot_json' not in payload['run'] assert 'provider_snapshot_json' not in payload['run'] assert 'provider_result_json' not in payload['run'] @@ -712,7 +1098,12 @@ def test_run_api_create_get_list_and_user_isolation(app, client): replay = client.post( '/api/workspace/shipping-notice/order-extraction-runs', - json={'agent_id': agent_id, 'conversation_id': session_id, 'intake_nos': [intake_no]}, + json={ + 'agent_id': agent_id, + 'conversation_id': session_id, + 'intake_nos': [intake_no], + 'upload_batch_id': 'api-batch-a', + }, headers={'Authorization': f'Bearer {owner_token}'}, ) assert replay.status_code == 202 @@ -732,6 +1123,316 @@ def test_run_api_create_get_list_and_user_isolation(app, client): assert hidden.get_json()['error']['code'] == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND' +def test_run_api_requires_upload_batch_id(app, client): + """发送端缺少服务端上传批次时必须拒绝,不能回退为全会话 Intake 选择。""" + with app.app_context(): + owner, agent, session, intake, _document = _seed_run_input(suffix='API-BATCH-REQUIRED') + token = issue_local_access_token(owner) + payload = { + 'agent_id': agent.id, + 'conversation_id': session.session_id, + 'intake_nos': [intake.intake_no], + } + + response = client.post( + '/api/workspace/shipping-notice/order-extraction-runs', + json=payload, + headers={'Authorization': f'Bearer {token}'}, + ) + + assert response.status_code == 400 + assert response.get_json()['error']['code'] == 'SHIPPING_NOTICE.UPLOAD_BATCH_REQUIRED' + + +def test_run_documents_api_returns_pdf_results_and_keeps_cross_user_isolation(app, client): + """文档详情接口直接返回按 PDF 归并的结果,不暴露内部事件或路径字段。""" + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='DOCS-API') + schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one() + schema.definition_json = { + 'fields': [ + {'field_id': 'po-id', 'field_code': 'po_number', 'scope': 'header'}, + {'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line'}, + {'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line'}, + {'field_id': 'source-type-id', 'field_code': 'inventory_source_hint', 'scope': 'line'}, + ], + } + run, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], + ) + unit = run.extraction_plan.units[0] + unit.status = 'candidate_ready' + unit.result_json = { + 'orders': [{ + 'header_fields': [{'field_id': 'po-id', 'observations': [{'value': '450001'}]}], + 'lines': [ + {'fields': [ + {'field_id': 'reservation-id', 'observations': [{'value': 'R-001'}]}, + {'field_id': 'source-type-id', 'observations': [{'value': 'EMAIL'}]}, + ]}, + {'fields': []}, + ], + '_hxops_email_supplement_relation': 'po_mpn', + }], + } + db.session.add(ShippingOrderExtractionRouteDecision( + run_id=run.id, + unit_id=unit.id, + job_id=run.current_job_id, + attempt_no=1, + decision='deterministic', + match_status='unique_match', + selected_profile_code='vendor_a_po', + selected_profile_version=2, + candidate_count=1, + table_count=1, + approved_table_count=1, + candidate_summary_json=[], + fallback_reason_codes_json=[], + )) + db.session.add(ShippingOrderExtractionProgressEvent( + run_id=run.id, + unit_id=unit.id, + document_id=document.id, + job_id=run.current_job_id, + sequence_no=run.progress_version + 1, + visibility='workspace', + event_code='email_supplement_merged', + status='completed', + occurred_at=datetime.utcnow(), + received_at=datetime.utcnow(), + summary_json={'status': 'merged', 'relation_codes': ['po_mpn'], 'conflict_count': 0}, + idempotency_key='docs-api-email-merged', + mapping_version='shipping-order-progress-v2', + )) + other = User(username='docs-api-other', email='docs-api-other@example.com', password_hash='x') + db.session.add(other) + db.session.commit() + owner_token = issue_local_access_token(user) + other_token = issue_local_access_token(other) + run_no = run.run_no + + response = client.get( + f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/documents', + headers={'Authorization': f'Bearer {owner_token}'}, + ) + assert response.status_code == 200 + items = response.get_json()['data']['items'] + assert len(items) == 1 + assert items[0]['file_name'] == 'orders-DOCS-API.pdf' + assert items[0]['status'] == 'candidate_ready' + assert items[0]['po_number'] == '450001' + assert items[0]['line_count'] == 2 + assert items[0]['profile'] == {'code': 'vendor_a_po', 'name': 'vendor_a_po', 'version': 2} + assert items[0]['email_supplement'] == { + 'status': 'merged', + 'relation_codes': ['po_mpn'], + 'conflict_count': 0, + 'reservation_id_status': 'merged', + 'source_type_status': 'merged', + } + assert items[0]['reason_code'] is None + assert items[0]['available_actions'] == ['view_evidence', 'review_candidate'] + + hidden = client.get( + f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/documents', + headers={'Authorization': f'Bearer {other_token}'}, + ) + assert hidden.status_code == 404 + + +def test_run_documents_and_summary_keep_partial_success_isolated_per_pdf(app, client): + """同一 Run 中成功、业务复核和技术失败的 PDF 必须分别保留自己的结果与操作。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='DOCS-MIXED') + schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one() + schema.definition_json = { + 'fields': [ + {'field_id': 'po-id', 'field_code': 'po_number', 'scope': 'header'}, + {'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line'}, + {'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line'}, + {'field_id': 'source-type-id', 'field_code': 'inventory_source_hint', 'scope': 'line'}, + ], + } + extra_assets: list[FileAsset] = [] + extra_documents: list[ShippingNoticeDocument] = [] + for suffix in ['REVIEW', 'FAILED']: + asset = FileAsset( + asset_no=f'FA-DOCS-MIXED-{suffix}', + owner_user_id=user.id, + original_filename=f'orders-{suffix}.pdf', + storage_provider='minio', + storage_bucket='test', + storage_key=f'temporary/{user.id}/orders-{suffix}.pdf', + content_hash=(suffix.lower() * 64)[:64], + file_size=100, + mime_type='application/pdf', + upload_status='ready', + lifecycle_status='temporary', + ) + db.session.add(asset) + db.session.flush() + extra_assets.append(asset) + document = ShippingNoticeDocument( + intake_id=intake.id, + asset_id=asset.id, + document_type='attachment', + attachment_key=f'orders-{suffix}.pdf', + filename=f'orders-{suffix}.pdf', + content_hash=(suffix.upper() * 64)[:64], + classification='order_notice', + parse_status='parsed', + extracted_text=f'PO MIXED {suffix}', + ) + db.session.add(document) + db.session.flush() + extra_documents.append(document) + + run, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], + ) + units = sorted(run.extraction_plan.units, key=lambda item: int(item.document_id)) + success_unit, review_unit, failed_unit = units + run.status = 'partially_completed' + + success_unit.status = 'candidate_ready' + success_unit.result_json = { + 'orders': [{ + 'header_fields': [{'field_id': 'po-id', 'observations': [{'value': '450009'}]}], + 'lines': [{ + 'fields': [ + {'field_id': 'reservation-id', 'observations': [{'value': 'RSV-1'}]}, + ], + }], + '_hxops_email_supplement_relation': 'po_fallback', + }], + } + review_unit.status = 'review_required' + review_unit.reason_code = 'email_supplement_conflict' + review_unit.result_json = { + 'orders': [{ + 'header_fields': [{'field_id': 'po-id', 'observations': [{'value': '450010'}]}], + 'lines': [{'fields': []}], + '_hxops_email_supplement_relation': 'po_mpn', + 'conflicts': [{'reason': 'supplement_relation_ambiguous'}], + }], + } + failed_unit.status = 'failed' + failed_unit.reason_code = None + failed_unit.result_json = {'orders': []} + + db.session.add(ShippingOrderExtractionRouteDecision( + run_id=run.id, + unit_id=success_unit.id, + job_id=run.current_job_id, + attempt_no=1, + decision='deterministic', + match_status='unique_match', + selected_profile_code='vendor_a_po', + selected_profile_version=2, + candidate_count=1, + table_count=1, + approved_table_count=1, + candidate_summary_json=[], + fallback_reason_codes_json=[], + )) + db.session.add(ShippingOrderExtractionProgressEvent( + run_id=run.id, + unit_id=success_unit.id, + document_id=success_unit.document_id, + job_id=run.current_job_id, + sequence_no=( + db.session.query(ShippingOrderExtractionProgressEvent.sequence_no) + .filter_by(run_id=run.id) + .order_by(ShippingOrderExtractionProgressEvent.sequence_no.desc()) + .first()[0] + 1 + ), + visibility='workspace', + event_code='email_supplement_merged', + status='completed', + occurred_at=datetime.utcnow(), + received_at=datetime.utcnow(), + summary_json={'status': 'merged', 'relation_codes': ['po_fallback'], 'conflict_count': 0}, + idempotency_key='docs-mixed-email-success', + mapping_version='shipping-order-progress-v2', + )) + db.session.add(ShippingOrderExtractionProgressEvent( + run_id=run.id, + unit_id=review_unit.id, + document_id=review_unit.document_id, + job_id=run.current_job_id, + sequence_no=2, + visibility='workspace', + event_code='email_supplement_merged', + status='completed', + occurred_at=datetime.utcnow(), + received_at=datetime.utcnow(), + summary_json={'status': 'conflict', 'relation_codes': ['po_mpn'], 'conflict_count': 1}, + idempotency_key='docs-mixed-email-conflict', + mapping_version='shipping-order-progress-v2', + )) + db.session.commit() + owner_token = issue_local_access_token(user) + run_no = run.run_no + + run_response = client.get( + f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}', + headers={'Authorization': f'Bearer {owner_token}'}, + ) + assert run_response.status_code == 200 + run_payload = run_response.get_json()['data'] + assert run_payload['summary'] == { + 'total_documents': 3, + 'pending_documents': 0, + 'processing_documents': 0, + 'completed_documents': 1, + 'review_required_documents': 1, + 'failed_documents': 1, + 'candidate_count': 1, + } + assert run_payload['available_actions'] == ['view_details', 'enter_manual_review', 'retry_failed_attachments'] + assert run_payload['current_activity'] is None + + response = client.get( + f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/documents', + headers={'Authorization': f'Bearer {owner_token}'}, + ) + assert response.status_code == 200 + items = response.get_json()['data']['items'] + assert [item['file_name'] for item in items] == [ + 'orders-DOCS-MIXED.pdf', + 'orders-REVIEW.pdf', + 'orders-FAILED.pdf', + ] + # 关键断言:部分成功时,成功 PDF 仍保留自己的确认操作,不被其他失败文档吞掉。 + assert items[0]['available_actions'] == ['view_evidence', 'review_candidate'] + assert items[0]['email_supplement'] == { + 'status': 'merged', + 'relation_codes': ['po_fallback'], + 'conflict_count': 0, + 'reservation_id_status': 'merged', + 'source_type_status': 'none', + } + assert items[1]['reason_code'] == 'email_supplement_conflict' + assert items[1]['available_actions'] == ['view_evidence', 'manual_review'] + assert items[1]['email_supplement'] == { + 'status': 'conflict', + 'relation_codes': ['po_mpn'], + 'conflict_count': 1, + 'reservation_id_status': 'conflict', + 'source_type_status': 'conflict', + } + assert items[2]['reason_code'] == 'technical_failure' + assert items[2]['available_actions'] == [] + assert items[2]['email_supplement'] == { + 'status': 'none', + 'relation_codes': [], + 'conflict_count': 0, + 'reservation_id_status': 'none', + 'source_type_status': 'none', + } + + def test_run_progress_events_api_returns_only_generic_stages(app, client): """用户进度明细只返回通用阶段、状态和时间,且继续执行 Run 所有权隔离。""" from app.models import ShippingOrderExtractionProgressEvent @@ -746,16 +1447,23 @@ def test_run_progress_events_api_returns_only_generic_stages(app, client): db.session.add(other) db.session.add(ShippingOrderExtractionProgressEvent( run_id=run.id, + unit_id=run.extraction_plan.units[0].id, + document_id=run.extraction_plan.units[0].document_id, job_id=run.current_job_id, - workflow_run_id='wf-secret', - node_execution_id='node-secret', - event_type='node_started', - node_type='llm', - stage_code='order_recognition', - event_status='running', + sequence_no=( + db.session.query(ShippingOrderExtractionProgressEvent.sequence_no) + .filter_by(run_id=run.id) + .order_by(ShippingOrderExtractionProgressEvent.sequence_no.desc()) + .first()[0] + 1 + ), + visibility='workspace', + event_code='profile_matching', + status='completed', + occurred_at=datetime.utcnow(), received_at=datetime.utcnow(), - details_json={'source': 'dify_workflow_observer'}, + summary_json={'source': 'deterministic'}, idempotency_key='progress-api-key', + mapping_version='shipping-order-progress-v2', )) db.session.commit() owner_token = issue_local_access_token(owner) @@ -769,9 +1477,9 @@ def test_run_progress_events_api_returns_only_generic_stages(app, client): assert response.status_code == 200 items = response.get_json()['data']['items'] assert len(items) == 1 - assert set(items[0]) == {'stage_code', 'status', 'occurred_at'} - assert items[0]['stage_code'] == 'order_recognition' - assert items[0]['status'] == 'running' + assert set(items[0]) == {'event_code', 'status', 'unit_id', 'document_id', 'reason_code', 'summary', 'occurred_at'} + assert items[0]['event_code'] == 'profile_matching' + assert items[0]['status'] == 'completed' assert 'secret' not in str(items).lower() hidden = client.get( @@ -781,23 +1489,15 @@ def test_run_progress_events_api_returns_only_generic_stages(app, client): assert hidden.status_code == 404 -def test_run_progress_health_is_computed_server_side(app): - """用户摘要按最后活动时间投影 idle/slow,不信任浏览器本地时间或前端状态。""" +def test_run_summary_omits_legacy_progress_projection(app): + """新的用户态 Run 摘要不再暴露 progress/health 旧字段。""" with app.app_context(): user, agent, session, intake, _document = _seed_run_input(suffix='PROGRESS-HEALTH') run, _ = create_order_extraction_run( user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - now = datetime.utcnow() - run.status = 'running' - run.last_activity_at = now - timedelta(seconds=60) - assert serialize_order_extraction_run(run)['progress']['health'] == 'idle' - - run.last_activity_at = now - timedelta(seconds=180) - assert serialize_order_extraction_run(run)['progress']['health'] == 'slow' - - run.status = 'completed' - assert serialize_order_extraction_run(run)['progress']['health'] == 'normal' + payload = serialize_order_extraction_run(run) + assert 'progress' not in payload def test_user_run_summary_never_exposes_worker_error_text(app): @@ -807,7 +1507,7 @@ def test_user_run_summary_never_exposes_worker_error_text(app): run, _ = create_order_extraction_run( user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - transition_order_extraction_run(run, target_status='running') + transition_order_extraction_run(run, target_status='processing') transition_order_extraction_run( run, target_status='failed', @@ -820,7 +1520,9 @@ def test_user_run_summary_never_exposes_worker_error_text(app): assert 'confidential document fragment' not in str(payload) message_state = serialize_order_extraction_message_state(run) - assert message_state['message'] == '' + assert message_state['status'] == 'failed' + assert message_state['summary']['failedDocuments'] == 0 + assert message_state['availableActions'] == ['view_details', 'retry_failed_attachments'] assert 'confidential document fragment' not in str(message_state) @@ -843,7 +1545,7 @@ def test_terminal_run_attention_is_new_only_seen_idempotently_and_resets_on_retr assert mark_order_extraction_run_seen(user_id=user.id, run_no=historical.run_no) is False assert historical.attention_generated_at is None - transition_order_extraction_run(run, target_status='running') + transition_order_extraction_run(run, target_status='processing') transition_order_extraction_run(run, target_status='failed', error_message='provider unavailable') assert run.attention_generated_at is not None assert run.seen_at is None @@ -857,8 +1559,7 @@ def test_terminal_run_attention_is_new_only_seen_idempotently_and_resets_on_retr retried, _ = retry_order_extraction_run(user_id=user.id, run_no=run.run_no) assert retried.attention_generated_at is None assert retried.seen_at is None - transition_order_extraction_run(retried, target_status='running') - transition_order_extraction_run(retried, target_status='result_persisted', result={}) + transition_order_extraction_run(retried, target_status='processing') transition_order_extraction_run(retried, target_status='completed') assert retried.attention_generated_at is not None assert retried.seen_at is None @@ -871,8 +1572,7 @@ def test_run_seen_api_keeps_cross_user_isolation(app, client): run, _ = create_order_extraction_run( user=owner, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - transition_order_extraction_run(run, target_status='running') - transition_order_extraction_run(run, target_status='result_persisted', result={}) + transition_order_extraction_run(run, target_status='processing') transition_order_extraction_run(run, target_status='completed') other = User(username='seen-other', email='seen-other@example.com', password_hash='x') db.session.add(other) @@ -914,7 +1614,7 @@ def test_chat_sessions_aggregate_only_new_unseen_order_extraction_attention(app) run, _ = create_order_extraction_run( user=owner, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - transition_order_extraction_run(run, target_status='running') + transition_order_extraction_run(run, target_status='processing') transition_order_extraction_run(run, target_status='failed', error_message='provider unavailable') historical = ShippingOrderExtractionRun( run_no='SNER-HISTORICAL-SESSION', user_id=owner.id, owner_agent_id=agent.id, @@ -949,7 +1649,7 @@ def test_failed_run_retry_reuses_snapshot_and_execution_result(app): original_job_id = run.current_job_id frozen_snapshot = run.input_snapshot_json run.execution_result_json = {'orders': [], 'execution': {'mode': 'deterministic'}} - transition_order_extraction_run(run, target_status='running', phase='deterministic_parsing') + transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing') transition_order_extraction_run( run, target_status='failed', error_code='TEST.FAILED', error_message='failed once', ) @@ -1010,7 +1710,7 @@ def test_run_retry_rejects_obsolete_frozen_snapshot(app): snapshot['intakes'] = [dict(item) for item in snapshot['intakes']] snapshot['intakes'][0].pop('deterministic_context') run.input_snapshot_json = snapshot - transition_order_extraction_run(run, target_status='running', phase='deterministic_parsing') + transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing') transition_order_extraction_run(run, target_status='failed', error_message='legacy snapshot') original_job_count = Job.query.filter_by(business_ref=run.run_no).count() db.session.commit() @@ -1045,7 +1745,7 @@ def test_terminal_transition_updates_persisted_chat_state(app): }, ) db.session.add(log) - transition_order_extraction_run(run, target_status='running', phase='deterministic_parsing') + transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing') transition_order_extraction_run( run, target_status='failed', @@ -1057,8 +1757,7 @@ def test_terminal_transition_updates_persisted_chat_state(app): db.session.refresh(log) assert log.payload['shipping_order_extraction_state']['status'] == 'failed' assert log.payload['shipping_order_extraction_state']['terminal'] is True - # The persisted card is user-visible on history replay, so it must not retain worker text. - assert log.payload['shipping_order_extraction_state']['message'] == '' + assert log.payload['shipping_order_extraction_state']['availableActions'] == ['view_details', 'retry_failed_attachments'] def test_chat_history_overrides_late_stale_run_card_with_terminal_fact(app, client): @@ -1068,7 +1767,7 @@ def test_chat_history_overrides_late_stale_run_card_with_terminal_fact(app, clie run, _ = create_order_extraction_run( user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - transition_order_extraction_run(run, target_status='running', phase='deterministic_parsing') + transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing') transition_order_extraction_run( run, target_status='failed', @@ -1103,7 +1802,7 @@ def test_chat_history_overrides_late_stale_run_card_with_terminal_fact(app, clie state = response.get_json()[-1]['payload']['shipping_order_extraction_state'] assert state['status'] == 'failed' assert state['terminal'] is True - assert state['message'] == '' + assert state['availableActions'] == ['view_details', 'retry_failed_attachments'] assert 'failed before card persisted' not in str(response.get_json()) @@ -1114,7 +1813,7 @@ def test_chat_history_does_not_project_user_run_anchor_as_duplicate_state_card(a run, _ = create_order_extraction_run( user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - transition_order_extraction_run(run, target_status='running', phase='deterministic_parsing') + transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing') transition_order_extraction_run(run, target_status='failed', error_message='failed once') db.session.add_all([ ChatLog( @@ -1174,7 +1873,7 @@ def test_failed_run_retry_api_returns_queued_run(app, client): run, _ = create_order_extraction_run( user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - transition_order_extraction_run(run, target_status='running', phase='deterministic_parsing') + transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing') transition_order_extraction_run(run, target_status='failed', error_message='workflow failed') db.session.commit() token = issue_local_access_token(user) @@ -1200,9 +1899,8 @@ def test_terminal_run_reparse_api_creates_versioned_run_and_hides_cross_user(app source, _ = create_order_extraction_run( user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - transition_order_extraction_run(source, target_status='running') - transition_order_extraction_run(source, target_status='result_persisted', result={'pending_count': 1}) - transition_order_extraction_run(source, target_status='needs_review', result={'pending_count': 1}) + transition_order_extraction_run(source, target_status='processing') + transition_order_extraction_run(source, target_status='review_required', result={'pending_count': 1}) other = User(username='reparse-api-other', email='reparse-api-other@example.com', password_hash='x') db.session.add(other) db.session.commit() @@ -1232,6 +1930,127 @@ def test_terminal_run_reparse_api_creates_versioned_run_and_hides_cross_user(app assert hidden.status_code == 404 +def test_terminal_run_reparse_reuses_orphaned_consumed_intake(app, client): + """空结果误标 consumed 时,重识别仍可复用附件;已建单 Intake 不可放开。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-ORPHANED-CONSUMED') + source, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], + ) + transition_order_extraction_run(source, target_status='processing') + transition_order_extraction_run(source, target_status='review_required', result={'pending_count': 1}) + intake.parse_status = 'consumed' + intake.consumed_at = datetime.utcnow() + intake.consumed_batch_id = None + intake.consumed_task_id = None + db.session.commit() + token = issue_local_access_token(user) + run_no = source.run_no + + response = client.post( + f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/reparse', + json={'reason': 'rule_updated'}, headers={'Authorization': f'Bearer {token}'}, + ) + + assert response.status_code == 202 + assert response.get_json()['data']['run']['reparse']['source_run_no'] == run_no + + +def test_reparse_submission_accepts_orphaned_consumed_intake(app): + """重识别产出订单后,可写入未实际建单的 consumed Intake 候选。""" + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='REPARSE-SUBMISSION') + source, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], + ) + transition_order_extraction_run(source, target_status='processing') + transition_order_extraction_run(source, target_status='review_required', result={'pending_count': 1}) + intake.parse_status = 'consumed' + intake.consumed_at = datetime.utcnow() + intake.consumed_batch_id = None + intake.consumed_task_id = None + db.session.commit() + replacement, _ = reparse_order_extraction_run( + user_id=user.id, run_no=source.run_no, reason='rule_updated', + ) + result = submit_order_extraction_run_result(run=replacement, orders=[]) + assert result['pending_count'] == 0 + assert ShippingNoticeCandidate.query.filter_by(order_extraction_run_id=replacement.id).count() == 0 + + +def test_failed_run_with_current_candidate_can_recover_to_review(app): + """仅候选已成功落库的技术失败 Run 可恢复为人工复核,普通失败仍不可跳过。""" + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='RECOVER-REVIEW') + run, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], + ) + transition_order_extraction_run(run, target_status='processing') + transition_order_extraction_run(run, target_status='failed', error_code='TEST', error_message='test') + with pytest.raises(ConflictError): + transition_order_extraction_run(run, target_status='review_required', result={}) + db.session.add(ShippingNoticeCandidate( + candidate_no='SNC-RECOVER-REVIEW', intake_id=intake.id, primary_document_id=document.id, + candidate_key='recover-review', + order_extraction_run_id=run.id, is_current_version=True, + )) + db.session.flush() + transition_order_extraction_run(run, target_status='review_required', result={'pending_count': 1}) + assert run.status == 'review_required' + + +def test_run_progress_events_api_excludes_previous_retry_job_events(app, client): + """手工重试后,用户时间线只展示当前 Job,不能保留旧技术错误码。""" + with app.app_context(): + owner, agent, session, intake, _document = _seed_run_input(suffix='PROGRESS-CURRENT-JOB') + run, _ = create_order_extraction_run( + user=owner, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], + ) + current_job = db.session.get(Job, run.current_job_id) + assert current_job is not None + stale_job = Job( + domain='shipping_notice', job_type='shipping_order_extraction', status='failed', + business_ref=run.run_no, payload_json={'run_no': run.run_no}, attempts=1, max_attempts=3, + ) + db.session.add(stale_job) + db.session.flush() + unit = run.extraction_plan.units[0] + now = datetime.utcnow() + next_sequence = ( + db.session.query(ShippingOrderExtractionProgressEvent.sequence_no) + .filter_by(run_id=run.id) + .order_by(ShippingOrderExtractionProgressEvent.sequence_no.desc()) + .first()[0] + 1 + ) + db.session.add_all([ + ShippingOrderExtractionProgressEvent( + run_id=run.id, unit_id=unit.id, document_id=unit.document_id, job_id=stale_job.id, + sequence_no=next_sequence, visibility='workspace', event_code='technical_failed', status='completed', + reason_code='gkpj', occurred_at=now, received_at=now, summary_json=None, + idempotency_key='progress-stale-job', mapping_version='shipping-order-progress-v2', + ), + ShippingOrderExtractionProgressEvent( + run_id=run.id, unit_id=unit.id, document_id=unit.document_id, job_id=current_job.id, + sequence_no=next_sequence + 1, visibility='workspace', event_code='review_required', status='completed', + reason_code='profile_auto_create_not_approved', occurred_at=now, received_at=now, summary_json=None, + idempotency_key='progress-current-job', mapping_version='shipping-order-progress-v2', + ), + ]) + db.session.commit() + token = issue_local_access_token(owner) + run_no = run.run_no + + response = client.get( + f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/progress-events', + headers={'Authorization': f'Bearer {token}'}, + ) + + assert response.status_code == 200 + items = response.get_json()['data']['items'] + assert [item['event_code'] for item in items] == ['plan_created', 'review_required'] + assert 'gkpj' not in str(items) + + def test_reparse_api_requires_valid_reason_and_json_object(app, client): """API 不接收自由原因或非对象请求体,避免审计分类失真。""" with app.app_context(): @@ -1239,7 +2058,7 @@ def test_reparse_api_requires_valid_reason_and_json_object(app, client): run, _ = create_order_extraction_run( user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - transition_order_extraction_run(run, target_status='running') + transition_order_extraction_run(run, target_status='processing') transition_order_extraction_run(run, target_status='failed', error_message='failed') db.session.commit() token = issue_local_access_token(user) @@ -1336,15 +2155,15 @@ def test_candidate_and_extraction_can_reference_run(app): assert extraction.run_id == run.id -def test_result_persisted_run_cannot_regress_to_failed(app): - """结果落库是不可逆边界;即使后续响应超时也不能把业务事实覆盖成失败。""" +def test_completed_run_cannot_regress_to_failed(app): + """成功结果一旦形成终态,就不能再被后续超时或重试回写成失败。""" with app.app_context(): user, agent, session, intake, _document = _seed_run_input() run, _ = create_order_extraction_run( user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - transition_order_extraction_run(run, target_status='running') - transition_order_extraction_run(run, target_status='result_persisted', result={'candidate_count': 1}) + transition_order_extraction_run(run, target_status='processing') + transition_order_extraction_run(run, target_status='completed', result={'candidate_count': 1}) with pytest.raises(ConflictError) as caught: transition_order_extraction_run( @@ -1355,7 +2174,7 @@ def test_result_persisted_run_cannot_regress_to_failed(app): ) assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_TRANSITION_INVALID' - assert run.status == 'result_persisted' + assert run.status == 'completed' def test_failed_run_projects_retryable_status_to_intake(app): @@ -1365,7 +2184,7 @@ def test_failed_run_projects_retryable_status_to_intake(app): run, _ = create_order_extraction_run( user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - transition_order_extraction_run(run, target_status='running') + transition_order_extraction_run(run, target_status='processing') transition_order_extraction_run( run, target_status='failed', @@ -1384,7 +2203,7 @@ def test_terminal_run_releases_intake_occupancy(app): run, _ = create_order_extraction_run( user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - transition_order_extraction_run(run, target_status='running') + transition_order_extraction_run(run, target_status='processing') transition_order_extraction_run(run, target_status='failed', error_message='provider unavailable') db.session.commit() assert run.intakes[0].released_at is not None @@ -1407,9 +2226,8 @@ def test_reparse_creates_new_run_with_lineage_and_current_snapshot(app): source, _ = create_order_extraction_run( user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - transition_order_extraction_run(source, target_status='running') - transition_order_extraction_run(source, target_status='result_persisted', result={'pending_count': 1}) - transition_order_extraction_run(source, target_status='needs_review', result={'pending_count': 1}) + transition_order_extraction_run(source, target_status='processing') + transition_order_extraction_run(source, target_status='review_required', result={'pending_count': 1}) db.session.commit() replacement, reused = reparse_order_extraction_run( @@ -1446,9 +2264,8 @@ def test_reparse_freezes_current_document_schema_and_layout_without_reprocessing source, _ = create_order_extraction_run( user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - transition_order_extraction_run(source, target_status='running') - transition_order_extraction_run(source, target_status='result_persisted', result={'pending_count': 1}) - transition_order_extraction_run(source, target_status='needs_review', result={'pending_count': 1}) + transition_order_extraction_run(source, target_status='processing') + transition_order_extraction_run(source, target_status='review_required', result={'pending_count': 1}) schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one() document.extracted_text = 'PO 451883815 SNAPSHOT QTY 42 EA' schema.definition_json = {**schema.definition_json, 'reparse_marker': 'current-published-rule'} @@ -1478,7 +2295,7 @@ def test_reparse_rejects_non_terminal_run_and_invalid_reason(app): with pytest.raises(ConflictError) as active: reparse_order_extraction_run(user_id=user.id, run_no=run.run_no, reason='other') assert active.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_REPARSABLE' - transition_order_extraction_run(run, target_status='running') + transition_order_extraction_run(run, target_status='processing') transition_order_extraction_run(run, target_status='failed', error_message='failed') with pytest.raises(ValidationError) as reason: reparse_order_extraction_run(user_id=user.id, run_no=run.run_no, reason='free text') @@ -1492,9 +2309,8 @@ def test_failed_reparse_restores_source_candidate_version(app): source, _ = create_order_extraction_run( user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - transition_order_extraction_run(source, target_status='running') - transition_order_extraction_run(source, target_status='result_persisted', result={'pending_count': 1}) - transition_order_extraction_run(source, target_status='needs_review', result={'pending_count': 1}) + transition_order_extraction_run(source, target_status='processing') + transition_order_extraction_run(source, target_status='review_required', result={'pending_count': 1}) candidate = ShippingNoticeCandidate( candidate_no='SNC-REPARSE-RESTORE', intake_id=intake.id, primary_document_id=document.id, candidate_key='restore-version', order_extraction_run_id=source.id, @@ -1512,7 +2328,7 @@ def test_failed_reparse_restores_source_candidate_version(app): assert candidate.selected_before_superseded is True assert candidate.candidate_status == 'expired' assert candidate.candidate_status_before_superseded == 'accepted' - transition_order_extraction_run(replacement, target_status='running') + transition_order_extraction_run(replacement, target_status='processing') transition_order_extraction_run(replacement, target_status='failed', error_message='provider unavailable') db.session.flush() @@ -1569,7 +2385,7 @@ def test_order_extraction_health_reports_backlog_latency_and_safe_errors(app): def test_order_extraction_health_calculates_segments_and_failure_rate(app): - """健康汇总应按 Run 时间戳计算队列、Provider、HXOPS 与总耗时。""" + """健康汇总应按 Run 时间戳计算队列、解析、候选落库与总耗时。""" from app.services.shipping_notice.order_extraction_run_service import get_order_extraction_run_health with app.app_context(): @@ -1593,7 +2409,7 @@ def test_order_extraction_health_calculates_segments_and_failure_rate(app): assert report['failure_rate'] == 1.0 assert report['latency']['queue']['avg_ms'] == 1000 assert report['latency']['deterministic_parsing']['avg_ms'] == 3000 - assert report['latency']['hxops_persistence']['avg_ms'] == 2000 + assert report['latency']['candidate_materialization']['avg_ms'] == 2000 assert report['latency']['total']['avg_ms'] == 7000 assert report['error_code_counts'] == {'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT': 1} assert report['thresholds']['user_slow_response_seconds'] >= 60 @@ -1626,7 +2442,7 @@ def test_order_extraction_diagnostic_apis_are_admin_only_audited_and_redacted(ap user=owner, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) run.execution_result_json = {'raw_output': 'must not leak'} - transition_order_extraction_run(run, target_status='running') + transition_order_extraction_run(run, target_status='processing') transition_order_extraction_run( run, target_status='failed', error_code='UPSTREAM.TIMEOUT', error_message='secret provider stack trace', ) diff --git a/backend/tests/test_shipping_order_extraction_stage0.py b/backend/tests/test_shipping_order_extraction_stage0.py index b02a0e49..3d7eedf5 100644 --- a/backend/tests/test_shipping_order_extraction_stage0.py +++ b/backend/tests/test_shipping_order_extraction_stage0.py @@ -13,26 +13,28 @@ from app.models import ShippingAuditEvent from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit -def test_business_review_route_transitions_unit_to_skipped_not_failed(app): - """模板未匹配等业务拒识使用 skipped,计划完成后由 Run 汇总为 needs_review。""" +def test_business_review_route_transitions_unit_to_review_required_not_failed(app): + """模板未匹配等业务拒识使用 review_required,计划完成后由 Run 汇总为 review_required/partially_completed。""" with app.app_context(): plan = SimpleNamespace(units=[]) unit = SimpleNamespace( - status='running', attempt_count=1, started_at=None, finished_at=None, - result_json={'stale': True}, error_code=None, error_message=None, plan=plan, + status='matching_profile', attempt_count=1, started_at=None, finished_at=None, + last_activity_at=None, result_json={'stale': True}, summary_json=None, + reason_code=None, error_code=None, error_message=None, plan=plan, ) plan.units = [unit] transition_order_extraction_unit( unit, - target_status='skipped', - error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED', + target_status='review_required', + error_code='profile_not_found', error_message='Template requires review', ) # 关键断言:业务不确定性是可复核的完成态,不能污染技术失败率。 - assert unit.status == 'skipped' - assert unit.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED' + assert unit.status == 'review_required' + assert unit.reason_code == 'profile_not_found' + assert unit.error_code is None assert plan.status == 'completed' @@ -42,16 +44,49 @@ def test_unit_transition_appends_auditable_status_event(app): run = SimpleNamespace(run_no='SNER-STAGE0') plan = SimpleNamespace(units=[], run=run) unit = SimpleNamespace( - id=37, status='running', attempt_count=1, started_at=None, finished_at=None, - result_json=None, error_code=None, error_message=None, plan=plan, + id=37, status='matching_profile', attempt_count=1, started_at=None, finished_at=None, + last_activity_at=None, result_json=None, summary_json=None, + reason_code=None, error_code=None, error_message=None, plan=plan, ) plan.units = [unit] - transition_order_extraction_unit(unit, target_status='skipped') + transition_order_extraction_unit(unit, target_status='review_required', error_code='profile_not_found') db.session.commit() event = ShippingAuditEvent.query.filter_by(aggregate_id='37').one() # 关键断言:单元业务复核状态能和 Run 关联,但不复制订单内容。 assert event.event_type == 'order_extraction_unit_status_changed' assert event.run_no == 'SNER-STAGE0' - assert event.reason_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED' + assert event.reason_code == 'profile_not_found' + + +def test_supplement_merge_transition_keeps_unit_on_business_path(app): + """正文补充合并必须走 merging_supplement -> candidate_ready,不能跳回技术态。""" + with app.app_context(): + plan = SimpleNamespace(units=[]) + unit = SimpleNamespace( + status='extracting', attempt_count=1, started_at=None, finished_at=None, + last_activity_at=None, result_json=None, summary_json=None, + reason_code=None, error_code=None, error_message=None, plan=plan, + ) + plan.units = [unit] + + transition_order_extraction_unit( + unit, + target_status='merging_supplement', + result={'orders': [{'po_number': '450001'}]}, + ) + assert unit.status == 'merging_supplement' + assert unit.error_code is None + assert plan.status == 'running' + + transition_order_extraction_unit( + unit, + target_status='candidate_ready', + result={'orders': [{'po_number': '450001', '_hxops_email_supplement_relation': 'po_mpn'}]}, + ) + + assert unit.status == 'candidate_ready' + assert unit.result_json['orders'][0]['_hxops_email_supplement_relation'] == 'po_mpn' + assert unit.reason_code is None + assert plan.status == 'completed' diff --git a/backend/tests/test_shipping_order_extraction_worker.py b/backend/tests/test_shipping_order_extraction_worker.py new file mode 100644 index 00000000..252f1d86 --- /dev/null +++ b/backend/tests/test_shipping_order_extraction_worker.py @@ -0,0 +1,368 @@ +"""订单抽取 Worker 的单元级自动重试与技术失败收口测试。""" + +from types import SimpleNamespace + +from app.core.errors import ServiceUnavailableError, ValidationError +from app.jobs.handlers.shipping_order_extraction import ( + _expansion_trigger_reason_codes, + _mark_expandable_business_gaps, + _pending_snapshot_batches, + _process_unit_with_retries, + _result_requires_review, + _should_expand_after_wave, + _units_for_batch, +) + + +def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch): + """深度抽取只允许在 Worker 首轮执行,且必须在读取 Unit 计划之前完成。""" + import app.jobs.handlers.shipping_order_extraction as handler + + events: list[str] = [] + run = SimpleNamespace( + id=1, run_no='SNER-WORKER-MATERIALIZE', status='queued', current_job_id=None, + attempt_count=0, input_snapshot_json={'attachment_selection': {}}, + ) + job = SimpleNamespace(id=1, attempts=1, business_ref=run.run_no, max_attempts=3) + plan = SimpleNamespace(id=1, unit_count=0, units=[]) + + monkeypatch.setattr(handler.db.session, 'get', lambda _model, _id: job) + monkeypatch.setattr( + handler, + 'ShippingOrderExtractionRun', + SimpleNamespace(query=SimpleNamespace( + filter_by=lambda **_kwargs: SimpleNamespace( + with_for_update=lambda: SimpleNamespace(first=lambda: run), + ), + )), + ) + monkeypatch.setattr( + handler, + 'ShippingOrderExtractionUnit', + SimpleNamespace( + position=SimpleNamespace(asc=lambda: None), + query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace( + order_by=lambda *_args: SimpleNamespace(all=lambda: []), + )), + ), + ) + monkeypatch.setattr(handler, 'transition_order_extraction_run', lambda target, **_kwargs: setattr(target, 'status', 'processing')) + monkeypatch.setattr(handler, 'materialize_order_extraction_run_inputs', lambda _run: events.append('materialize') or plan) + monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: events.append('units') or []) + monkeypatch.setattr(handler, '_next_existing_batch', lambda _plan, *, after_batch: None) + monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda _run, _plan: []) + monkeypatch.setattr(handler, '_wave_orders_for_expansion', lambda _run, *, orders: []) + monkeypatch.setattr(handler, '_expansion_trigger_reason_codes', lambda **_kwargs: []) + monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: None) + monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: None) + monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda *, run, orders: {}) + monkeypatch.setattr(handler, '_result_requires_review', lambda **_kwargs: False) + monkeypatch.setattr(handler, 'finish_job', lambda *_args, **_kwargs: events.append('finished')) + monkeypatch.setattr(handler.db.session, 'commit', lambda: None) + monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None) + + handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 1}) + + assert events.index('materialize') < events.index('units') + + +def _patch_unit_transitions(monkeypatch): + """用轻量状态机替代 ORM transition,便于验证单元级自动重试行为。""" + + def fake_transition(unit, *, target_status, error_code=None, error_message=None, result=None, **_kwargs): + if target_status == 'routing': + unit.attempt_count = int(unit.attempt_count or 0) + 1 + unit.retry_status = 'retrying' if int(unit.attempt_count or 0) > 1 else 'running' + elif target_status == 'pending': + unit.retry_status = 'pending_retry' + elif target_status == 'failed': + unit.retry_status = 'failed' + unit.technical_failure_reason_code = error_code + unit.error_code = error_code + unit.error_message = error_message + elif target_status == 'review_required': + unit.retry_status = 'review_required' + elif target_status == 'candidate_ready': + unit.retry_status = 'succeeded' + unit.status = target_status + unit.result_json = result + + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_plan.transition_order_extraction_unit', + fake_transition, + ) + + +def _patch_worker_io(monkeypatch, *, event_log: list[tuple[str, str | None]]): + monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.db.session.commit', lambda: None) + monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.db.session.rollback', lambda: None) + monkeypatch.setattr( + 'app.jobs.handlers.shipping_order_extraction.record_unit_progress', + lambda *, event_code, reason_code=None, **_kwargs: event_log.append((event_code, reason_code)), + ) + monkeypatch.setattr( + 'app.jobs.handlers.shipping_order_extraction._append_route_decision', + lambda **_kwargs: None, + ) + + +def test_process_unit_with_retries_retries_retryable_failures_and_returns_orders(monkeypatch): + """同一附件技术故障应在单元内自动重试,成功后不需要整轮 Run 重跑。""" + event_log: list[tuple[str, str | None]] = [] + _patch_unit_transitions(monkeypatch) + _patch_worker_io(monkeypatch, event_log=event_log) + + run = SimpleNamespace(id=1, run_no='SNER-WORKER-RETRY') + unit = SimpleNamespace( + id=7, + intake_id=11, + document_id=101, + status='pending', + attempt_count=0, + retry_status='not_started', + technical_failure_reason_code=None, + result_json=None, + ) + job = SimpleNamespace(id=5) + orders = [{'source_intake_no': 'SNI-1', 'primary_document_id': 101, 'header_fields': [], 'lines': []}] + + calls = {'count': 0} + + def fake_route(_run, *, unit): + calls['count'] += 1 + if calls['count'] < 3: + raise ServiceUnavailableError('layout service unavailable', code='SYSTEM.SERVICE_UNAVAILABLE') + return SimpleNamespace( + execution_mode='deterministic', + orders=orders, + decision={'selected_profile_code': 'vendor_a', 'selected_profile_version': 2}, + ) + + monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.route_deterministic_unit', fake_route) + monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.validate_unit_orders', lambda _run, *, unit, orders: orders) + monkeypatch.setattr( + 'app.jobs.handlers.shipping_order_extraction._reload_run_and_unit', + lambda *, run_id, unit_id: (run, unit), + ) + + result = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1) + + assert result is orders + assert unit.status == 'merging_supplement' + assert unit.attempt_count == 3 + assert event_log.count(('technical_retrying', 'SYSTEM.SERVICE_UNAVAILABLE')) == 2 + assert event_log.count(('technical_failed', 'SYSTEM.SERVICE_UNAVAILABLE')) == 2 + + +def test_process_unit_with_retries_records_distinct_route_attempts(monkeypatch): + """同一 Job 内重试路由时,审计尝试号必须随 Unit 递增以避开唯一约束。""" + event_log: list[tuple[str, str | None]] = [] + _patch_unit_transitions(monkeypatch) + _patch_worker_io(monkeypatch, event_log=event_log) + + run = SimpleNamespace(id=1, run_no='SNER-WORKER-ROUTE-ATTEMPTS') + unit = SimpleNamespace( + id=10, intake_id=14, document_id=104, status='pending', attempt_count=0, + retry_status='not_started', technical_failure_reason_code=None, result_json=None, + ) + job = SimpleNamespace(id=8) + route_attempts: list[int] = [] + calls = {'count': 0} + + def fake_route(_run, *, unit): + calls['count'] += 1 + return SimpleNamespace( + execution_mode='deterministic', + orders=[{'source_intake_no': 'SNI-ROUTE', 'primary_document_id': 104, 'header_fields': [], 'lines': []}], + decision={'selected_profile_code': 'vendor_a', 'selected_profile_version': 1}, + ) + + def fake_validate(_run, *, unit, orders): + if calls['count'] == 1: + raise ServiceUnavailableError('temporary validation failure', code='SYSTEM.SERVICE_UNAVAILABLE') + return orders + + monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.route_deterministic_unit', fake_route) + monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.validate_unit_orders', fake_validate) + monkeypatch.setattr( + 'app.jobs.handlers.shipping_order_extraction._append_route_decision', + lambda **kwargs: route_attempts.append(kwargs['attempt_no']), + ) + monkeypatch.setattr( + 'app.jobs.handlers.shipping_order_extraction._reload_run_and_unit', + lambda *, run_id, unit_id: (run, unit), + ) + + assert _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1) + assert route_attempts == [1, 2] + + +def test_process_unit_with_retries_exhausts_retry_budget_and_marks_unit_failed(monkeypatch): + """自动重试耗尽后仅保留单元级技术失败,调用方可继续处理其他附件。""" + event_log: list[tuple[str, str | None]] = [] + _patch_unit_transitions(monkeypatch) + _patch_worker_io(monkeypatch, event_log=event_log) + + run = SimpleNamespace(id=1, run_no='SNER-WORKER-FAILED') + unit = SimpleNamespace( + id=8, + intake_id=12, + document_id=102, + status='pending', + attempt_count=0, + retry_status='not_started', + technical_failure_reason_code=None, + result_json=None, + ) + job = SimpleNamespace(id=6) + + monkeypatch.setattr( + 'app.jobs.handlers.shipping_order_extraction.route_deterministic_unit', + lambda _run, *, unit: (_ for _ in ()).throw(ServiceUnavailableError('ocr timeout', code='OCR.TIMEOUT')), + ) + monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.validate_unit_orders', lambda _run, *, unit, orders: orders) + monkeypatch.setattr( + 'app.jobs.handlers.shipping_order_extraction._reload_run_and_unit', + lambda *, run_id, unit_id: (run, unit), + ) + + result = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1) + + assert result is None + assert unit.status == 'failed' + assert unit.attempt_count == 3 + assert unit.technical_failure_reason_code == 'OCR.TIMEOUT' + assert event_log.count(('technical_retrying', 'OCR.TIMEOUT')) == 2 + assert event_log.count(('technical_failed', 'OCR.TIMEOUT')) == 3 + + +def test_process_unit_with_retries_does_not_retry_non_retryable_validation_errors(monkeypatch): + """业务/校验类异常不得误走技术自动重试。""" + event_log: list[tuple[str, str | None]] = [] + _patch_unit_transitions(monkeypatch) + _patch_worker_io(monkeypatch, event_log=event_log) + + run = SimpleNamespace(id=1, run_no='SNER-WORKER-NONRETRY') + unit = SimpleNamespace( + id=9, + intake_id=13, + document_id=103, + status='pending', + attempt_count=0, + retry_status='not_started', + technical_failure_reason_code=None, + result_json=None, + ) + job = SimpleNamespace(id=7) + + monkeypatch.setattr( + 'app.jobs.handlers.shipping_order_extraction.route_deterministic_unit', + lambda _run, *, unit: (_ for _ in ()).throw( + ValidationError('snapshot stale', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE'), + ), + ) + monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.validate_unit_orders', lambda _run, *, unit, orders: orders) + monkeypatch.setattr( + 'app.jobs.handlers.shipping_order_extraction._reload_run_and_unit', + lambda *, run_id, unit_id: (run, unit), + ) + + result = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1) + + assert result is None + assert unit.status == 'failed' + assert unit.attempt_count == 1 + assert unit.technical_failure_reason_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE' + assert ('technical_retrying', 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE') not in event_log + assert event_log.count(('technical_failed', 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE')) == 1 + + +def test_should_expand_after_wave_when_current_wave_needs_more_evidence(): + """只有可补证的 review/业务缺口才扩批;纯技术失败不应直接消耗下一轮预算。""" + assert _should_expand_after_wave( + wave_units=[SimpleNamespace(status='review_required', reason_code='required_field_missing')], + wave_orders=[], + ) is True + assert _should_expand_after_wave( + wave_units=[SimpleNamespace(status='failed', reason_code='OCR.TIMEOUT')], + wave_orders=[{'id': 1}], + ) is False + + +def test_auto_freeze_blocked_task_requires_run_review(): + """自动冻结的 Task 级门禁拒绝必须把 Run 收口为需人工处理,而非 completed。""" + assert _result_requires_review( + units=[SimpleNamespace(status='candidate_ready')], + result={'pending_count': 0, 'auto_freeze': {'blocked_tasks': [{'task_no': 'ST-1'}]}}, + ) is True + assert _should_expand_after_wave( + wave_units=[SimpleNamespace(status='candidate_ready', reason_code=None)], + wave_orders=[{'_hxops_expand_for_missing_reservation': True}], + ) is True + assert _should_expand_after_wave( + wave_units=[SimpleNamespace(status='merging_supplement', reason_code=None)], + wave_orders=[{'id': 1}], + ) is False + + +def test_expansion_trigger_reason_codes_merge_review_and_order_gaps(): + """扩批原因应同时汇总 review reason、正文冲突和缺 Reservation。""" + codes = _expansion_trigger_reason_codes( + wave_units=[SimpleNamespace(status='review_required', reason_code='required_field_missing')], + wave_orders=[{ + '_hxops_expand_for_missing_reservation': True, + 'conflicts': [{'reason': 'supplement_relation_ambiguous'}], + }], + ) + + assert codes == [ + 'missing_reservation_id', + 'required_field_missing', + 'supplement_relation_ambiguous', + ] + + +def test_mark_expandable_business_gaps_flags_missing_reservation_from_schema(): + """缺 Reservation 的订单应被标记为可通过下一附件补证。""" + run = SimpleNamespace( + input_snapshot_json={ + 'schema': { + 'definition': { + 'fields': [ + {'field_code': 'reservation_id', 'field_id': 'reservation-id'}, + ], + }, + }, + }, + ) + orders = [{ + 'lines': [ + {'fields': []}, + {'fields': [{'field_id': 'reservation-id', 'observations': [{'value': 'RSV001'}]}]}, + ], + }] + + marked = _mark_expandable_business_gaps(run, orders=orders) + + assert marked[0]['_hxops_expand_for_missing_reservation'] is True + + +def test_pending_snapshot_batches_ignore_already_activated_units(): + """冻结计划里已有的未来批次,激活后不应重复出现在待扩批列表里。""" + run = SimpleNamespace( + input_snapshot_json={ + 'attachment_selection': { + 'items': [ + {'planned_selection_batch': 2}, + {'planned_selection_batch': 3}, + ], + }, + }, + ) + plan = SimpleNamespace(units=[ + SimpleNamespace(selection_batch=1), + SimpleNamespace(selection_batch=2), + ]) + + assert _pending_snapshot_batches(run, plan) == [3] + assert [unit.selection_batch for unit in _units_for_batch(plan, selection_batch=1)] == [1] diff --git a/backend/tests/test_shipping_order_extraction_workspace_projection_unit.py b/backend/tests/test_shipping_order_extraction_workspace_projection_unit.py new file mode 100644 index 00000000..c4ae318d --- /dev/null +++ b/backend/tests/test_shipping_order_extraction_workspace_projection_unit.py @@ -0,0 +1,42 @@ +"""订单抽取工作台投影的纯单元测试。""" + +from types import SimpleNamespace + +from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run_chat_state + + +def test_workspace_projection_exposes_run_level_current_activity(monkeypatch): + """Run 级事件也应进入聊天卡 currentActivity,而不是只支持单元级事件。""" + run = SimpleNamespace( + status='processing', + extraction_plan=SimpleNamespace(units=[]), + input_snapshot_json={}, + error_code=None, + started_at=None, + finished_at=None, + ) + + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workspace_projection._latest_progress_events', + lambda _run: ( + {}, + SimpleNamespace( + unit_id=None, + document_id=None, + event_code='expansion_wave_started', + reason_code='budget_initial_limit', + summary_json={'selection_batch': 2, 'reason_codes': ['required_field_missing']}, + ), + ), + ) + + result = serialize_workspace_run_chat_state(run) + + assert result['currentActivity'] == { + 'unitId': 0, + 'fileName': None, + 'eventCode': 'expansion_wave_started', + 'selectionBatch': 2, + 'reasonCodes': ['budget_initial_limit', 'required_field_missing'], + } + assert result['status'] == 'processing' diff --git a/backend/tests/test_shipping_order_profile_matcher.py b/backend/tests/test_shipping_order_profile_matcher.py index 5f8a4934..93c61189 100644 --- a/backend/tests/test_shipping_order_profile_matcher.py +++ b/backend/tests/test_shipping_order_profile_matcher.py @@ -88,3 +88,22 @@ def test_profile_matcher_uses_page_glyphs_for_anchor_outside_table(): def test_profile_matcher_uses_table_glyphs_only_for_legacy_evidence(): """缺少新 page_glyphs 的历史冻结快照继续保持兼容,不降低已有模板可回放性。""" assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=_layout()).status == 'unique_match' + + +def test_profile_matcher_allows_multiple_template_regions_on_one_detected_table(): + """续页未被检测器拆表时,页级坐标证据仍可匹配多区域模板。""" + profile = _profile('PO_A') + profile['definition']['table_regions'][0]['region']['y1'] = .5 + profile['definition']['table_regions'][0]['line_layouts'][0]['region']['y1'] = .5 + profile['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['y1'] = .5 + profile['definition']['table_regions'].append({ + 'region_id': 'lines_page_2', 'page_scope': 'exact_page', 'page_no': 2, + 'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': 1}, + 'header_layouts': [{'layout_id': 'header_page_2', 'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': 1}}], + }) + layout = _layout() + layout['coordinate_evidence']['page_glyphs'] = {'1': layout['coordinate_evidence']['tables']['table-1']} + + result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout) + + assert result.status == 'unique_match' diff --git a/docs/convention/error_handling.md b/docs/convention/error_handling.md index 6e791b16..c2ce549b 100644 --- a/docs/convention/error_handling.md +++ b/docs/convention/error_handling.md @@ -197,6 +197,27 @@ catch (e) { | 在 `*.api.ts` 里 `msg.error` | API 层只抛错,UI 层负责展示 | | 新增后端 code 却不加 `errors.json` | 四语言同步 `errors.codes.*` | +### 3.6 订单抽取:API 错误码 vs 运行原因码(强约束) + +订单抽取链路同时存在两类“码”,**语义不同,禁止混用**: + +| 类型 | 承载位置 | 例子 | 用途 | 前端展示位置 | +|------|----------|------|------|--------------| +| **API 错误码** | Envelope `error.code` / `BusinessError.code` | `SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND`、`SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING` | 请求级失败:创建 Run、重试、重解析、详情接口访问失败 | `errors.json` / `BusinessError.message` / `useMessage()` | +| **运行原因码** | 订单抽取 payload 内部字段:`reason_code`、`summary.reason_codes`、`unit_summary.review_required_reason_codes`、`unit_summary.expansion_trigger_reason_codes`、`technical_failure_reason_code` | `required_field_missing`、`multiple_po_detected`、`missing_reservation_id`、`budget_initial_limit`、`SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT` | Run/Unit 事实解释:为什么复核、为什么扩批、为什么预算停止、哪个技术单元失败 | 聊天卡片、详情抽屉、逐 PDF 结果项 | + +**硬约束:** + +1. `reason_code(s)` **不是** `BusinessError.code`,不得走 `errors.codes.*` 全局错误映射。 +2. 订单抽取业务原因码(如 `required_field_missing`、`supplement_relation_ambiguous`)使用 `chat.json` 的 `shippingOrderExtractionReason.*` 翻译。 +3. 预算原因码(如 `budget_initial_limit`)和技术原因码(如 `SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT`)在订单抽取卡片/抽屉中按运行事实展示,**不得**伪装成请求失败 toast。 +4. 只有当请求本身失败时,才使用 `BusinessError` + `errors.json`;Run 已创建后的 `review_required / failed / budget_stopped` 一律视为**业务运行事实**。 +5. 对话卡片与详情抽屉可以按以下四类对时间线做轻量分组,但不得发明额外状态: + - `business`:业务复核 / 证据不足 / 扩批触发 + - `technical`:技术异常 / 技术重试 / 技术失败 + - `budget`:预算停止 / 限额耗尽 + - `progress`:计划创建、首轮启动、普通进度 + --- ## 4. 新增错误码检查清单 diff --git a/docs/demand.md b/docs/demand.md index 60a7d4da..624ba6b1 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -113,18 +113,18 @@ ### 3.x 一封邮件多订单与 Candidate 级判重 -- 保持“一封 EML = 一个 Intake”;上传阶段只预处理正文和附件为 Document。订单抽取已切换为独立 Run:点击发送直接创建后台作业并轮询 Run 状态,不再把 `shipping_intake_nos` 发送给普通 Chatflow;普通无附件问答仍走聊天 SSE。 +- 保持“一封 EML = 一个 Intake”;上传阶段只做快览:读取邮件头、正文白名单 HTML 表格快照和附件目录,不抽取附件全文、不创建附件 Document/派生资产、不调度 MinerU/OCR。订单抽取已切换为独立 Run:点击发送直接创建后台作业并轮询 Run 状态,不再把 `shipping_intake_nos` 发送给普通 Chatflow;普通无附件问答仍走聊天 SSE。 - 一个附件可包含多个订单,一个订单也可跨正文/多个附件;按实际业务订单生成 Candidate,不按附件数量机械拆分。 -- 正文与附件由 LLM 结合语义关联;后端规则解析与 Dify LLM 均只产出不可变字段 Observation,由 HXOPS 按字段证据统一裁决;`part_number`/Qty 必须保留原文 evidence,不确定字段返回空值,关键字段冲突必须阻断自动建单。 +- 正文与附件由 HXOPS 的确定性关系规则关联并统一裁决;`part_number`/Qty 必须保留原文 evidence,不确定字段返回空值,关键字段冲突必须阻断自动建单。订单抽取主链不调用 Dify。 - 判重以 Candidate 为业务粒度:附件 hash 判断相同文件,业务身份指纹判断同一订单,内容指纹区分完全重复与订单修订。 - 高置信发货需求只要包含可信内部料号 `part_number` + 正数 Qty 且有原文证据即可自动创建 Batch/Task;Reservation ID 缺失时 Task 必须停在自然对话补字段门禁;`inventory_source_hint` 是可选库存源路由线索,不作为必填门禁。 - 低置信、证据不足、阻断冲突或可能修订的 Candidate 保留待处理;同 Intake 已自动建单部分不得导致剩余 Candidate 丢失。 -- 订单抽取最终必须以持久化 `ShippingOrderExtractionRun` 为业务生命周期真相;Run 冻结用户、入口 Agent、会话、Intake/Document 正文和 published Schema,幂等键由服务端快照计算,不依赖浏览器 request ID。 +- 订单抽取最终必须以持久化 `ShippingOrderExtractionRun` 为业务生命周期真相;发送时 Run 冻结用户、入口 Agent、会话、Intake、Schema 与附件选择计划的轻量请求快照,Worker 物化后另冻结 Document 正文执行快照。幂等键始终锚定请求快照,不依赖浏览器 request ID。 - 订单附件结构化必须支持版本化订单坐标 Profile v2。模板真相为静态文档锚点、表区相对坐标、独立表头布局、明细物理行布局、字段区域到稳定 `field_id + field_code` 的绑定、注册解析器、跨页/终止规则;表头文字只能用于建议、校准和匹配,不能决定最终字段。已发布版本不可原地修改,同模板发布新版本时原子退役旧版本;Run 必须复制完整 published Profile,不能只保存当前 Profile ID。 - 业务管理员必须通过受控样本页面维护订单坐标 Profile:可配置相对区域、静态锚点、独立表头/明细布局和注册解析器;不得编辑 HTML、原始 bbox、JSON、正则、脚本、Prompt 或结构指纹。草稿更新使用乐观锁;每个明细字段区域必须绑定 Schema 允许的 `pdf_coordinate`/`ocr_coordinate` 来源和最低证据等级;不可变版本可复制为新草稿或退役。 - Profile 治理必须保存模板模式、训练样本计数和不含锚点正文的匹配策略摘要;训练/标注样本、盲测样本及其增删、草稿保存、区域/字段绑定变化、测试执行/批准、发布和退役均追加审计。样本文档被训练或盲测引用后不得删除;审计不得保存 PDF、HTML、对象存储地址、正文或凭据。 - 模板工作台页面预览仅针对已绑定样本:PDF 以短时、单页、单用途 Redis 授权返回低分辨率 PNG,响应始终 `private, no-store`,不返回 MinIO URL、PDF、bbox、原始 HTML 或永久下载令牌。OCR 坐标只可由管理员对绑定 PDF 显式触发;页面文本和局部解析候选不包含坐标/token 身份。EML 仅使用既有白名单清洗的表格文本,禁止脚本、事件属性、表单、iframe、外链及远程图片/字体。 -- MinerU 按显式环境开关固定使用 `pipeline`,由独立布局 Job 在 Intake 持久化 Document 后异步调用,不得阻塞 Intake 预解析。布局必须按 Document 独立版本化,保存 parser revision、状态、checksum、大小、质量问题和 Worker lease;只有成功版本可成为当前布局,失败/超限/旧 Worker 结果不得覆盖上一次成功版本。多附件受单 Intake 文档预算限制;Provider 失败、超预算、结构不匹配或多表命中时回退现有 Dify/人工复核,不得伪造确定性字段。 +- MinerU 按显式环境开关固定使用 `pipeline`,由发送后的 Worker 在 Document 物化后异步调用,不得阻塞上传快览。布局必须按 Document 独立版本化,保存 parser revision、状态、checksum、大小、质量问题和 Worker lease;只有成功版本可成为当前布局,失败/超限/旧 Worker 结果不得覆盖上一次成功版本。多附件受单 Run 文档预算限制;Provider 失败、超预算、结构不匹配或多表命中时进入人工复核,不得伪造确定性字段或回退 Dify。 - 人工单元格真值当前允许延期,不阻塞布局版本/任务生命周期建设;但在真值评测完成前,不得宣称 95% 准确率、把 MinerU/OpenCV/文本对齐候选自动标记为 `accepted`,也不得据此开启错误自动建单风险。 - 原生 PDF 可使用 PDFium 字符坐标与 MinerU HTML 生成 `shipping_document_layout.v1` 候选;只允许唯一连续文本或“OpenCV 多参数有框网格 + 原生文本全量一致”两条保守路径。候选必须保持 `needs_review`,扫描 PDF 不得由本阶段伪造 OCR 结果。 - 扫描 PDF 的布局 OCR 必须保留 RapidOCR 原始多边形坐标和置信度,并且只有与严格有框网格及全部非空 cell 文本一致时才能生成 OCR cell 候选。EML HTML table 必须经主动内容/属性白名单清理后按 DOM 行列和跨度生成逻辑布局;原始 HTML 不得进入 Intake 摘要、Dify 或日志。两类结果在人工真值完成前均保持 `needs_review`。 @@ -133,22 +133,22 @@ - 对 MinerU 行列关系错误或数据页表头不完整的 PDF,管理员可基于原生/OCR 字符坐标确认相对字段区域。坐标模板不得依赖数据页完整表头:系统以主行锚点、y-band、物理行相对偏移、前一明细完整性和显式跨页声明综合判定新行/续行;无稳定主行锚点不得默认新明细。合计、税额、条款和签字区必须由排除/终止规则排除。几何位置是主证据,字段内容类型与同行左右顺序仅用于边界歧义辅助。 - 同一订单明细允许由任意连续 N 条物理行构成,不限定两行、三行或四行。管理员可动态增加/删除第 2..N 行版式,每行独立配置相对列边界和固定字段映射,横坐标区间允许跨行重叠;第 1 行必须包含 `line_no` 作为新明细锚点,后续行按 `row_offset` 合并到最近明细。 - 管理员不得被要求从 PDF 截图手工计算 0..1 列边界。系统须基于冻结的 PDF/OCR 字符坐标自动建议物理行数量、每行列边界及列示例文字;人工只确认字段映射,并可在必要时使用高级边界校准。 -- 阶段 2 创建 Run 时同步创建 `shipping_order_extraction` Job;Worker 按 Run 冻结快照调用 `shipping.order_extraction` 能力绑定的内部 Provider,并把 Dify 成功结果先于 HXOPS 订单落库独立提交,重试不得重复调用 Dify。 -- 应用管理必须显式创建 `exposure_mode=internal` 的 Dify Workflow Provider,再由货代 Agent 绑定 `shipping.order_extraction`。业务代码只识别能力编码和数据库外键,禁止写死 App ID、按名称匹配或从环境变量静默回退;Dify 画布由管理员手工配置。 -- Run 冻结 Provider App ID、Base URL 与执行参数;二者变更后旧 Run 必须失败并重新发起。API Key 不进入快照,允许在不重建 Run 的情况下安全轮换。 +- 创建 Run 时同步创建 `shipping_order_extraction` Job;发送请求不做深度解析,Worker 先按冻结的附件选择计划物化首轮输入,再按执行快照执行 HXOPS 本地确定性解析与候选落库,不依赖 Dify Workflow、Runtime Binding 或内部 Provider 成功缓存。 +- 货代订单抽取由 HXOPS 的确定性解析 Run 和 Worker 执行,不依赖应用管理中的 Dify Workflow Provider、Runtime Binding 或内部执行器;Dify 画布如需保留,仅由管理员独立维护且不参与该执行链路。 +- Run 不冻结 Provider App ID、Base URL 或 API Key;订单抽取主链不调用 Provider。Dify 如保留,仅用于独立只读问答且不参与 Run 执行。 - Run 模型声明的执行追溯字段必须由独立 Alembic 增量迁移提供;已经进入任何环境的迁移文件禁止继续追加列。部署验收必须同时核对 Alembic head、数据库实际列和 SQLAlchemy 模型,任一不一致均阻断下一阶段。 - 用户点击发送后,聊天区必须立即显示订单识别进行态;该阶段无法获得可信完成比例,因此使用不确定进度,不展示伪造百分比。 - 首次发送无需先创建聊天消息:Run 创建事务会创建本地 ChatSession 并原子绑定尚未归属会话的 Intake,前端使用返回的 `conversation_id` 更新路由。 - 订单识别状态卡必须可在刷新/重新进入会话后按 Run 列表恢复;活动态只显示不确定进度,不按固定轮询频率重复写 ChatLog,只有业务状态变化才原位持久化。 -- 订单抽取进度由 HXOPS 服务端消费专用 Workflow 的 Dify SSE 节点事件并自动按节点类型归并;用户默认查看当前脱敏阶段、真实运行时长和最近活动,可展开时间线。无需手工修改 Dify Workflow;不展示模型思考、节点输入输出、伪百分比或内部运行标识。浏览器继续使用自适应短轮询,不建立订单抽取浏览器长 SSE。 +- 订单抽取进度必须来自 HXOPS 持久化的 Run / PDF Unit / Progress Event 数据库事实;用户卡片只展示 `summary/current_activity/available_actions` 及按 PDF 归并结果,不再消费 Dify 节点事件、Workflow 阶段或浏览器 SSE。浏览器继续使用自适应短轮询,页面刷新、重新登录和 Worker 重启后均可恢复同一事实视图。 - 用户状态卡、Run 查询和历史聊天回放只可显示稳定错误码与通用可操作提示;Worker、Provider 或上游异常正文不得进入用户 API、ChatLog 或前端状态。 - 新上线 Run 的完成、待确认和失败状态应在用户离开会话后形成会话级待查看提示;进入对应会话且终态卡片成功加载后才清除。管理员在货代管理域只读诊断 Run、Job Attempt 和脱敏节点时间线;不提供管理端强制操作。 - Run 失败或取消时 Intake 恢复为可重试失败态;切换会话后的迟到轮询响应不得更新当前页面或重启旧 Run 计时器。 -- 管理员必须可查询最近 1-168 小时订单抽取 Run 的状态/阶段/错误码分布、失败率、重试数、积压 Run,以及排队、Provider、HXOPS 落库和总耗时;监控视图不得返回文档正文、Provider 配置、原始结果或错误正文。 +- 管理员必须可查询最近 1-168 小时订单抽取 Run 的状态、当前活动事件、错误码分布、失败率、重试数、积压 Run,以及排队、处理和总耗时;监控视图不得返回文档正文、Provider 配置、原始结果或错误正文。 - 前端 Run 查询单次最多等待 10 秒;超时或切换会话只取消当前 GET,后台 Run 继续执行,页面保持进行态并按退避策略重试。 - 订单识别终态必须区分新建任务、打开已有任务、待补充/冲突、非发货忽略和已建但缺流程字段,并在刷新或重新进入会话后仍可恢复。 -- Dify 错误、网络超时或成功结束但未提交 `orders[]` 时,订单识别必须离开 `extracting` 并显示可重试的失败原因。 -- 同一 Intake 同时只允许一个订单识别 Run;已有 Run 处理中时,新请求必须复用相同快照或返回冲突。Provider 结果或订单事实已持久化后,任何 Dify 断流、读超时、Worker 重试或迟到终态都不得重复调用 Dify、回退完成事实,或使附件重新具备自动提交资格。 +- 本地解析器、对象存储或 Worker 超时/失败时,订单识别必须离开 `extracting` 并显示可重试的稳定错误码。 +- 同一 Intake 同时只允许一个订单识别 Run;已有 Run 处理中时,新请求必须复用相同快照或返回冲突。订单事实已持久化后,Worker 重试或迟到终态不得重复创建 Candidate/Task、回退完成事实,或使附件重新具备自动提交资格。 ### 3.x 唯一订单 Schema 与动态字段 @@ -586,12 +586,13 @@ - 本期不在 HXOPS 后端并行调用多个子 Agent,不合并多个 Dify 回答;多路召回与答案融合由聚合 Chatflow 承担。 ## 2026-07-22 订单抽取唯一 Manifest 与自动建单策略 -- 订单抽取只保留唯一、可冻结的 `execution_manifest`,不提供输入格式切换或回退。 -- Manifest 仅向模型提供压缩后的结构化字段候选,不传递版面坐标、HTML、token 或内部映射代码;确定性 accepted 字段不可被模型覆盖。 +- 订单抽取只保留由 HXOPS Worker 消费的请求快照与物化执行快照,不提供模型 `execution_manifest`、输入格式切换或回退。 +- 执行快照不向 Dify 传递版面坐标、HTML、token 或内部映射代码;确定性 accepted 字段只能由 HXOPS 规则与人工复核产生。 - 人工真值暂缓期间,版面候选保持 `needs_review`,质量验收与 95% 准确率目标延期,不得自动 accepted、自动建单或对外宣称达标。 - L6 要求所有 accepted Observation 具有稳定证据引用;无 cell 的纯文本表格只能形成复核原因,不能作为已验证后端表格证据。跨文档关联必须使用同 Document 强身份,禁止以 Qty 等常见值串接订单行。 - 自动建单配置位于“货代配置 → 订单字段模板”:管理员只维护一个自动建单总开关;每个字段独立标记为建单关键字段并设置自身最低置信度。每个 Run 冻结开关与字段快照;阈值不能绕过必填、证据、冲突、重复和 Reservation 等硬门禁。 - 终态且未消费的订单抽取 Run 支持“按当前规则重新识别”:创建新的可审计 Run,重新冻结当前 Schema、执行绑定、文档 Profile 与 ready 布局;旧候选在新版执行期间不可建单,新版失败后恢复旧版。失败 Run 的基础设施重试仍复用原冻结 Run,不得与重新识别混用。 -- **模板自动建单资格**:Profile 发布仅表示可作为受控解析候选,不等于可跳过 Dify。发布前必须有至少 1 份训练样本,且建立与训练/标注样本完全独立的盲测集;所有模板最低仅需 1 份独立样本,其中至少 1 份为多明细真值;声明跨页时还必须覆盖带 `continuation_of` 的续页样本。样本按管理员确认真值通过并由管理员批准后才允许发布;资格与正式 Profile checksum 绑定,checksum 变化立即失效。唯一命中的已批准 Profile 才可确定性建单,未知、多模板、行解析异常或未批准时一律回退 Dify/人工复核。 -- **Dify 证据边界**:Dify 输出只能使用冻结 `extraction_contract` 中的 field_id,所有 Observation 必须引用当前 Unit 文档且 quote 可在冻结输入中逐字验证;不得回传确定性上下文字段或覆盖已锁定值。Dify 画布由管理员在最终验收时手工配置,HXOPS 不修改画布。 +- **模板自动建单资格**:Profile 发布仅表示可作为受控解析候选,不等于自动冻结资格。发布前必须有至少 1 份训练样本,且建立与训练/标注样本完全独立的盲测集;所有模板最低仅需 1 份独立样本,其中至少 1 份为多明细真值;声明跨页时还必须覆盖带 `continuation_of` 的续页样本。样本按管理员确认真值通过并由管理员批准后才允许发布;资格与正式 Profile checksum 绑定,checksum 变化立即失效。唯一命中的已批准 Profile 才可确定性建单,未知、多模板、行解析异常或未批准时一律人工复核。 +- **Dify 边界**:订单抽取不向 Dify 发送字段契约、文档或 Observation,也不消费 Dify 输出。Dify 画布由管理员手工维护,仅提供只读问答与状态查询;HXOPS 不修改画布。 - **客户绑定与冻结**:订单原文、按 `order-customer-fingerprint.v1` 标准化生成的身份指纹、正式 `customer_id` 三层分离保存。Bill-to 是订购客户;只有已人工确认并写明理由的 Bill-to 匹配可以冻结为 Snapshot。调用方不能在冻结请求中自由传入客户或简码;Snapshot 固化客户简码和匹配规则版本,客户后续改名、合并或规则变化不回写历史。 +- **自动冻结资格范围**:模板发布资格与自动冻结资格继续分离。每个发布 Profile 版本的自动冻结资格必须独立保存客户白名单、业务场景白名单和“是否仍需客户确认”开关;新模板、新版本和新客户/场景默认人工确认。Run 只能消费当前版本资格和本轮已确认 Bill-to 客户来评估是否进入自动冻结门禁,未配置、越界、冲突或仍需客户确认时一律降级人工复核。 diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index eba0fa4b..0a961c8f 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -16,37 +16,24 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、OpenAPI、多文件批次解析、自动上传与 Agent 指令合集。 -## 2026-07-20 订单抽取异步改造基线(优先级最高) +## 2026-07-20 订单抽取异步改造基线(已废弃) -> 本节覆盖本文档中仍残留的“上传即生成 Candidate / 人工确认后建单 / 通知附件只回引 Hxops”等旧描述;如有冲突,以本节为准。 +> 本节仅保留为历史设计档案,不再作为实现或配置依据。当前有效结论以“订单抽取确定性执行收口(2026-07-28)”为准。 -```text -上传 EML/PDF/Word --> HXOPS 自动预处理 Intake + Document[](正文、附件文本、派生资产) --> 创建 ShippingOrderExtractionRun,冻结入口 Agent、会话、Intake/Document 正文和 published Schema --> 后台 Job 调用应用管理显式绑定的 shipping.order_extraction Provider(阶段 2) --> HXOPS 逐订单校验、Candidate 落库、订单级判重 --> Run 先进入 result_persisted,再进入 completed / needs_review --> 高置信订单自动建 Batch/Task;缺流程字段的 Task 停在补充门禁 -``` - -- **阶段 3 已完成的端到端边界**:新增 Run、Run-Intake 关系、Candidate/Extraction 追溯外键、独立 API、能力绑定、后台 Job/Workflow Worker,并已将聊天页订单附件切换为 Run 创建、轮询与刷新恢复。 -- **Run 是业务真相,Job 是执行尝试**:Run 状态为 `queued/running/result_persisted/completed/needs_review/failed/cancelled`;`result_persisted` 后禁止回退失败或取消。 +- 当前有效模型为:`上传 EML/PDF/Word -> HXOPS 预处理 Intake + Document[] -> 创建 ShippingOrderExtractionRun -> 按 PDF 建立 Unit 并写入 Progress Event -> 投影 Workspace Run 摘要与 Documents 详情 -> 用户按后端 available_actions 进入后续处理`。 +- **Run 是业务真相,Job 是执行尝试**:Run 状态固定为 `queued / processing / completed / partially_completed / review_required / failed / cancelled`;Unit 状态固定为 `pending / routing / matching_profile / extracting / merging_supplement / candidate_ready / review_required / failed / cancelled`。 +- **进度事实来自数据库**:前端只消费 Run 摘要、当前活动、文档详情和服务端动作按钮,不再展示 Workflow 节点阶段、Provider 状态、伪百分比或浏览器 SSE 进度。 - **输入快照不可变**:Run 保存 Document 正文、内容 hash、Schema definition/checksum;Worker 不得重新读取可变 Document 作为执行输入。 -- **并发与幂等**:服务端快照计算 idempotency key;相同输入返回同一 Run;同一 Intake 同时只允许一个 `released_at IS NULL` 的 Run。 -- **Provider 不写死**:阶段 2 由应用管理显式绑定 `shipping.order_extraction`;禁止名称匹配、固定 Agent/App ID 或环境变量回退。Dify Workflow 画布由管理员手工维护。 -- **Provider 成功结果先提交**:Worker 取得结构化 `orders` 后立即保存 `provider_result_json` 并提交,再执行 HXOPS 订单落库;即使 Dify 未返回 `workflow_run_id`,落库重试也不得再次调用 Dify。 -- **失败 Run 手工重试**:用户在订单识别失败卡片点击“重新识别”,调用 `POST /api/workspace/shipping-notice/order-extraction-runs/{run_no}/retry`。仅 `failed` 可重试;复用原 Run、冻结附件/正文、Schema、Provider 身份和 Intake 关系,不要求重新上传,也不创建新 Run。重试创建新的 Job 执行尝试;若 `provider_result_json.orders` 已保存,则跳过 Dify,只继续 HXOPS 落库。 -- **重新识别版本链**:终态且未消费的 Run 可调用 `POST /api/workspace/shipping-notice/order-extraction-runs/{run_no}/reparse` 创建新的 Run,原因仅允许 `rule_updated/field_mapping_error/document_quality/other`。新版重新冻结当前已发布的 Schema、Binding、Profile 和当前 ready 布局快照,不复用 Provider 成功缓存,也不在用户路径重跑 MinerU/OpenCV;旧候选在新版执行期间只读,新版失败后恢复旧版选择状态。仅当前版本 Candidate 可建单,旧版永远保留审计。 -- **订单抽取可观测进度(阶段化建设)**:订单抽取仍是后台异步作业。HXOPS 服务端消费专用 Workflow 的 Dify SSE 节点事件,按节点类型自动投影为脱敏业务阶段;浏览器只通过自适应短轮询读取 Run 投影,不建立新的浏览器长 SSE。Dify Workflow 无需新增节点、标记或其他手工配置。 -- **变更边界**:Run 冻结 Provider App ID、Base URL、timeout 和 max attempts;App ID/Base URL 漂移阻断旧 Run,API Key 不入快照并允许轮换。用户态 Run API不返回正文、Provider 快照、原始结果或配置。 -- **阶段 0 Review 门禁**:已执行的 Alembic revision 不得继续追加模型字段;`provider_config_json/provider_snapshot_json` 由后续独立 revision 增加。进入下一阶段前必须确认数据库处于唯一 head、模型可完整查询 Candidate/Extraction/Run,并通过迁移往返、Run 服务和能力绑定 Worker 测试。 +- **并发与幂等**:服务端快照计算 idempotency key;相同输入返回同一 Run;同一 Intake 同时只允许一个活动 Run。 +- **失败 Run 手工重试**:用户在订单识别失败卡片点击“重试失败附件”,调用 `POST /api/workspace/shipping-notice/order-extraction-runs/{run_no}/retry`。仅 `failed` 可重试;复用原 Run、冻结附件/正文、Schema、解析器/策略版本和 Intake 关系,不要求重新上传,也不创建新 Run。 +- **重新识别版本链**:终态且未消费的 Run 可调用 `POST /api/workspace/shipping-notice/order-extraction-runs/{run_no}/reparse` 创建新的 Run,原因仅允许 `rule_updated/field_mapping_error/document_quality/other`。新版重新冻结当前已发布的 Schema、Profile、解析器/策略和当前 ready 布局快照,不复用旧单元结果;仅当前版本 Candidate 可建单,旧版永远保留审计。 +- **变更边界**:Run 冻结解析器版本、策略版本、超时和最大尝试次数;运行时版本漂移安全阻断旧 Run。用户态 Run API 不返回正文、解析快照、原始结果或内部配置。 -### 2026-07-21 文档级抽取优化实施阶段与 Review 门禁 +### 2026-07-21 文档级抽取优化历史阶段与 Review 门禁 > 本路线描述“避免把邮件和全部附件一次性丢给单个 LLM”的目标架构,不沿用旧整单/整封邮件单次模型调用作为兼容路径。各阶段必须按顺序实施;阶段内测试、自检和 Review 的阻断问题全部关闭并满足验收标准后,才能自动进入下一阶段。Dify 画布由管理员按本文档手工修改,代码阶段不直接操作 Dify。 -目标数据流固定为:`冻结 Run -> 抽取计划 -> 确定性邮件/表格解析 -> 文档级抽取单元 -> 受控并行的无状态 Dify 调用 -> 必要时邮件关系抽取 -> HXOPS 跨文档合并/冲突裁决 -> 严格 Schema 校验 -> Candidate/Task 持久化`。Dify 只承担无状态候选抽取;HXOPS 始终负责计划、重试、合并、审计、业务状态和持久化。 +目标数据流固定为:`上传快览 -> 轻量请求 Run -> Worker 物化首轮附件 -> 文档级确定性抽取单元 -> 必要时邮件关系合并 -> HXOPS 跨文档裁决 -> 严格 Schema 校验 -> Candidate/Task 持久化 -> 条件满足时仅冻结`。订单抽取主链不调用 Dify;Dify 仅保留独立的只读问答与状态查询。 | 优化阶段 | 实现目标 | Review 关键节点 | 阶段验收标准 | | --- | --- | --- | --- | @@ -61,37 +48,37 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open 每个阶段 Review 统一检查:数据和状态单调性、幂等/并发、权限与隐私、错误恢复、Schema 冻结、可观测性、迁移/回滚、测试覆盖、文档/Dify 手工说明。阶段验收证据必须来自当前代码、迁移、测试/构建输出和文档,不能仅以实现意图或窄范围单测替代。 -**阶段 0 当前结论(2026-07-21)**:Run 已保存版本化当前阶段、活动/已完成阶段、最近活动和健康投影;Dify Workflow 生命周期由可选观察器写入独立短事务,重复事件去重,终态及 `hxops_persistence` 防回退。用户摘要和按需时间线只返回通用阶段码、状态和时间;Workflow Run ID、节点执行 ID/类型/标题、Job、Provider、Prompt、正文、输出和异常堆栈均不进入用户契约,自定义节点标题不持久化。迁移 `a63b4c5d6e7f -> a64c5d6e7f80` 有独立 upgrade/downgrade 测试;前端按进度版本更新持久化状态并显示四语言阶段文案,仍使用不确定进度条。 +**阶段 0 当前结论(2026-07-21)**:Run 已保存用户态汇总、当前活动、可操作按钮和健康投影;Progress Event 由订单域独立短事务写入,重复事件去重,终态与迟到事件均受保护。用户摘要和按需详情只返回稳定业务状态、事件码和时间;Workflow Run ID、节点执行 ID/类型/标题、Job、Provider、Prompt、正文、输出和异常堆栈均不进入用户契约,自定义节点标题不持久化。迁移与前后端契约已有独立测试,前端按事实版本更新持久化状态并显示四语言文案,不再依赖旧 Workflow 阶段。 -**阶段 0 Dify 手工配置**:无需修改画布、节点名称、Prompt、Start/End 变量或 OpenAPI。进度映射仅消费 Dify 原生 Workflow/节点事件,节点标题不会作为业务阶段依据。 +**阶段 0 Dify 手工配置**:无需修改画布、节点名称、Prompt、Start/End 变量或 OpenAPI。订单抽取进度由 HXOPS 后端事实生成,不依赖 Dify 节点事件或节点标题。 -**阶段 1 当前结论(2026-07-21)**:Run 锁定版本的完整 `definition_json` 已成为确定性订单表格解析的唯一业务配置来源。解析器只使用已启用字段的 `field_code + display_name + aliases` 编译冻结表头契约,不再维护业务别名常量,不读取当前 published 版本,也不在缺少契约时猜测表头。保存草稿和发布版本都会拒绝标准化后跨字段别名碰撞,并拒绝把 Allocation ID、Parent Allocation ID、Commodity Group ID、Supplier Code、UUID、Internal ID 配置为 Reservation ID 表头。同一字段命中多列时不静默选首列,而是记录 `deterministic_table_issues` 并进入复核。后端不再扫描任意单元格猜 Reservation ID,不把文档级 Reservation 广播到所有明细行,也不会为 Schema 未启用的 UOM、币种、金额等字段注入默认值或派生值。冻结的 retired 版本继续按自身别名解析,上传预处理若在任务边界选择当前 published Schema,也只生成提示,不替代正式 Run 的冻结真值。 +> **历史归档说明(2026-07-28)**:下列阶段 1–5 的 Dify/Manifest 描述记录了 2026-07-21 的设计过程,已经被本节“上传快览与发送门禁”和阶段 3 Dify 手工配置结论取代。订单抽取当前不调用 Dify,所有 `execution_manifest`、Provider、模型输入和模型重试配置均不适用于订单抽取;保留这些段落仅用于审计设计演进。 -**阶段 1 Dify 手工配置**:无需修改画布、Prompt、Start/End 变量或 Code 节点。管理员只需在 HXOPS 已发布订单 Schema 中完整维护确定性表格别名;别名冲突或 Reservation 安全禁用表头会阻止保存/发布,重复业务列会转人工复核。Dify 继续只按 `execution_manifest.extraction_contract` 返回允许的稳定字段 ID 与逐字证据,不得复制后端表头映射、覆盖确定性结果或回传 `readonly_hints`。 +**阶段 1 历史结论(2026-07-21)**:Run 锁定版本的完整 `definition_json` 已成为确定性订单表格解析的唯一业务配置来源。解析器只使用已启用字段的 `field_code + display_name + aliases` 编译冻结表头契约,不再维护业务别名常量,不读取当前 published 版本,也不在缺少契约时猜测表头。保存草稿和发布版本都会拒绝标准化后跨字段别名碰撞,并拒绝把 Allocation ID、Parent Allocation ID、Commodity Group ID、Supplier Code、UUID、Internal ID 配置为 Reservation ID 表头。同一字段命中多列时不静默选首列,而是记录 `deterministic_table_issues` 并进入复核。后端不再扫描任意单元格猜 Reservation ID,不把文档级 Reservation 广播到所有明细行,也不会为 Schema 未启用的 UOM、币种、金额等字段注入默认值或派生值。冻结的 retired 版本继续按自身别名解析,上传预处理若在任务边界选择当前 published Schema,也只生成提示,不替代正式 Run 的冻结真值。 -**阶段 2 当前结论(2026-07-21)**:每个新建 Run 在同一事务创建唯一 `ShippingOrderExtractionPlan`,计划以版本号和 `input_snapshot_hash` 锚定冻结输入;每个冻结 Document 在计划内唯一形成 `ShippingOrderExtractionUnit`。邮件正文单元类型为 `email_relation`,附件为 `document_extraction`,单元只保存 Intake/Document/内容哈希引用,不复制正文。`(document_id, intake_id)` 复合外键阻止跨 Intake 挂接;局部状态机只允许 `pending -> running -> succeeded/failed`、`failed -> pending` 重试或 `pending -> skipped`,成功结果不会因其他单元失败而被清除,计划汇总为 `planned/running/completed/partial_failed/failed`。创建重入和 Worker 恢复均复用同一计划。本阶段尚未改变现有 Provider 调用粒度;单元级最小输入在阶段 3 接入,受控并行和局部重试在阶段 4 接入。 +**阶段 1 历史 Dify 配置**:此段不再适用订单抽取。当前无需为订单抽取配置画布、Prompt、Start/End 变量、Code 节点或 `execution_manifest`;Schema 别名只在 HXOPS 管理端维护。 -**阶段 2 Dify 手工配置**:无需修改画布。计划和单元完全由 HXOPS 持久化,Dify 当前仍接收既有 `execution_manifest`;不要新增子任务 ID、计划状态或调度节点。阶段 3 文档更新后再按新的单元级输入契约手工调整。 +**阶段 2 历史结论(2026-07-21)**:每个新建 Run 在同一事务创建唯一 `ShippingOrderExtractionPlan`,计划以版本号和 `input_snapshot_hash` 锚定冻结输入;每个冻结 PDF Document 在计划内唯一形成 `ShippingOrderExtractionUnit`。邮件正文不再作为一级执行单元,而是并入对应 PDF 的补充事实。`(document_id, intake_id)` 复合外键阻止跨 Intake 挂接;局部状态机只允许 `pending -> routing -> matching_profile -> extracting -> merging_supplement -> candidate_ready/review_required/failed/cancelled`,失败重试仅通过新的 attempt 追加事实,不覆盖历史。成功结果不会因其他单元失败而被清除,Run 最终按文档汇总为 `completed / partially_completed / review_required / failed`。创建重入和 Worker 恢复均复用同一计划。 -**阶段 3 当前结论(2026-07-21)**:Worker 当前按计划顺序处理单元。每个单元先使用 Run 冻结 Schema 执行确定性表格解析;只有所有 required Header/Line 字段均可由明确列关系形成逐字证据时,才直接生成动态订单并以 `execution_mode=deterministic` 成功收口,Dify 调用为零。无法完整确定的单元才调用 Dify;唯一 `execution_manifest` 只含当前 `unit`、当前 Intake 的受控只读提示和一个冻结 Document。兄弟附件、整封邮件拼接和完整 Schema definition 均不进入模型输入。模型输出的 `source_intake_no`、`primary_document_id` 和每条 Observation `document_id` 必须全部等于当前单元,否则在局部结果落库前拒绝。所有单元结果按计划顺序汇总后,仍进入 HXOPS 现有严格 Schema、逐字证据、Reservation 安全和 Candidate/Task 门禁。 +**阶段 2 历史 Dify 配置**:此段不再适用订单抽取;当前无需配置 `execution_manifest` 或单元级输入契约。 -**上传与布局准备状态(2026-07-27)**:`parse_status=parsed` 仅代表 EML/附件文本预处理完成,不代表独立文档布局任务已经终结。Intake 状态响应额外返回 `layout_status=processing/completed/not_required` 与脱敏数量汇总;聊天页在任一布局版本仍为 `queued/running` 时持续轮询、显示“正在解析订单版面”并禁止创建 Run。所有已调度布局版本进入 `ready/needs_review/failed/unsupported` 后统一视为 `completed`,其中失败或不支持不永久阻断用户,后续仍可使用已抽取文本和 Dify 兜底。后端 `ORDER_EXTRACTION_LAYOUT_PENDING` 门禁保留,防止绕过前端冻结空布局快照。 +**阶段 3 历史结论(2026-07-21)**:Worker 当前按计划顺序处理单元。每个单元先使用 Run 冻结 Schema 执行确定性表格解析;只有所有 required Header/Line 字段均可由明确列关系形成逐字证据时,才直接生成动态订单并以 `execution_mode=deterministic` 成功收口,Dify 调用为零。无法完整确定的单元才调用 Dify;唯一 `execution_manifest` 只含当前 `unit`、当前 Intake 的受控只读提示和一个冻结 Document。兄弟附件、整封邮件拼接和完整 Schema definition 均不进入模型输入。模型输出的 `source_intake_no`、`primary_document_id` 和每条 Observation `document_id` 必须全部等于当前单元,否则在局部结果落库前拒绝。所有单元结果按计划顺序汇总后,仍进入 HXOPS 现有严格 Schema、逐字证据、Reservation 安全和 Candidate/Task 门禁。 -**阶段 3 Dify 手工配置(必须由管理员执行)**:Start 节点只保留一个 String 输入 `execution_manifest`。模型节点只读取 `document`,并把 `unit.intake_no` 写入每个订单的 `source_intake_no`、`unit.document_id` 写入 `primary_document_id` 和所有 Observation 的 `document_id`。不得遍历或期待多个 Intake/Document,不得从外部回读兄弟附件。End 仍只输出 `orders`。确定性完整表格不会进入 Dify,因此 Workflow 必须允许单个非表格/不完整文档返回零个或多个订单。 +**上传快览与发送门禁(2026-07-28)**:`parse_status=parsed` 仅代表 Intake 快览完成。对 EML,上传阶段只读取邮件头、正文、白名单 HTML 表格快照与附件目录,不抽取附件全文、不创建附件 Document/派生资产,也不调度布局、MinerU 或 OCR。Intake 状态响应额外返回 `preview_status`、`ready_for_extraction`、`attachment_directory_complete` 与附件目录脱敏汇总;聊天页快览成功后显示“已就绪/已发现 N 个附件”并允许发送。真正的布局、深度解析和订单识别只在点击发送后由 Run/计划链路按需触发,上传阶段不再以 `layout_status` 阻塞发送。 -**阶段 4 当前结论(2026-07-21)**:非确定性单元以 Run 冻结的 `unit_concurrency=2..4` 受控并行调用 Dify;线程只持有冻结 Run/Unit 和 Provider 网络字段的纯快照,不共享 ORM Session。每个单元按 `unit_max_attempts=1..3` 独立重试,并使用 `unit_retry_backoff_ms=100..5000` 指数退避加抖动;已成功和确定性单元不重跑。主线程串行写入单元状态、结果、attempt 和 latency,并按冻结 position 汇总,完成顺序不改变业务顺序。任一单元耗尽局部重试后保留其他成功结果,再由 Job 重试恢复失败单元;全局 Provider 治理与熔断在阶段 6 完成。 +**阶段 3 Dify 手工配置**:无需为订单抽取配置 `execution_manifest`、附件输入、模型节点、重试节点或 `orders` 输出。订单抽取的附件选择、深度解析、模板路由、人工复核和 Candidate 裁决均由 HXOPS Worker 执行;无法确定识别的文档保持人工复核,绝不回退到 Dify。 -**阶段 4 Dify 手工配置**:画布无需新增并行或重试节点,继续按唯一单文档 Manifest 执行。并发、局部重试和退避全部由 HXOPS Worker 管理;不要在 Dify 内叠加循环重试。 +**阶段 4 历史结论(2026-07-21)**:非确定性单元以 Run 冻结的 `unit_concurrency=2..4` 受控并行调用 Dify;线程只持有冻结 Run/Unit 和 Provider 网络字段的纯快照,不共享 ORM Session。每个单元按 `unit_max_attempts=1..3` 独立重试,并使用 `unit_retry_backoff_ms=100..5000` 指数退避加抖动;已成功和确定性单元不重跑。主线程串行写入单元状态、结果、attempt 和 latency,并按冻结 position 汇总,完成顺序不改变业务顺序。任一单元耗尽局部重试后保留其他成功结果,再由 Job 重试恢复失败单元;全局 Provider 治理与熔断在阶段 6 完成。 -**阶段 5 当前结论(2026-07-21)**:HXOPS 在所有成功单元完成后按冻结 Schema 的稳定 `field_id -> field_code` 合并订单。同一 Intake 内仅当 Header 的唯一 `po_number` 一致,或至少一条 Line 的唯一 `(part_number, reservation_id)` 组合相同时才判为同一订单;只有料号、数量或弱文本相似度绝不合并。合并只追加并去重 Observation,不选值、不覆盖冲突,Qty/金额/日期等不同值继续由现有动态字段裁决形成阻断冲突。没有可靠身份的订单保持拆分。单元耗尽局部重试时,其他成功单元仍进入 HXOPS 提交;失败单元保留 `failed` 状态,Run 以 `needs_review` 收口并返回 `failed_unit_count`,不会把部分成功伪装成 completed。 +**阶段 4 Dify 手工配置**:无需修改画布。订单抽取的受控并发、局部重试和退避全部由 HXOPS Worker 管理;不要在 Dify 内新增任何订单抽取循环、重试或文件处理节点。 -**阶段 5 Dify 手工配置**:无需修改画布。Dify 仍只返回当前单文档的候选订单和证据,不负责跨附件合并、冲突裁决或部分成功决策;不要在 Prompt 中要求模型猜测其他附件或生成全局订单 ID。 +**阶段 5 历史结论(2026-07-21)**:HXOPS 在所有成功单元完成后按冻结 Schema 的稳定 `field_id -> field_code` 合并订单。同一 Intake 内仅当 Header 的唯一 `po_number` 一致,或至少一条 Line 的唯一 `(part_number, reservation_id)` 组合相同时才判为同一订单;只有料号、数量或弱文本相似度绝不合并。合并只追加并去重 Observation,不选值、不覆盖冲突,Qty/金额/日期等不同值继续由现有动态字段裁决形成阻断冲突。没有可靠身份的订单保持拆分。单元耗尽局部重试时,其他成功单元仍进入 HXOPS 提交;失败单元保留 `failed` 状态,纯业务拒识单元保留 `review_required` 状态,Run 按汇总事实收口为 `partially_completed` 或 `review_required`,不会把部分成功伪装成 `completed`。 -**阶段 6 当前结论(2026-07-21)**:Runtime Binding 新增并冻结 `max_model_units=1..100`、`provider_max_concurrency=1..20`、`circuit_failure_threshold=2..20`、`circuit_cooldown_seconds=10..600`。确定性解析后仍需模型的单元数超过预算时,在任何 Dify 请求前失败;同一进程内相同 Provider 共享并发信号量,防止多个 Run 合计突破容量;连续可重试失败达到阈值后短期开路,成功调用清零。管理员只读诊断新增单元 position/type/status/attempt/duration/error_code,不返回文件名、正文、quote、orders、Prompt、Provider 配置或凭据;访问继续写入原有诊断审计。用户 Run API 不新增内部单元字段。 +**阶段 5 历史 Dify 配置**:此段不再适用订单抽取;当前 Dify 不返回订单候选或证据,也不参与跨附件合并、冲突裁决或部分成功决策。 -**阶段 6 Dify 手工配置**:无需修改画布。预算、Provider 并发和熔断全部由 HXOPS 管理;Dify 继续保持单文档无状态执行。管理员只在 HXOPS Runtime Binding 配置治理参数,不要在 Dify 内复制限流、循环重试或熔断逻辑。 +**阶段 6 当前结论**:订单抽取 Worker 不调用 Dify;管理员诊断只展示脱敏单元 position/type/status/attempt/duration/error_code,不返回文件名、正文、quote、orders、Prompt 或凭据。用户 Run API 不新增内部单元字段。 -**阶段 7 当前结论(2026-07-21)**:自动建单由 Run 冻结的 `auto_create_enabled` 硬门禁控制,默认 `false`;它必须同时满足 Schema 总开关、`shipping.order_extraction` Runtime Binding 显式开启及已批准质量批次,任一层关闭即冻结为影子模式。关闭时仍完整持久化 Extraction、Decision、FieldValue、Candidate、重复检测和客户影子识别;满足全部业务门禁的 Candidate 保持 `validation_status=ready`、`selected=false`,增加 `auto_create_disabled` 待审原因,不创建或打开 Task。开启后也不能绕过分类置信度、必填/流程字段、逐字证据、动态 Schema、Reservation 安全、冲突和重复决策门禁。生产代码和测试只维护唯一 Manifest 契约。 +**阶段 7 当前结论**:自动建单由 Run 冻结的 Schema 人工确认策略控制,默认 `false`;关闭时仍完整持久化 Extraction、Decision、FieldValue、Candidate、重复检测和客户影子识别,但不创建或打开 Task。开启后也不能绕过分类置信度、必填/流程字段、逐字证据、动态 Schema、Reservation 安全、冲突和重复决策门禁。 ### L5 紧凑模型契约(2026-07-22) @@ -123,7 +110,7 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open - 纯文本表格即使字段齐全也必须进入模型补充和后端 needs_review 门禁。Profile 发布本身只提供紧凑候选;只有唯一命中的 Profile 已完成独立盲测资格(至少 1 份样本通过、管理员批准且 checksum 未漂移)时,才可由该 Profile 的实际解析行零 Provider 建单。 - Profile 仍可生成不含 HTML/bbox/token 的紧凑候选供模型参考,并继续执行零 Qty 删除等候选清洗,但未获得 accepted cell 前不能直接生成订单。 - 自动建单只能在质量门禁满足时由 Schema 策略开启;它不依赖 Dify 输入格式开关。 -- L7 最终工程 Review 覆盖 L0-L7 布局、Intake、Schema、订单抽取、Runtime Binding、质量门禁与迁移共 `247 passed`;前端生产构建通过。该记录的历史基线 head 为 `a72f8091a2b8`;当前货代履约链部署必须以 `023a4b5c6d7e` 为唯一 Alembic head,`git diff --check` 通过。静态检查确认 `build_deterministic_unit_orders` 不再调用纯文本表格解析器。 +- L7 最终工程 Review 覆盖 L0-L7 布局、Intake、Schema、订单抽取、质量门禁与迁移;当前部署以 Alembic 唯一 head 为准。静态检查确认 `build_deterministic_unit_orders` 不再调用纯文本表格解析器。 **L7 当前验收结论:未通过,不得开启自动建单。** 缺少人工单元格真值、真实字段准确率/召回率、解析性能指标、100 个影子 Run、20 个测试环境真实 Run、业务/技术负责人批准及 Dify 实际配置验收。当前完成的是安全切换准备,不是 L7 完成。 @@ -136,7 +123,7 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open 1. 保持 `auto_create_enabled=false`,选择至少 100 个已脱敏真实 Run,覆盖纯确定性表格、PDF/Word、邮件正文关系、多附件同订单、多订单、冲突、缺 Reservation、低质量扫描、非发货内容、Provider 超时和重复订单。 2. 由业务双人复核 Candidate,与人工金标准逐字段比较。核心字段 `part_number/qty/reservation_id/po_number` 精确率不得低于 99.5%,召回率不得低于 98%;订单错误合并和错误拆分各不得超过 0.5%;错误自动建单必须为 0(影子期本身应为零 Task)。 3. 所有阻断冲突必须保留双方 document/quote 证据;失败单元、预算阻断、熔断和部分成功必须可在管理员诊断定位,且诊断响应不得包含正文、orders、Prompt 或凭据。 -4. 达标并经业务负责人、技术负责人书面批准后,在入口 Agent Runtime Binding 开启 `auto_create_enabled=true`。先在测试环境运行不少于 20 个真实脱敏 Run,再发布生产;任一错误建单立即关闭开关,已生成 Task 按既有人工修订/作废流程处理。 +4. 达标并经业务负责人、技术负责人书面批准后,在订单 Schema 的自动建单策略中开启。先在测试环境运行不少于 20 个真实脱敏 Run,再发布生产;任一错误建单立即关闭开关,已生成 Task 按既有人工修订/作废流程处理。 **阶段 7 Dify 手工配置**:确认 Start 只含 String 类型 `execution_manifest`,所有 Code/LLM/End 节点只接受本手册定义的唯一 Manifest;删除任何按文档集合遍历、整封邮件拼接、输入格式判断、跨附件合并和画布内自动建单逻辑。End 只输出当前 Unit 的 `orders`。 @@ -511,84 +498,61 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工 #### 产品与状态边界 -- Run 是订单抽取的唯一业务真相;Job 仅代表一次执行尝试,Dify Workflow 成功不等于 HXOPS 订单已落库。只有 Run 进入 `completed` 或 `needs_review` 才是业务终态。 -- `needs_review` 的含义固定为“识别已完成,但需要用户处理”;它不是失败,不显示重新识别入口。 -- 同一 `user_id + owner_agent_id + conversation_id` 同时最多一个 `queued/running/result_persisted` Run;不同会话可并行。现有 Intake 单活跃约束继续生效。 -- 用户卡片默认只显示当前阶段、运行时长、最近真实活动和健康提示;用户按需展开归并后的阶段时间线。管理端才可查看脱敏节点生命周期与 Job Attempt。 -- 不展示模型思考、Prompt、节点输入输出、文档正文、原始订单、密钥、Provider 配置或异常堆栈;用户端不返回 Workflow Run ID、节点类型或 Job 信息。管理员附件名默认脱敏,列表仅显示附件数量。 -- 自定义节点标题可能包含客户或业务意图,阶段 0 起不进入事件表、去重指纹或用户 API;阶段映射只能读取受控事件类型和技术节点类型。 +- Run 是订单抽取的唯一业务真相;Job 仅代表一次执行尝试。Run 终态固定为 `completed / partially_completed / review_required / failed / cancelled`,其中 `review_required` 表示全部 PDF 都是业务拒识,`partially_completed` 表示成功与人工处理并存。 +- Unit 是 PDF 级处理单元,状态固定为 `pending / routing / matching_profile / extracting / merging_supplement / candidate_ready / review_required / failed / cancelled`;一份 PDF 的拒识或失败不得覆盖其他 PDF 已有结果。 +- 同一 `user_id + owner_agent_id + conversation_id` 同时最多一个 `queued / processing` Run;不同会话可并行。现有 Intake 单活跃约束继续生效。 +- 用户卡片只显示后端事实投影:Run 汇总、当前文件、当前业务动作、可操作按钮,以及按 PDF 打开的详情抽屉。用户端不再展示 Workflow、节点、Provider、LLM、伪百分比或内部运行标识。 +- 用户接口不得返回正文、原始订单、Prompt、密钥、Provider 配置、异常堆栈、绝对路径、MinIO 地址、Workflow Run ID、节点类型或 Job 信息。管理员诊断继续只读、脱敏并与用户契约分层。 -#### 自动阶段映射与归并 +#### 业务事件与工作台投影 -| 阶段码 | 事实来源 | 用户文案语义 | +| event_code | 业务含义 | 用户展示 | | --- | --- | --- | -| `queued` | Run/Job 排队 | 等待后台执行 | -| `workflow_accepted` | `workflow_started` | 已连接识别服务 | -| `document_processing` | 文档处理类节点 | 正在解析邮件及附件 | -| `order_recognition` | LLM 类节点 | 正在识别订单信息 | -| `result_processing` | Code/Template/参数处理类节点 | 正在整理和校验结果 | -| `provider_result_ready` | 成功 `workflow_finished` | 识别完成,正在保存结果 | -| `hxops_persistence` | HXOPS Candidate/Task 持久化 | 正在生成订单任务 | -| `auto_recovering` | Job 自动重试或 Provider 结果补偿查询 | 系统正在自动恢复 | +| `document_queued` | 文档已排入后台处理 | 已接收附件,等待处理 | +| `profile_matching` | 正在匹配模板 | 当前 PDF 正在匹配已发布模板 | +| `profile_matched` | 已唯一命中模板 | 已找到模板,继续提取字段 | +| `table_reconstructed` | 订单表格已恢复 | 正在校验表格与字段 | +| `order_fields_extracted` | 关键字段已提取 | 正在整理订单候选 | +| `email_supplement_merged` | 正文补充已合并 | 正在合并 Reservation / Source Type 等补充信息 | +| `candidate_ready` | PDF 候选已生成 | 可进入人工确认 | +| `review_required` | 业务拒识 | 需要人工复核 | +| `technical_retrying` | 技术失败后重试中 | 系统正在重试失败附件 | +| `technical_failed` | 技术失败 | 可重试失败附件 | +| `run_completed` | 本次 Run 汇总完成 | 显示最终结论与下一步操作 | -- 映射只根据 Dify 节点类型,不依赖节点 ID 或名称;未知节点降级为通用“正在处理识别任务”。LLM/Code 节点的具体业务目的不可可靠推断,禁止输出过度具体的业务断言。 -- 并行节点保存活动阶段集合;用户主卡按受控优先级选择或组合当前阶段,相同阶段合并。终态和 `hxops_persistence` 不得被迟到 Dify 事件覆盖;管理员原始时间线仍保留可用的迟到事件。 -- 无可信 `current/total` 时只显示阶段和不确定进度动画,禁止伪百分比;真实计数存在时才可展示 `current/total`。 -- Dify 没有发送节点事件时,必须降级为 `queued -> workflow_accepted -> 通用识别 -> hxops_persistence -> 终态`,不得影响订单结果。 +- 用户工作台主接口固定返回 `summary / current_activity / available_actions`;详情接口固定返回按 PDF 归并的 `documents[]`。所有计数、当前活动和按钮权限均由后端计算,前端不得自行猜测。 +- `available_actions` 由服务端根据 Run/Unit 当前状态下发;聊天卡片只渲染 `view_details / enter_manual_review / retry_failed_attachments`,详情项只渲染 `view_evidence / review_candidate / manual_review`。 +- 事件必须是已经发生并持久化的事实,前端只根据 `event_code` 做 i18n 文案映射;不允许把 Dify 节点标题或自定义显示文本当作业务阶段。 #### 事件、健康与恢复 -- 通用 Dify 层标准化 `workflow_started/node_started/node_finished/workflow_finished/error/stream_interrupted/poll_started/retry_started/recovered`,仅通过可选观察器上报;不得写入货代业务状态,也不得因观察器或进度落库失败中断 Workflow。 -- 订单域使用独立短事务持久化进度事件和 Run 投影,不能复用长时间 Worker 业务事务。事件优先以 `workflow_run_id + node_execution_id + event_type` 去重;字段不全时使用受控指纹。重复心跳只更新最近活动时间。 -- 阈值由后端统一计算:60 秒无新活动只在详情提示;主卡慢响应阈值为 `max(60 秒, 同 Provider 最近30天终态 Run 总耗时 P95)`,最高 300 秒;样本少于20个时使用 60 秒。展示阈值不终止、不重试任务,真实超时仍沿用现有 Worker/Provider 策略。 -- 短暂抖动仅记录管理端时间线;进入自动重试或补偿查询才在用户端提示。Worker 重启时,已有 Provider 结果必须直接续做 HXOPS 落库;无结果但已有 Workflow Run ID 时优先查询原 Workflow,避免重复执行。 +- 订单域使用独立短事务持久化 Progress Event、Run 摘要和文档详情投影,不能复用长时间 Worker 业务事务。事件以幂等键和序号去重;重复执行、迟到事件与终态保护必须保证事实不倒退。 +- 浏览器仅使用短轮询读取 Run 与 Documents 投影;网络失败只标记“暂时无法刷新状态”,不能把业务 Run 判成失败。页面刷新、重新登录和 Worker 重启后必须恢复到同一事实视图。 +- 健康阈值由后端统一计算:60 秒无新活动只在详情提示;积压判断基于 `queued / processing` 的持续时长与最终失败率。展示阈值不终止、不重试任务,真实超时仍沿用现有 Worker 策略。 #### 待查看、管理诊断与保留 -- 新功能上线后产生的 `completed/needs_review/failed` Run 创建待查看标记;用户进入对应会话且终态卡片成功加载后才确认已查看。会话历史显示未查看数量和严重级别;仅加载列表、后台预取或失败请求不得清除。 +- 新功能上线后产生的 `completed / partially_completed / review_required / failed` Run 创建待查看标记;用户进入对应会话且终态卡片成功加载后才确认已查看。会话历史显示未查看数量和严重级别;仅加载列表、后台预取或失败请求不得清除。 - 管理入口固定为“货代管理 → 订单识别 → 识别任务”,所有现有管理员可只读访问;不新增权限点,不提供管理员重试、取消、强制完成、导出或状态修改。 -- 管理端访问记录订单域诊断审计:列表与详情访问分别记录一次;详情包含 Workflow Run ID、Job Attempt、节点时间线。审计仅保留筛选摘要,绝不保存正文或输入输出。 -- 进度明细保留90天,Run摘要、阶段累计耗时、Job Attempt和最终错误码长期保留。默认排程 `shipping-order-extraction-progress-cleanup` 每日 03:15(Asia/Shanghai)分批清理明细;清理失败不得影响主链路并在下一次排程重试。 +- 管理端访问记录订单域诊断审计:列表与详情访问分别记录一次;详情包含 Job Attempt、Unit 诊断和脱敏事件时间线。审计仅保留筛选摘要,绝不保存正文或输入输出。 +- 进度明细保留 90 天,Run 摘要、阶段累计耗时、Job Attempt 和最终错误码长期保留。默认排程 `shipping-order-extraction-progress-cleanup` 每日 03:15(Asia/Shanghai)分批清理明细;清理失败不得影响主链路并在下一次排程重试。 + +#### 2026-07-28 Dify 手工配置说明 + +- 本次重构只切换“订单解析进度与结果展示”模型;**Dify 不再承担任何进度生成职责**。用户卡片、详情抽屉、会话待查看和刷新恢复全部来自 HXOPS 的 Run / Unit / Progress Event 数据库事实。 +- 管理员手工调整 Dify 画布时,**不需要**为进度新增节点、变量、输出字段或节点命名约定;节点标题、节点类型、执行百分比和中间文本都不会进入用户展示。 +- 若当前 Workflow 仍参与订单候选内容抽取,Dify 只需维持既有候选输出契约;**禁止**输出或依赖 `workflow_accepted`、`provider_result_ready`、`current_stage_code`、`progress`、`shipping_order_extraction_state`、`_hxops_*progress*` 等进度字段。 +- 允许继续维护的仅是候选内容相关配置,例如 `orders` 结构、字段证据、单文档输入约束和正文补充关联规则;这些调整只影响抽取结果,不影响前端进度卡的显示逻辑。 - **上传阶段不调用 LLM、不生成 Candidate、不判订单重复**:规则解析只作为 `rule_hints`,Candidate 只在后台 Workflow 结果通过 HXOPS 提交服务后生成。 - **一封 EML 仍是一个 Intake**;一个 Document 可以产生多个 Candidate;跨附件同一订单由 LLM 合并并以一个主 Document、多个 evidence 记录来源。 - **判重粒度是订单 Candidate,不是整封邮件或单个附件**:附件 hash 是证据之一,最终通过身份指纹 + 内容指纹区分完全重复与可能修订。 - **自动建单硬条件**:`classification=shipping_request`、至少一条合法 `part_number` + 正数 Qty、分类与 `part_number`/Qty 置信度达阈值、两者均有非空原文证据、无阻断冲突、无必须人工决策的修订。 +- **自动建单硬条件**:`classification=shipping_request`、至少一条合法 `part_number` + 正数 Qty、分类与 `part_number`/Qty 置信度达阈值、两者均有非空原文证据、无阻断冲突、无必须人工决策的修订。 - **流程字段允许缺失**:Reservation ID 缺失不阻止 Task 创建,但会阻止库存、匹配、Excel 与上传;自然对话补齐后重新进入解析确认。订单行 `inventory_source_hint` 可选,不单独触发门禁。 -### 阶段 2 应用管理与 Dify Workflow 手工配置 +### 阶段 2 订单抽取执行边界 -1. 在 HXOPS“应用管理”创建一个内部 Provider:`runtime_provider=dify`、`dify_app_type=workflow`、`exposure_mode=internal`,填写对应 Dify App ID、API Base URL 和 API Key并启用。 -2. 编辑货代发货通知 Agent,在“后台业务能力绑定”中指定“订单抽取服务” Provider,并配置 `timeout_seconds`(30–3600)和 `max_attempts`(1–10)。保存后写入 `agent_runtime_bindings`;新表单不再勾选启用,绑定存在即表示该必需能力启用;后端旧 `enabled` 字段仅为历史 API/运维停用兼容。 - -订单抽取服务的技术约束由货代 Agent Catalog 的 `required_runtime_capabilities.shipping.order_extraction` 声明;管理员在应用侧从启用的内部 Dify Workflow 中选择执行器,业务用途以 Runtime Binding 为准。 - -3. Dify Workflow Start 节点只增加一个 string 输入:`execution_manifest`。该 JSON 字符串固定含 `run.run_no`、`unit`、`integrity.input_snapshot_hash`、`extraction_contract`、`document`、`structured_table_candidates` 和 `readonly_hints`;必须按传入内容解析,不能回读 HXOPS 可变文档。`extraction_contract.fields[]` 仅包含 `collection_mode=llm_extraction` 的字段;Workflow 只能返回其中列出的稳定 `field_id`,不得提取、补写或回传 `general_context/deterministic_context` 字段(包括发件人邮箱和企业域名)。`readonly_hints` 仅按已发布 Schema 策略提供当前单元提示/关联信息,Dify 不得将其中字段加入 `orders.header_fields` 或 `lines.fields`,也不得从正文、`Reply-To`、签名或转发内容重建被排除字段。 -4. Workflow End 节点只输出结构化 `orders`;可以是数组,或 JSON 字符串形式的数组。推荐契约如下: - -```json -{ - "orders": [ - { - "schema_version_id": 123, - "schema_checksum": "...", - "classification": "shipping_request", - "classification_confidence": 0.98, - "source_intake_no": "SNI-...", - "primary_document_id": 456, - "header_fields": [], - "lines": [{"fields": []}], - "conflicts": [] - } - ] -} -``` - -5. Workflow 只负责“冻结文档 + Schema → orders”。不得调用已删除的 HXOPS 订单抽取提交 Tool,不得创建 Batch/Task、判重、决定库存源或执行最终字段裁决,不得在输出中包含思考过程或自然语言包裹。 -6. 普通货代 Chatflow 继续负责无附件问答和后续交互,但不执行订单抽取;阶段 5 已删除旧抽取分支、Tool、聊天参数和专属 SSE。 - -> 兼容说明:内部 Provider 的 `effective_role` 由 `exposure_mode=internal` 只读派生为 -> `internal_executor`。历史 `conversation_mode` 仍保留并继续出现在 API 中,但不用于聊天呈现; -> 只有货代用户入口 Agent 使用 `conversation_mode`。 +订单抽取由 HXOPS 冻结 Run、抽取计划和后台 Worker 执行。应用管理不配置内部执行器、Runtime Binding 或 Dify Workflow;普通货代 Chatflow 只负责无附件问答和后续交互,不参与订单抽取执行。 ### 通用上下文字段运行与审计边界 @@ -608,9 +572,9 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工 ### 阶段 4 可靠性、监控与故障注入 -- 管理员健康 API:`GET /api/admin/shipping-notice/order-extraction-runs/health`。默认统计最近 24 小时终态,同时始终包含所有活动 Run;可传 `window_hours=1..168`、`queued_stale_seconds=30..86400`、`running_stale_seconds=60..86400`。 -- 健康状态:存在积压 Run,或至少 5 个终态且失败/取消比例达到 20% 时为 `degraded`;否则为 `healthy`。默认 queued 超过 300 秒、running/result_persisted 超过 1800 秒记积压。 -- 分段耗时:`queue=created_at→started_at`、`provider=started_at→provider_completed_at`、`hxops_persistence=provider_completed_at→result_persisted_at`、`total=created_at→finished_at`,返回 count/avg/p95/max。 +- 管理员健康 API:`GET /api/admin/shipping-notice/order-extraction-runs/health`。默认统计最近 24 小时终态,同时始终包含所有活动 Run;可传 `window_hours=1..168`、`queued_stale_seconds=30..86400`、`processing_stale_seconds=60..86400`。 +- 健康状态:存在积压 Run,或至少 5 个终态且失败/取消比例达到 20% 时为 `degraded`;否则为 `healthy`。默认 queued 超过 300 秒、processing 超过 1800 秒记积压。 +- 分段耗时:`queue=created_at→started_at`、`processing=started_at→finished_at`、`total=created_at→finished_at`,返回 count/avg/p95/max。 - 隐私边界:API 只返回聚合计数、错误码和最多 20 个积压 Run 的 `run_no/status/phase/attempt_count`;禁止返回错误正文、文档、orders、Provider 快照/配置或凭据。 - Worker 日志事件:`shipping_order_extraction_started/provider_completed/completed/attempt_failed`。日志仅带 Run/Job/attempt/phase/status/elapsed/error_code,禁止输出异常正文和业务原文。 - 浏览器轮询单次 GET 上限 10 秒;切会话、组件卸载和新 Run 会中止旧 GET。中止/超时只触发指数退避,后台 Run 不受影响。 @@ -619,12 +583,12 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工 | 注入点 | 必须结果 | | --- | --- | -| Provider 请求超时/网络中断 | Job 按 max_attempts 重试;Run queued/running 单调迁移,耗尽后 failed;Intake 恢复重试入口 | -| Provider 已成功,HXOPS 落库暂时失败 | `provider_result_json/provider_completed_at` 已独立提交;重试不再次调用 Dify | +| Provider 请求超时/网络中断 | Job 按 max_attempts 重试;Run `queued/processing` 单调迁移,耗尽后 `failed`;Intake 恢复重试入口 | +| Provider 已成功,HXOPS 落库暂时失败 | 已有的单元结果与进度事实独立提交;重试不重复生成已确认的用户事件 | | 用户修复 Dify 配置后手工重试 | 失败卡片点击“重新识别”;原 Run `failed→queued`,新 Job 入队并恢复轮询,不重新上传附件 | | 失败 Run 的冻结快照不满足当前输入契约 | 禁止复用旧 Run 入队,返回 `SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE`;用户须重新发送邮件及附件创建新 Run | -| Worker 进程在 Provider 成功提交后退出 | 下一次领取直接复用缓存 orders,并收口 result_persisted/终态 | -| running Job 超过回收阈值 | `recover_stale_jobs` 重排或失败,并同步 Run;不得永久 running | +| Worker 进程在成功写入单元结果后退出 | 下一次领取直接复用已持久化事实,并继续收口终态 | +| processing Job 超过回收阈值 | `recover_stale_jobs` 重排或失败,并同步 Run;不得永久停留在 processing | | 浏览器 GET 挂起/断网/切会话 | 10 秒 abort 或立即 abort;页面不显示业务失败,旧响应不污染新会话 | | 浏览器轮询中断或历史 ChatLog 仍为运行态 | Run 是唯一状态源;终态事务同步状态卡,历史消息接口按 Run 事实覆盖陈旧 payload,禁止永久显示 `extracting` | @@ -749,16 +713,17 @@ EML FileAsset -> ShippingNoticeIntake | 软删除唯一 | `(parent_asset_id, content_hash)` 为 **partial unique**(`deleted_at IS NULL`);清理后同哈希可复活/重建;迁移去重行转 `orphan_cleanup` 供 MinIO 回收 | | 重复刷新 | `refresh_intake_duplicate_detection` 逐 Candidate 重检再聚合 Intake;避免仅更新概览导致候选状态陈旧 | | Document | `ShippingNoticeDocument`:`body` + 各附件一行;详情/轮询经 Intake 序列化返回 | -| Candidate | 上传阶段恒为 0;点击发送后由专用 Workflow 返回的 `orders[]` 经 Worker 校验并生成。正文不单独生成 Candidate,但可以作为订单 evidence | +| Candidate | 上传阶段恒为 0;点击发送后才按当前批次附件创建识别计划并生成 Candidate。正文不单独生成 Candidate,但可以作为订单 evidence | | 分类 | 无业务信号的 PDF 等为 `supporting` Document,禁止伪造 PO/SKU | | 失败与重试 | 阶段二持久化失败 → `parse_failed`(可重试);与文本抽取成功解耦后不再静默 `parsed` | | 并发 | Job 原子领取 `parsing`;派生资产部分唯一 + IntegrityError 回查;补偿删 MinIO 失败写 `orphan_cleanup` 行供定时回收 | | 重复隔离 | 候选 A 重复只阻断 A;Intake 概览可为 `partial_duplicate` | | 重试幂等 | Document 使用内容与附件键去重;Candidate 使用 intake + candidate_key;Run 使用冻结 snapshot、Provider 结果缓存与建批幂等键回放 | -| 解析器版本 | 默认 `SHIPPING_NOTICE_PARSER_VERSION=v6`(上传阶段落库 Document/派生资产;Candidate 延后到 Chatflow 提交) | +| 解析器版本 | 默认 `SHIPPING_NOTICE_PARSER_VERSION=v6`(上传阶段仅落快览摘要;附件 Document/派生资产与布局任务延后到发送后的按需深度解析) | +| 发送后识别预算 | `SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_ATTACHMENTS=2`、`SHIPPING_NOTICE_ORDER_EXTRACTION_EXPANSION_BATCH_SIZE=2`、`SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS=6`;Run 创建时只首轮选中 2 个附件,其余可扩展附件冻结为后续批次事实,不在上传阶段或首轮外被提前物化/执行 | | 建单 | `ShippingTask.source_candidate_id` 已启用;满足自动建单门禁的 Candidate 分别创建 Task,待处理 Candidate 保留在原 Intake | -实现入口:上传预处理 persist_intake_documents ← run_intake_parse;完整订单抽取由 order_extraction_run_service、shipping_order_extraction Worker 与 persist_order_extraction_result 协作。 +实现入口:上传快览由 `run_intake_parse` 直接写入 Intake 摘要;`persist_intake_documents` 仅保留给模板样本或发送后深度解析链路复用。完整订单抽取由 order_extraction_run_service、shipping_order_extraction Worker 与 persist_order_extraction_result 协作。 ### EML 附件提取(阶段一) @@ -1090,7 +1055,17 @@ GET /api/admin/shipping-order-schema/published-contract # 后端冻结每个 Artifact 实际规则来源、规则版本、流水和最终文件名;客户端不得提交文件名。 # SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx -# 订单抽取固定由 Intake Run + 显式绑定的内部 Dify Workflow 执行;不再提供 Chatflow/同步解析切换开关 +# 订单抽取固定由 Intake Run + 本地确定性 Worker 执行;不依赖 Chatflow、Dify Workflow 或应用管理执行器。 + +# 发送后附件选择与 Worker 资源预算:首轮默认 2 个附件、实际并发 2; +# 后续只在需要补证时每轮增加 2 个,整次最多 6 个、30MB 原始输入、5 分钟。 +# 任一预算停止均转人工复核,不能自动冻结。 +# SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_ATTACHMENTS=2 +# SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_CONCURRENCY=2 +# SHIPPING_NOTICE_ORDER_EXTRACTION_EXPANSION_BATCH_SIZE=2 +# SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS=6 +# SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_BYTES=31457280 +# SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_RUNTIME_SECONDS=300 # EML 附件提取安全上限(阶段一) # SHIPPING_NOTICE_EML_MAX_ATTACHMENTS=20 @@ -1863,9 +1838,9 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv ## 2. Dify 手工配置边界 - 普通货代 Chatflow 删除所有订单抽取判断、LLM、Code 和旧 Tool 节点,只保留无附件问答、临时库存与后续修订。 -- 内部专用 Workflow Start 固定接收一个 `execution_manifest` String;它是版本化 JSON,含 Run 标识、输入哈希、冻结的 `extraction_contract` / `documents` 和 `readonly_hints`。End 只输出结构化 `orders`。`readonly_hints` 只可用于当次提示与 Intake 关联,不得缓存、恢复脱敏值或回传其中 `field_id`。 -- Workflow 不调用 HXOPS Tool,不创建 Batch/Task,不决定库存源,不输出思考过程或自然语言包裹。 -- 应用管理通过 shipping.order_extraction 能力显式绑定 internal + dify + workflow Provider,代码不写死 App ID。 +- 订单抽取不配置 Dify Workflow、变量、Prompt、Tool、SSE 或 `execution_manifest`。普通货代 Chatflow 仅处理无附件问答、临时库存与后续修订。 +- Dify 不调用 HXOPS 订单抽取 Tool,不创建 Batch/Task,不决定库存源,也不参与订单 Candidate 的生成或裁决。 +- 上述附件选择、深度解析、扩批、预算和自动冻结均由 HXOPS Worker 执行;Dify 无需新增配置。部署前只需确认普通货代 Chatflow 不含旧订单抽取节点。 ## 3. 当前与原型对齐状态 @@ -2124,17 +2099,17 @@ API 层 库存源测试不依赖履约策略,因其不冻结订单、不匹配订单、不生成 Excel 或上传;因此“库存源可测试”和“订单可履约”是两个独立状态。订单冻结、库存核验、滚动制单与上传仍强制要求已发布策略和冻结 Snapshot,不能以库存源已启用替代。 -#### Dify 手工配置说明(阶段 1) +#### Dify 手工配置说明(阶段 1,历史归档) -本阶段不由 HXOPS 修改 Dify 画布或 Tool。当前已发布 Schema V2(完整识别配置)包含 55 个启用字段:每个字段均维护了中文显示名、无冲突的中英文表头别名、业务说明、抽取指令和 `pdf_coordinate` 坐标识别许可。业务管理员应使现有 Workflow 仅依据运行时下发的 published contract 返回允许的 Observation;已启用字段在原文存在时均应返回当前文档可验证的 value、quote 与 document ID,15 个必填字段(Header:客户 PO、Bill 客户/地址、Ship 客户/地址、币种;Line:项次、内部料号、客户料号、预约单号、数量、单位、单价、含税金额、库存源线索)缺失时不得编造。 +本段为订单抽取退役 Dify 前的历史配置,不能作为当前画布操作依据。订单抽取现在由 HXOPS Worker 完成,Dify 不接收 published contract、Document 或 Observation,也不应返回 value、quote 或 document ID。 -`reservation_id`、`part_number`、`qty` 和 `inventory_source_hint` 均为 Line 值;其中前三项是履约能力字段,必须附当前文档可验证的 quote 与 document ID。`pdf_coordinate` 仅允许 HXOPS 的订单文档 Profile 使用,不是 Dify 的输出来源或画布变量。不得回传 `inventory_source_hint_default` 或 `shipping_method`;Dify 不判断重复 Reservation、不选择库存源、不冻结订单、不生成 Excel 或上传,这些结果全部由 HXOPS 门禁裁决。 +`reservation_id`、`part_number`、`qty` 和 `inventory_source_hint` 均为 Line 值;其中前三项是履约能力字段,必须附 HXOPS 可验证的原文证据。`pdf_coordinate` 仅允许 HXOPS 的订单文档 Profile 使用,不是 Dify 的输出来源或画布变量。Dify 不判断重复 Reservation、不选择库存源、不冻结订单、不生成 Excel 或上传,这些结果全部由 HXOPS 门禁裁决。 #### 字段能力绑定与履约策略(阶段 2) 字段目录只定义数据身份,`business_purpose` 仅保留为 Schema 抽取配置的历史元数据,禁止作为库存、冻结、Reservation、导出或上传的履约真相。管理端仅允许使用代码注册的能力:`fulfillment.reservation_identity`、`fulfillment.part_number`、`fulfillment.quantity` 和可选 `routing.inventory_source_hint`;禁止自由脚本、SQL、JSONPath 或外部调用。能力按稳定 `field_id` 绑定,字段必须匹配指定的 Header/Line 作用域和数据类型;因此自定义字段可在满足约束后承担能力,不能按名称猜测。 -当前唯一允许的策略为 `SHIP_AVAILABLE_ROLLING_V1`。发布策略会退役前一版本;冻结时把策略 ID、编码、版本、checksum、完整 definition 与绑定字段 ID 写入 Snapshot,库存、Reservation、滚动制单和上传只能读取这个冻结事实。发布新策略不会重解释已有快照。Dify 无需新增配置:仍只依据 HXOPS 发布的 Schema 契约返回 Observation,不能选择能力绑定、发布策略或裁决履约。 +当前唯一允许的策略为 `SHIP_AVAILABLE_ROLLING_V1`。发布策略会退役前一版本;冻结时把策略 ID、编码、版本、checksum、完整 definition 与绑定字段 ID 写入 Snapshot,库存、Reservation、滚动制单和上传只能读取这个冻结事实。发布新策略不会重解释已有快照。Dify 不参与订单字段契约、能力绑定、策略发布或履约裁决。 #### 策略管理闭环(阶段 3) @@ -2142,7 +2117,7 @@ API 层 反向依赖同样在 Schema 发布时执行:当前 published 履约策略绑定的字段、库存路由规则、库存解析 Profile、订单文档 Profile、Excel 模板和客户识别定义都不能被新的 Schema 版本移除。这样策略、库存与制单的字段问题在配置发布时阻断,而不会延后到冻结或库存核验运行时才暴露。 -**阶段 3 Dify 手工配置**:无需修改 Dify 画布、变量、Prompt 或 Tool。Dify 继续只按 HXOPS 发布 Schema 的稳定 `field_id` 返回 Observation 与当前文档证据;不配置、选择或发布履约策略。 +**阶段 3 Dify 手工配置(历史归档)**:当前无需为订单抽取修改 Dify 画布、变量、Prompt 或 Tool;Dify 不再返回 Observation 或当前文档证据,也不配置、选择或发布履约策略。 **阶段 6/7 Review(2026-07-23)**:冻结入口在取得当前 published 策略前 fail closed;即使已接受订单、必需字段和已确认 Bill-to 客户齐全,未发布策略也以 `SHIPPING.FULFILLMENT_POLICY_NOT_PUBLISHED` 阻断且不写入 Snapshot。管理员策略 API 同样完成权限和发布顺序回归:普通用户返回 `AUTH.FORBIDDEN`;管理员只能在当前 Schema 已发布且包含绑定字段时发布策略。阶段回归为 33 passed,前端 production build 通过。 @@ -2190,7 +2165,7 @@ API 层 订单抽取主链不再调用 Dify、Provider 或 Runtime Binding。Run 创建仅冻结文档、Schema、模板 Profile、`parser_engine_version`、`parser_policy_version` 和人工冻结策略;Worker 仅执行本地确定性模板解析。`deterministic` Unit 可写入候选结果,`review_required` 与 `skipped` 进入人工复核;只有解析器、数据库、对象存储或 Job 技术异常才使 Run 失败。 -迁移 `08f12a3b4c5d` 已破坏性删除订单解析专属的 Runtime Binding、Provider、质量批次、Workflow 运行号及结果快照列,替换为确定性解析版本、`execution_result_json` 和 `extraction_completed_at`。通用 Agent Runtime Binding 能力仍可服务其他 Agent,但不得重新接入订单抽取。 +迁移 `08f12a3b4c5d` 已破坏性删除订单解析专属的 Provider、Workflow 运行号及结果快照列,替换为确定性解析版本、`execution_result_json` 和 `extraction_completed_at`;后续迁移删除应用管理的内部执行器和 Runtime Binding 模型。 订单抽取状态卡由 HXOPS 的 Run 投影恢复和更新:会话侧栏聚合未查看终态提醒,进入对应会话并成功投影状态卡后才确认已查看;用户上传锚点不重复渲染为助手卡。Dify 无需、也不应为订单抽取配置画布、变量、Prompt、Tool 或 SSE。 @@ -2208,9 +2183,11 @@ Route Decision 现在分别记录 `document_table_count`、`business_table_count #### 阶段 4:模板发布与自动冻结资格分离(2026-07-28) -模板版本生命周期仍为 `draft / published / retired`,仅决定模板能否参与确定性解析;它不授予自动冻结能力。每个发布 Profile 版本会单独建立 `shipping_document_profile_auto_freeze_qualifications` 记录,冻结 Profile ID/版本/checksum、Schema 版本、解析器版本和可选质量套件,状态只能是 `manual_confirmation`、`auto_freeze_approved` 或 `auto_freeze_suspended`。新版本绝不继承旧版本资格,checksum 改变即不匹配,管理员可单独暂停某一版本。 +模板版本生命周期仍为 `draft / published / retired`,仅决定模板能否参与确定性解析;它不授予自动冻结能力。每个发布 Profile 版本会单独建立 `shipping_document_profile_auto_freeze_qualifications` 记录,冻结 Profile ID/版本/checksum、Schema 版本、解析器版本和可选质量套件,状态只能是 `manual_confirmation`、`auto_freeze_approved` 或 `auto_freeze_suspended`。资格记录现已额外保存 `customer_ids_json`、`business_scenarios_json`、`requires_customer_confirmation` 以及 scope 配置人/时间,用于表达“哪些客户 + 哪些业务场景 + 是否仍需客户确认”才允许进入自动冻结门禁。新版本绝不继承旧版本资格,checksum 改变即不匹配,管理员可单独暂停某一版本。 -当前样本不足,首版发布一律写入 `manual_confirmation`,Run 的 `auto_freeze_policy.mode` 固定为 `manual_confirmation` 且 `enabled=false`。盲测、质量批次或模板发布本身均不能打开自动冻结;用户仍须完成人工确认和后续冻结门禁。 +当前样本不足,首版发布一律写入 `manual_confirmation`。Run 创建时冻结的 `auto_freeze_policy` 仍以 `mode=manual_confirmation`、`enabled=false` 起步;结果落库后再按本轮事实刷新 `run.auto_freeze_policy_json`,补入命中的 Profile 版本、资格状态、授权客户/场景状态以及阻断原因(如 `profile_manual_confirmation_required`、`profile_auto_freeze_suspended`、`customer_scope_out_of_scope`、`business_scenario_not_configured`、`technical_failure_present`、`budget_stopped`)。 + +Run 自动冻结门禁真实消费资格表中的客户/业务场景范围:若 Bill-to 客户未确认、命中多个客户、客户不在白名单、业务场景未配置或不在白名单,都会写入稳定 `blocking_reason_codes` 并保持 **fail-closed**。只有资格、客户/场景范围及所有 Run/Task 冻结门禁均放行时,执行入口才消费当前 Run 的 accepted Candidate 并冻结新建 Task;盲测、质量批次或模板发布本身均不能直接打开自动冻结,也绝不触发库存、Excel 或上传。 #### 阶段 5:人工复核与字段证据闭环(2026-07-28) @@ -2222,9 +2199,11 @@ Route Decision 现在分别记录 `document_table_count`、`business_table_count `freeze_order_snapshot` 在同一事务以 `SELECT FOR UPDATE` 锁定 Task,并由 `freeze_readiness_service` 聚合检查当前已接受 Extraction、已确认 Bill-to、开放字段冲突、订单行、履约策略绑定的 `part_number` / `reservation_id` / 正数 `qty`,以及客户端给出的 `order_data_version`。任意失败均以 `SHIPPING.ORDER_FREEZE_BLOCKED`(或更具体的既有门禁码)拒绝,绝不写入半成品 Snapshot。 +同一服务现已预留 `freeze_mode=auto` 的门禁分支:当后续自动冻结入口接入时,必须显式传入 Run 已刷新的 `auto_freeze_policy_json`,并把 `enabled=false`、`customer_scope_not_configured`、`customer_scope_out_of_scope`、`business_scenario_not_configured`、`customer_confirmation_required`、`profile_auto_freeze_suspended` 等阻断原因折叠为统一 `issues`。人工冻结路径继续使用 `freeze_mode=manual`,不因阶段 5 的资格范围模型而误伤现有人工确认流程。 + `shipping_order_snapshots.task_id` 现在具有数据库唯一约束。重复点击冻结返回该 Task 已有的同一 Snapshot;冻结后的所有编辑入口继续由 `assert_task_order_is_editable` 统一阻断。每个 Snapshot 新增 `source_manifest_json`,冻结 Schema/策略版本、字段裁决的 Observation、文档 hash、quote、页码/表格/单元格等 evidence metadata,以及冻结前的人工复核审计,后续履约不得回读可变 Extraction 事实重建来源。 -首版仍只允许用户明确确认后冻结;Run 的 `auto_freeze_policy.enabled` 固定为 `false`。库存源必须在冻结后的快照上裁决,随后才允许库存/RPA 副作用,因此不以冻结前的可变路由状态作为替代条件。 +首版仍只允许用户明确确认后冻结;库存源必须在冻结后的快照上裁决,随后才允许库存/RPA 副作用,因此不以冻结前的可变路由状态作为替代条件。后续自动冻结只允许消费 Run 已刷新过的 `auto_freeze_policy_json`,不得回退到 Schema 历史开关或模板发布状态猜测是否可自动履约。 #### 阶段 7:客户重发、版本替代与货代撤销(2026-07-28) diff --git a/docs/funclist.md b/docs/funclist.md index ca524f19..0dc60b0a 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -61,13 +61,14 @@ | 发货通知业务说明 | 已文档化 | 见 [docs/features/shipping-notice/business.md](features/shipping-notice/business.md) | | 业务去重与任务版本(Phase 3) | 已实现 | Intake 业务指纹/重复决策、修订版本链、强制新建权限与审计;见技术手册第三节摘要 | | EML 附件提取(阶段一) | 已实现 | 结构化解析主题/发件人/正文与真实附件;`message/rfc822`/附件型 multipart 独立登记;完整性门禁与容器计费;见技术手册「EML 附件提取」 | -| EML/附件上传预处理 | 已实现 | 上传后自动创建 Intake,解析邮件正文/真实附件并派生 FileAsset/Document;上传阶段不调用 LLM、不生成 Candidate、不判订单重复;解析失败、超时、取消和资产引用补偿保持幂等 | -| 上传与订单版面准备状态一致性 | 已实现 | Intake 状态接口独立汇总文档布局任务;聊天附件在 `queued/running` 时显示“正在解析订单版面”、持续轮询并禁止过早发送,所有布局任务终结后才允许创建订单识别 Run;布局失败或不支持进入人工复核,不调用 Dify 兜底 | +| EML/附件上传预处理 | 已实现 | 上传后自动创建 Intake 快览:只解析邮件正文、白名单 HTML 表格快照和附件目录;上传阶段不抽取附件全文、不创建附件 FileAsset/Document、不生成 Candidate、不判订单重复;解析失败、超时、取消保持幂等 | +| 上传与发送门禁状态一致性 | 已实现 | Intake 状态接口返回 `preview_status / ready_for_extraction / attachment_directory_complete` 等快览事实;聊天附件快览成功后显示“已就绪/已发现 N 个附件”并允许发送,不再因上传阶段版面任务阻塞;真正的订单识别进度在点击发送后单独展示 | | 点击发送完整订单抽取 | 已实现 | Run 冻结文档、Schema、模板 Profile 和确定性解析器版本;Worker 只执行本地模板解析,支持一附件多订单、证据门禁、幂等重放及人工复核,不依赖 Dify、Provider 或 Runtime Binding | | 订单识别生命周期反馈 | 已实现 | Run 状态卡按真实确定性解析进度和终态计数更新并持久化到 `ChatLog.payload`;聊天历史可恢复,侧栏显示未查看终态提醒,处理中不伪造百分比 | | EML 正文补充表合并(阶段 2) | 已实现 | 正文 HTML 表解析为带 DOM 单元格证据的 PO 级补充事实,不创建独立订单或执行 Unit;按 `PO + MPN`、受限 PO 降级补 Reservation/Allocation/库存来源提示,PDF 数量保持权威,歧义统一进入人工复核 | | PDF 模板 PO 拆分与严格拒识(阶段 3) | 已实现 | 已批准模板中每条明细均有唯一 PO 证据时,单 PDF 自动拆为多个独立订单;表级多 PO 未能归属明细、模板歧义、漂移和证据不足统一转人工复核,Route Decision 分别审计四类表计数 | | 模板发布与自动冻结资格分离(阶段 4) | 已实现 | Profile 的发布仅允许确定性解析;每个发布版本独立冻结人工确认资格,首版强制 `manual_confirmation` 且自动冻结关闭,盲测批准、旧版本资格或 checksum 变化均不能越过该门禁 | +| Run 自动冻结门禁与执行 | 已实现 | Run 创建时冻结 `manual_confirmation` 初始策略;结果落库后按模板资格、已确认 Bill-to 客户、业务场景、技术失败、预算停止和待处理订单刷新 `auto_freeze_policy_json`。仅资格与全部门禁显式放行时,自动消费当前 Run 的 accepted Candidate 并冻结新建 Task;不触发库存、Excel 或上传履约副作用。 | | 人工复核与字段证据闭环(阶段 5) | 已实现 | 单头、订单行、冲突解决均要求乐观锁、原因和结构化 `document_cell`/`manual_input` 证据;跨订单或伪造证据在写值前拒绝,复核审计保存结构化证据且详情页展示页码、表格、单元格与原文 | | 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 身份/内容双指纹;高置信 SKU+Qty 订单自动建 Task,低置信/冲突/修订保留待处理;部分消费 Intake 不丢剩余订单;缺 Reservation/Source Type/Hub Code 的 Task 停在自然对话补字段门禁 | | 库存 RPA 源 YAML 配置 | 已实现 | `backend/config/shipping_inventory_sources.yaml`,新增 Warehouse 只改 YAML | diff --git a/docs/platform/agent_application_management.md b/docs/platform/agent_application_management.md index f6d7552d..b61a9e30 100644 --- a/docs/platform/agent_application_management.md +++ b/docs/platform/agent_application_management.md @@ -58,48 +58,11 @@ | **conversation_mode** | 交互形态:`chat` \| `task_chat` \| `embedded` | **列** | | **context_adapter** | 从业务模型投影白名单字段到 Dify | 不落库;`agent_code` → `CONTEXT_ADAPTER_REGISTRY`,未知则 `generic` | | **runtime_handler** | 内置执行模块 key | 仅 Catalog;`agent_code` → `AGENT_TYPE_CATALOG[code].runtime_handler` → `HANDLER_REGISTRY` | -| **exposure_mode** | `workspace` 为用户入口;`internal` 为不可授权、不可聊天展示的内部 Provider | **列** | -| **runtime capability** | 入口 Agent 需要的命名后台能力,如 `shipping.order_extraction` | Catalog 声明,数据库绑定 | -| **AgentRuntimeBinding** | `owner_agent_id + capability_code → provider_agent_id` 的显式映射 | `agent_runtime_bindings` 表 | | **adapter_hints** | 请求级业务锚点(如 `task_id`、`batch_no`) | 请求参数 | | **description** | 用户可见描述;generic 的 `domain.summary` 来源(≤500 字) | **列** | **禁止作为 `agents` 表列的字段**:`runtime_handler`、`context_adapter`、`runtime_context_summary`(用 `description` 代替)。 -### 2.3 命名运行能力与内部 Provider - -- Catalog 只声明稳定能力编码及允许的 Provider 类型,不保存具体 Agent/App ID。 -- 管理员先创建 `exposure_mode=internal` 的 Provider Agent,再在入口 Agent 表单显式选择绑定;运行时只查数据库外键,不按名称匹配、不写死 ID、不使用环境变量静默回退。 -- 入口 Agent 注册后,Catalog 声明的必需能力天然生效;表单只指定执行器 Provider 和超时/重试参数,不再提供“启用订单抽取服务”勾选。后端旧 `enabled` 字段保留用于历史 API 和运维停用。 -- 内部 Provider 复用 `agents` 表保存 Dify App ID、Base URL 和 API Key,但不出现在用户工作台、权限分配或普通 Agent 列表中。 -- 订单抽取能力当前只允许 `runtime_provider=dify + dify_app_type=workflow + exposure_mode=internal`。绑定可配置超时和最大尝试次数。 -- 订单抽取能力的 Provider 技术约束由入口 Agent Catalog 的 `required_runtime_capabilities` 声明;具体用途由 `AgentRuntimeBinding.capability_code` 与管理员选择的执行器共同确定。 - -### 2.2 effective_role(兼容派生字段) - -`effective_role` 是只读运行时派生值,不新增数据库列:`exposure_mode=internal` 时为 -`internal_executor`,其他情况为 `user_agent`。旧 `conversation_mode`、`exposure_mode`、 -`type` 和 `extra_config` 字段继续按原 API 契约返回;历史内部 Provider 即使仍保存旧的 -`conversation_mode`,该值也不参与聊天呈现。只有 `user_agent` 使用 `conversation_mode`, -内部执行器的表单应隐藏对话形态等聊天配置。 - -`exposure_mode=internal` 是内部执行器注册入口的固定属性,不提供编辑切换;内部执行器不能转为工作台应用。 - -管理端采用两个独立页签:`应用` 页仅管理 `exposure_mode=workspace` 的用户入口,`内部执行器` -页仅管理 `exposure_mode=internal` 的后台 Provider。两个页签分别提供“新建应用”和“新建内部执行器”入口, -后端列表通过 `GET /api/admin/agents?scope=applications|executors` 隔离;不传 `scope` 仅用于旧客户端兼容。 -两类资源创建后禁止互相转换。 - -用户侧采用强隔离策略:所有用户授权、公开列表、工作台、收藏、默认应用、常用问题、新手指南、 -Agent 详情及普通 Chat API 只接受 `exposure_mode=workspace`。该约束同样适用于管理员通过用户入口访问; -内部执行器只能在管理页配置,并由后台 Runtime Binding 调用。后端写入口必须拒绝 internal ID,读取入口 -仍需防御性过滤历史脏关系;数据迁移清理用户授权、收藏与默认应用,并将内部执行器待审批申请置为拒绝。 - -内部执行器注册时不登记业务服务编码。执行器只保存 Dify Workflow 的技术连接信息;业务用途 -由应用侧 `AgentRuntimeBinding.capability_code + provider_agent_id` 表达。当前暂不实现绑定级契约认证, -管理员可从所有启用的内部 Dify Workflow 中选择具体执行器。 -- Run 冻结 Provider App ID/Base URL 和运行参数以保证执行身份稳定;API Key 不进入 Run 快照,以支持密钥轮换。 - ### 2.1 conversation_mode | 值 | 含义 | 典型场景 | diff --git a/docs/platform/agent_application_management_implementation.md b/docs/platform/agent_application_management_implementation.md index 38379a6f..e91cab99 100644 --- a/docs/platform/agent_application_management_implementation.md +++ b/docs/platform/agent_application_management_implementation.md @@ -35,8 +35,6 @@ | 对象 | 路径 / 操作 | 迭代 | | --- | --- | --- | | `agents` 表新增列 | `backend/migrations/versions/*_add_agent_registry_columns.py` | 1 | -| `agents.exposure_mode` | `c17c8d9e0f1a_add_agent_runtime_bindings.py` | 订单抽取异步阶段 2 | -| `agent_runtime_bindings` | owner + capability 唯一绑定,Provider 外键与运行参数 | 订单抽取异步阶段 2 | | `Agent` ORM | `backend/app/models/agent.py` | 1 | | FK `bound_schedule_task_id` | → `schedule_tasks.id` | 1 | | 回填脚本 | `backend/scripts/backfill_agent_registry.py` | 1 | @@ -53,7 +51,6 @@ | Agent Registry | `services/agent_registry/catalog_loader.py` | 3+ | 加载 YAML + 合并 `catalog_bindings.RUNTIME_HANDLER_BINDINGS` | | Agent Registry | `services/agent_registry/catalog_validation.py` | 3+ | required_fields、forced_capabilities、handler_config 归一化 | | Agent Registry | `services/agent_registry/admin_schema.py` | 3+ | `build_agent_registry_schema()` → Admin 表单 | -| Runtime Capability | `services/agent_runtime_binding_service.py` | 订单抽取异步阶段 2 | Catalog 约束、显式绑定、运行时解析;禁止隐式回退 | | Agent Registry | `services/agent_registry/resolver.py` | 1 | **只读列**、capabilities 归一化;须先 backfill | | Agent Registry | `services/agent_registry/handlers/*` | 4 | `HANDLER_REGISTRY` | | Runtime Context | `services/agent_runtime_context/registry.py` | 2 | `CONTEXT_ADAPTER_REGISTRY` | @@ -80,15 +77,15 @@ | 货代 | `services/shipping_notice/dify_inputs.py` | 2 | 移除 `is_shipping_notice_chat_agent` 对外分发 | | 货代 | `services/agent_registry/handlers/shipping_notice.py`、`services/shipping_notice/dify_inputs.py` | 4 | 普通聊天只构建运行态上下文与 UI State,不承担订单抽取 | | 货代 | `services/shipping_notice/agent_resolver.py` | 1 | 改读 `agent_code` 列 / resolver | -| 货代订单抽取 | `services/shipping_notice/order_extraction_run_service.py`、`order_extraction_workflow.py` | 订单抽取异步阶段 2 | Run/Job 同事务、冻结 Provider、Workflow 输入输出契约 | -| 货代订单抽取 Worker | `jobs/handlers/shipping_order_extraction.py` | 订单抽取异步阶段 2 | Provider 结果先提交、落库恢复、状态单调推进 | +| 货代订单抽取 | `services/shipping_notice/order_extraction_run_service.py`、`order_extraction_workflow.py` | 本地确定性执行 | Run/Job 同事务,冻结文档、Schema、Profile 与解析版本 | +| 货代订单抽取 Worker | `jobs/handlers/shipping_order_extraction.py` | 本地确定性执行 | 单元结果先提交、落库恢复、状态单调推进,不调用 Dify | | 检核 | `services/file_check_tools/context_adapter.py` | 2 | 新建 | | 检核 | `services/file_check_tools/dify_inputs.py` | 2 | `bound_schedule_task_id` 优先于 extra | | 检核 | `services/file_check_tools/agent_resolver.py` | 2 | 校验保留,不作主路由 | | 检核 | `services/file_check_tools/task_resolver.py` | 1 | 读 `bound_schedule_task_id` | | 检核 | `api/workspace/file_check.py` | 3 | 进度 API 读 capabilities 列 | | 排程 | `services/schedule/*` | 3 | 仅当 Admin 绑定排程联动需调整 | -| Dify 封装 | `services/dify.py` | 4 | Executor 内调用,接口可薄改 | +| Dify 封装 | `services/dify.py` | 4 | 仅普通应用对话 Executor 调用;订单抽取不使用 | ### 0.6 前端(可改) @@ -98,7 +95,6 @@ | Admin 类型 | `features/admin/types/agent.types.ts` | 3 | 新字段、`capabilities` schema | | Admin 表单 | `features/admin/modules/agents/composables/useAgentsAdmin.ts` | 3 | 类型下拉、写列不再拼 extra | | Admin 表单 | `features/admin/modules/agents/components/AgentFormModal.vue` | 3 | 区块联动 | -| Admin 能力绑定 | `AgentFormModal.vue`、`useAgentsAdmin.ts`、`admin.api.ts` | 订单抽取异步阶段 2 | internal Workflow 下拉、启停、超时与重试;Agent+binding 原子保存 | | Admin 检核绑定 | `.../AgentToolRunProgressConfig.vue` | 3 | → `bound_schedule_task_id` | | Admin 列表 | `features/admin/modules/agents/AgentsPage.vue` | 3 | 展示 `agent_code` / `runtime_provider` | | Admin 测试 | `AgentTestModal.vue`、`AgentPermissionModal.vue` | 3 | 类型字段适配 | @@ -123,7 +119,6 @@ | 类别 | 路径 | 迭代 | 说明 | | --- | --- | --- | --- | | Dify 画布 | 各环境 Chatflow Start 节点 | 5 | 增 `agent_runtime_context` | -| Dify 订单抽取画布 | 管理员手工维护的 internal Workflow | 订单抽取异步阶段 2 | Start: run_no/hash/schema/documents;End: 仅结构化 orders;不得调用提交 Tool | | OpenAPI | `docs/openapi/agent_runtime_context_tools.dify.json` | 2、5 | 契约变更时重导 | | 环境变量注释 | `.env.dev` / `.env.test` 示例注释 | 1 | 指向本手册 | | 功能清单 | `docs/funclist.md` | 每迭代 | 状态更新 | @@ -140,7 +135,7 @@ | **1** | 迁移 + 回填 | model、catalog、resolver、seed | — | task_resolver 读列 | funclist、本手册 §1 | | **2** | — | registry、bootstrap、chat inputs | — | shipping/file_check context_adapter | 领域 technical §Agent | | **3** | — | admin/user/agents API、agent_service | Admin + 聊天 + workspace 全改 | file_check workspace API | i18n、errors.json | -| **4** | Runtime Binding | Run Worker、handlers、chat.py 瘦身 | 应用管理能力绑定 | shipping order extraction Workflow | 错误码 | +| **4** | Run Worker | Run Worker、handlers、chat.py 瘦身 | 订单抽取后台执行 | 确定性订单抽取 | 错误码 | | **5** | — | — | — | Dify 画布 | dify 集成文档 | | **6** | — | router.py、chat.py | — | text2sql 等快路径 | tec.md 引用 | @@ -318,9 +313,6 @@ def resolve_runtime_provider(agent) -> str: def resolve_conversation_mode(agent) -> str: """只读 agents.conversation_mode 列;缺省 chat。""" -def resolve_effective_role(agent) -> str: - """exposure_mode=internal 时返回 internal_executor,否则返回 user_agent。""" - def resolve_capabilities(agent) -> dict: """只读 agents.capabilities 列;NULL 时 DEFAULT_CAPABILITIES。""" @@ -552,7 +544,7 @@ class ShippingNoticeHandler: ... `resolve_handler(agent)`:Catalog → Registry;无实现且 `provider=hybrid` → `AppError`(`agent_handler_not_configured`)。 -**首批注册**:`shipping_notice` 普通聊天 Handler 只负责上下文与 UI State;订单抽取由 `shipping.order_extraction` Runtime Binding 解析内部 Workflow Provider 后交给 Run Worker。`file_check` 可后续迭代。 +**首批注册**:`shipping_notice` 普通聊天 Handler 只负责上下文与 UI State;订单抽取由 HXOPS Run Worker 执行。`file_check` 可后续迭代。 ### 6.3 Hybrid 骨架 @@ -629,24 +621,11 @@ Intent Router **不**替代 `runtime_provider`;仅在 `completions` 内先于 ### 8.4 迁移退出(代码已完成,环境待 backfill) -### 8.5 内部执行器历史兼容 +### 8.5 内部执行器移除 -- 旧客户端仍可读写 `conversation_mode`、`exposure_mode`、`type`、`extra_config` 和 Runtime Binding `enabled`;结构化列优先,`extra_config` 不参与运行时兜底。 -- 历史 `exposure_mode=internal` Provider 的 `conversation_mode` 原值保留,但运行时忽略;不得批量改为 `workspace`。 -- 新建 internal 记录强制为 `dify + workflow`;历史非法组合允许读取和编辑,但不能新建绑定或执行新 Run。 -- 迁移只允许先 dry-run 诊断,再由管理员逐项修正;不得按名称猜测订单抽取 Provider,也不得自动切换已有绑定。 -- 历史 Run 继续使用冻结的 Provider 身份;API Key 不冻结,允许轮换。App ID、Base URL 或协议漂移继续触发执行身份门禁。 -- 内部执行器不持久化业务服务编码;业务能力用途以 Runtime Binding 的 `capability_code` 为权威来源。 - -### 8.6 管理端双页签 - -- `应用` 页签调用 `/api/admin/agents?scope=applications`,只展示 workspace 用户入口。 -- `内部执行器` 页签调用 `/api/admin/agents?scope=executors`,只展示 internal Provider。 -- 应用表单不显示内部服务类型;内部执行器表单不显示应用类型、对话形态、应用可见性、用户权限及聊天配置。 -- `exposure_mode` 由创建入口固定,已有资源禁止在两种角色之间转换。 -- 用户管理、权限矩阵、常用问题、热点和应用资料选择器显式请求 `scope=applications`;旧客户端无 scope 返回全部仅用于管理兼容,不得用于用户授权。 -- 后端统一通过 `agent_user_access` 策略阻断 internal ID:授权写入明确失败,公开/工作台/详情/指南/收藏/快捷问题/普通 Chat 防御性过滤或拒绝,管理员用户入口不例外。 -- 迁移 `a62b3c4d5e6f` 清理内部执行器的用户授权、收藏、首页默认关系及 `users.default_agent_id`,并拒绝尚未处理的内部执行器权限申请;历史内容与已审批记录保留用于审计。 +- 应用管理只保留单一应用列表和 CRUD 接口;不再提供 `exposure_mode`、内部执行器页签或 Runtime Binding API。 +- 迁移 `0ac56d7e8f90` 删除绑定表与 `agents.exposure_mode` 列,并将已有内部执行器记录转为普通应用;该清理为破坏性操作,不提供回滚路径。 +- 货代订单抽取继续由 HXOPS Run、计划和 Worker 执行,不读取任何应用管理 Provider 配置。 **代码变更(已合入)**: diff --git a/docs/tec.md b/docs/tec.md index 2195fc53..6dd64304 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -1,4 +1,4 @@ -# Agent 内部执行器注册补充(2026-07-21) +# Agent 应用注册补充(2026-07-28) ## 订单坐标模板 v2 工作台与表头建议(阶段 3-4) @@ -6,14 +6,12 @@ - 前端将几何状态转为 v2 相对区域,多个 `line_layouts` 以连续 `row_offset` 持久化;撤销/重做仅记录真实编辑手势。 - 表头建议服务在服务端读取冻结字符坐标,将已配置相对区域投影到页面,并以启用且允许坐标来源的 Schema 精确别名匹配。歧义结果为未映射、状态固定 `needs_review`,不写回 Profile。 -后台长任务能力采用“用户入口 Agent → Runtime Binding → internal_executor → Dify Workflow”模型。 -`effective_role` 由 `exposure_mode` 只读派生;内部执行器不进入用户授权和聊天呈现,必需能力绑定存在即启用。 -用户侧 API 以 `exposure_mode=workspace` 为统一信任边界:授权、公开列表、工作台、收藏、默认应用、FAQ、指南、详情和普通 Chat 均排除 internal;管理员通过用户入口同样不能绕过。内部执行器仅供管理配置和后台 Runtime Binding 执行。 +后台长任务由用户入口 Agent 触发 HXOPS Job Worker 执行。应用管理只维护可授权、可聊天的应用配置,不再提供内部执行器、`exposure_mode`、`effective_role` 或 Runtime Binding。 ## 货代订单抽取文档级优化架构(2026-07-21) - 订单抽取从“邮件和全部附件一次性提交单个 LLM”迁移为“冻结 Run -> 抽取计划 -> 确定性解析 -> 文档级子任务 -> 受控并行无状态 Dify -> HXOPS 合并裁决 -> Candidate/Task”。最终不保留旧整单执行模式。 -- MinerU `pipeline` 已改为独立布局 Job:Intake 同事务创建 Document、`ShippingDocumentLayoutVersion` 和通用 Job 后即可完成预解析;布局 Worker 再通过 `/tasks` 短提交、轮询 `/tasks/{task_id}` 并读取 `/result`,不使用同步 `/file_parse` 长连接。版本表保存紧凑表格快照、parser revision、checksum、大小、质量问题和 lease,不保存完整 Provider 原始响应;Document 仅引用当前成功版本,旧单列 `layout_snapshot_json` 已移除。失败、超限和重试耗尽保留审计但不覆盖旧成功结果。 +- 货代发货通知上传链路已切换为“上传快览 -> 发送后按需深度解析”。`shipping_notice` 用途的 Intake 在上传阶段只读取邮件头、正文白名单 HTML 表格快照与附件目录,返回 `preview_status / ready_for_extraction / attachment_directory_complete` 等快览事实;此阶段不创建附件 Document、派生 FileAsset、`ShippingDocumentLayoutVersion` 或布局 Job,也不调用 MinerU/OCR。点击发送创建 Run 后,系统才按冻结的附件选择计划物化当前批次所需 Document,并由后续 Worker 按需调度布局与深度解析。 - 布局 Job 使用活动版本唯一索引和 `job_id:attempt` lease 防止重复执行及旧 Worker 回写;超时回收可安全 requeue,parser revision 变化自动生成新版本。管理员可查看脱敏版本摘要并显式重解析;诊断不返回 HTML、bbox、全文或内部异常。人工真值当前延期,因此 ready 布局仍只是 Profile/候选输入,不等于 cell 证据已获准自动接受。 - 原生 PDF 候选使用已有 `pypdfium2` 提取字符 bbox,并只为 MinerU 表格区域生成稳定 token。HTML cell 优先做唯一/连续/非重叠字符对齐;失败时仅允许 OpenCV 多参数有框网格共识,并由原生文本 100% 验证。结果以内嵌 `shipping_document_layout.v1` 保存且固定 `needs_review`;parser revision 已提升为 `v2`,使历史 v1 结果不会静默复用。 - L3 将 parser revision 提升为 `v3`。扫描 PDF 直接适配 RapidOCR 多边形坐标,OCR cell 必须同时通过 OpenCV 网格和全部非空 cell 文本一致性;EML HTML 只保留清洗后的 table DOM,并用逻辑网格表达 rowspan/colspan。OCR/HTML 均固定 needs_review,原始 OCR 响应、页面图、主动 HTML 和临时表格片段不入库或 Dify。 @@ -35,12 +33,12 @@ - 阶段 1 已完成动态 Schema 表格契约收敛:确定性解析只消费 Run 锁定版本的 `field_code/display_name/aliases`,无契约不猜列;禁用/不支持字段不参与映射,重复列进入复核,Reservation 安全禁用表头由后端硬规则保护。默认 UOM、任意单元格 Reservation 推断、文档级 Reservation 广播及未启用字段派生均已从正式路径移除。 - 阶段 2 已建立持久化抽取计划:Run 唯一 Plan,冻结 Document 唯一 Unit;正文关系单元与附件抽取单元隔离,复合外键保证 Document/Intake 一致。局部状态机和计划汇总支持 Worker 重启恢复、成功结果保留与失败单元后续重试;Provider 切分留在阶段 3/4。 - 阶段 3 已切换为确定性优先、单文档紧凑契约:完整确定性表格零 LLM;其余单元只向 Dify 发送一个冻结 Document 和允许的动态字段契约。后端强制 Intake/主文档/Observation 全部属于当前 Unit,单元结果最终仍经统一裁决。 -- 阶段 4 已实现 Run 内 2–4 单元受控并行与单元局部指数退避重试。网络线程不共享数据库 Session;主线程按冻结顺序持久化和汇总,成功单元可跨 Job 重试复用。并发/重试参数随 Runtime Binding 冻结到 Run。 -- 阶段 5 已实现 HXOPS 保守跨文档合并与部分成功:只按唯一 PO 或强行身份合并并保留全部 Observation;弱身份保持拆分,冲突交统一字段裁决。失败单元不抹除成功单元,Run 以 needs_review 收口。 -- 阶段 6 已补齐模型单元预算、进程级 Provider 并发闸门、连续失败短期熔断和管理员脱敏单元诊断。治理参数由 Runtime Binding 校验并冻结,用户 API 不暴露内部单元或 Provider 细节。 +- 阶段 4 已实现 Run 内受控并行与单元局部指数退避重试。网络线程不共享数据库 Session;主线程按冻结顺序持久化和汇总,成功单元可跨 Job 重试复用。 +- 阶段 5 已实现 HXOPS 保守跨文档合并与部分成功:只按唯一 PO 或强身份合并并保留全部 Observation;弱身份保持拆分,冲突交统一字段裁决。失败或业务拒识单元不抹除成功单元,Run 按实际结果收口为 `completed / partially_completed / review_required / failed`。 +- 阶段 6 已补齐确定性单元治理和管理员脱敏单元诊断;用户 API 不暴露内部执行细节。 - 阶段 7 已完成影子/自动建单工程硬门禁、质量验收延期:默认只落可审核 Candidate,显式开启后仍复用全部业务安全门禁。订单抽取只使用唯一 Manifest 契约;人工真值与真实影子批准完成前不得开启自动建单。 - 每阶段执行测试、自检和 Review 门禁,阻断问题全部关闭后方可进入下一阶段。Dify 画布由管理员按 `docs/features/shipping-notice/technical.md` 手工修改。 -- 订单抽取可观测进度已完成:用户仅见通用阶段、健康和时间线;新终态会话待查看、管理员只读诊断审计、90天事件每日清理均已实现。Workflow/节点/Job/Provider/正文不进入用户契约,自定义节点标题不持久化。 +- 订单抽取可观测进度已完成:用户仅见后端事实投影出的 `summary / current_activity / available_actions / documents`;新终态会话待查看、管理员只读诊断审计、90 天事件每日清理均已实现。Workflow/节点/Job/Provider/正文不进入用户契约,自定义节点标题不持久化。 - 重新识别采用 Run 谱系而非原地覆盖:`reparse_of_run_id/superseded_by_run_id` 连接来源和新版,Candidate 按 `(intake_id,candidate_key,order_extraction_run_id)` 版本化,`is_current_version` 是唯一可建单门禁。新版创建时冻结旧候选,失败时恢复其原选择状态;用户端仅见来源/后继编号、原因和 Schema/Profile/layout 是否变化的脱敏摘要。 # 智能HR请假管理技术架构 @@ -115,21 +113,21 @@ - 新会话由 Run 创建事务生成 `ChatSession` 并绑定 Intake;前端保存带稳定 `formId` 的用户附件气泡与助手状态卡,路由随后写入服务端返回的 `conversation_id`。 - Run 活动态使用不确定进度;轮询网络错误指数退避且不写业务失败,状态/phase/result/error 未变化时不重复落 ChatLog。会话切换使用轮询 generation 隔离迟到响应,终态刷新各领域视图独立容错。 - 阶段 5 已删除旧 Chatflow 订单抽取 Tool、聊天参数、Handler 生命周期和专属 SSE;普通 Chatflow 仅保留无附件问答、临时库存与订单后续自然语言修订。 -- 阶段 4 可观测性端点为 `GET /api/admin/shipping-notice/order-extraction-runs/health`,仅管理员可访问;支持 `window_hours/queued_stale_seconds/running_stale_seconds`,服务端钳制安全范围并返回 health、计数、状态/phase/error_code 分布及 queue/provider/HXOPS/total 时延。 -- 健康窗口按终态 `finished_at` 统计,活动 Run 始终纳入;queued 默认 300 秒、running/result_persisted 默认 1800 秒判积压。至少 5 个终态且失败率达到 20%,或存在积压 Run 时标记 degraded。 +- 阶段 4 可观测性端点为 `GET /api/admin/shipping-notice/order-extraction-runs/health`,仅管理员可访问;支持 `window_hours/queued_stale_seconds/processing_stale_seconds`,服务端钳制安全范围并返回 health、计数、状态/current_activity/error_code 分布及 queue/processing/total 时延。 +- 健康窗口按终态 `finished_at` 统计,活动 Run 始终纳入;queued 默认 300 秒、processing 默认 1800 秒判积压。至少 5 个终态且失败率达到 20%,或存在积压 Run 时标记 degraded。 - Worker 结构化日志只记录 `run_no/job_id/attempt/phase/status/elapsed_ms/error_code`,禁止记录异常正文、输入快照、Provider 配置、API Key 或 orders 原始结果。 - 前端 GET 使用 AbortController:每次查询 10 秒超时,切会话/卸载立即 abort;Abort 只视为传输失败并退避,不写 Run failed,也不取消后台作业。用户 Run DTO 与持久化聊天状态只保留错误码和通用提示,Worker/Provider 错误正文仅限服务端日志与管理员脱敏诊断边界。 - Candidate 使用身份指纹 `shipping-v1` 与内容指纹 `shipping-content-v4` 双层判重;内容版本覆盖单头、V2 订单行、价格与分配字段,主附件 hash 独立落到 Task,避免以整封 EML 作为所有订单的判重依据。 - Candidate 唯一键为 `(intake_id, candidate_key)`,支持一个 Document 产生多个 Candidate;Task 与 Candidate 一对一关联。 - 自动建单后若仍有未消费/待处理 Candidate,Intake 保持 `parsed + partially_completed`;全部处理后才 `consumed`。后补订单可创建新的 Batch,并继续关联原 Intake/Candidate。 -- Catalog 由货代应用声明 `shipping.order_extraction`,管理端通过 `agent_runtime_bindings` 显式绑定一个 `internal + dify + workflow` Provider Agent;业务代码只识别能力编码与数据库绑定,不识别具体 App ID、应用名称或环境变量回退。 +- 货代订单抽取由订单抽取 Run、计划和 Worker 直接执行;应用管理不保存订单抽取 Provider 或 Runtime Binding。 - Worker 只调用 Workflow API,并以版本化 `execution_manifest` 传入冻结 Schema、文档和受控只读提示;只接受结构化 `outputs.orders`。Dify 成功结果先保存到 Run,再执行 Candidate/Extraction/Batch 持久化,后续失败重试直接复用缓存结果。App ID/Base URL 属于冻结执行身份,API Key 只从当前 Provider 读取以支持轮换。 - Run 的 `provider_config_json/provider_snapshot_json` 由独立迁移 `d28c9e0f1a2b` 增加;迁移链以“已执行版本不可改写、模型新增列必须新增 revision”为强约束。发布前同时执行迁移往返测试、`flask db current` 和数据库 inspector 列/外键/索引核对。 - 普通货代 Chatflow 继续处理无附件问答与订单后续交互,不承担订单抽取;专用 Workflow 画布由管理员手工维护。 -- 阶段 5 后订单抽取进度完全来自 Run API;状态卡继续保存到本地聊天消息并可由 Run 列表恢复,但普通聊天 SSE 不再发送或解析订单抽取事件。 -- 订单完整抽取不展示虚假百分比;Run 卡片展示排队、执行、结果持久化及终态摘要,轮询断线不改变后台作业状态。 -- 订单抽取进度采用“通用 Dify 事件采集、订单域映射”:`DifyService` 标准化 Workflow/节点 SSE 事件并以可选观察器上报,不保存订单业务状态;订单域以独立短事务持久化脱敏事件、Run 当前投影和90天明细。浏览器通过 Run API 自适应短轮询读取投影,用户端与管理员端按字段白名单分层展示。 -- Dify节点类型只映射通用技术阶段,不能推断精确业务目的;并行分支按阶段集合归并,终态和 HXOPS 落库阶段不可被迟到事件回退。进度记录失败不得影响 Dify 调用或订单落库事务。 +- 阶段 5 后订单抽取进度完全来自 Run / Unit / Progress Event 的数据库事实投影;状态卡继续保存到本地聊天消息并可由 Run 列表恢复,但普通聊天 SSE 不再发送或解析订单抽取事件。 +- 订单完整抽取不展示虚假百分比;Run 卡片展示排队、当前文件与业务动作、终态摘要及下一步操作,轮询断线不改变后台作业状态。 +- 订单抽取进度采用“订单域事实建模、工作台投影展示”:订单域以独立短事务持久化脱敏业务事件、Run 当前投影和 90 天明细;浏览器通过 Run API 与 Documents API 自适应短轮询读取投影,用户端与管理员端按字段白名单分层展示。 +- 订单进度事件只允许固定 `event_code` 与稳定原因码,不能依赖 Dify 节点标题、节点类型或自由显示文本推断业务阶段;迟到事件不得回退终态。进度记录失败不得影响订单落库事务。 ### 2.x 唯一订单 Schema 基础 @@ -1259,13 +1257,13 @@ Dify - **订单通用上下文字段目录**:订单 Schema 的稳定字段增加 `field_category` 与 `collection_mode`,`general_context` 固定为 Header + `deterministic_context`。`shipping_context_providers/options` 只维护展示、敏感等级、默认 Dify 策略和启停;可执行能力、允许暴露策略和脱敏器必须同时命中代码注册表。首批注册 `mail_header/from_email`、`mail_header/from_domain`,来源语义固定为原始 EML `From`,禁止任意 JSONPath、SQL、模型属性、模板指纹或自由 selector。版本快照冻结 provider/option/source key、敏感等级与 Dify 策略;来源停用或代码能力移除会阻止新发布,但不改写历史快照。Workflow 在 `execution_manifest.readonly_hints` 中接收按 Intake 分组的受控 JSON:`never` 不输出,`redacted` 只输出受控不可逆占位值,`confirmed_readonly` 只输出 Run 冻结值;三者均不进入 `extraction_contract.fields[]`,Dify 回传对应 `field_id` 仍由后端拒绝。 ## 2026-07-22 订单抽取唯一 Manifest 技术决策 -- Runtime Binding 只绑定执行器和运行参数;运行时不进行输入格式探测或多格式混传。 +- 订单抽取运行时不进行输入格式探测或多格式混传,执行参数由 Run 自身冻结。 - 唯一 Manifest 使用单 `document` 和 `structured_table_candidates`。候选只暴露稳定 field_id、值、短引文、行列位置与质量问题;原始布局证据保留在 HXOPS 冻结快照中。 - accepted 完整表走确定性零 Provider 路径;需要模型补充时,后端校验 accepted 字段集合和值未被删改。人工真值未完成前生产候选不提升 accepted。 - L6 Observation 通过 `evidence_ref + evidence_metadata_json` 保存文本、邮件头或 layout cell 证据身份。旧纯文本表格解析器只做候选检测,不再进入 verified Observation;accepted layout 仅按同 Document 强身份关联。 - L7 清理后 Worker 的零 Provider 分支只认 accepted layout;Profile/纯文本必须进入唯一 Manifest 上下文。 - L7 质量门禁独立保存匿名质量批次/双人标签,不保存订单字段值;Run 创建和 Worker 执行均复核当前 Schema、阈值、指标仍达标和双角色批准,避免配置后漂移或绕过。 -- **Profile 盲测资格门禁**:`shipping_document_profile_test_suites/samples/runs` 保存草稿/发布 Profile 的独立盲测集、管理员确认真值及不可变执行摘要,不复制订单正文。盲测集以 `profile_id + profile_checksum` 唯一绑定;模板保存改变草稿定义 hash 后,旧草稿集转为 `superseded`,新定义必须新建盲测集。发布事务校验至少 1 份训练样本、与 annotation/training 完全独立的 1 份盲测样本、至少 1 份多明细真值及跨页声明对应的 `continuation_of` 样本;全量通过并批准后,事务内将套件/执行记录的草稿 hash 原子提升为正式 Profile checksum。Run 创建只冻结正式 checksum 的 `auto_create_approved` 事实。确定性订单直接由该 Profile 的当前解析行生成,绝不借用其他 accepted layout 候选。Dify 输出在进入持久化前还会校验冻结 field_id 白名单、Unit document_id 和 quote 的逐字可验证性。 +- **Profile 盲测资格门禁**:`shipping_document_profile_test_suites/samples/runs` 保存草稿/发布 Profile 的独立盲测集、管理员确认真值及不可变执行摘要,不复制订单正文。盲测集以 `profile_id + profile_checksum` 唯一绑定;模板保存改变草稿定义 hash 后,旧草稿集转为 `superseded`,新定义必须新建盲测集。发布事务校验至少 1 份训练样本、与 annotation/training 完全独立的 1 份盲测样本、至少 1 份多明细真值及跨页声明对应的 `continuation_of` 样本;全量通过并批准后,事务内将套件/执行记录的草稿 hash 原子提升为正式 Profile checksum。Run 创建只冻结正式 checksum 的 `auto_create_approved` 事实。`shipping_document_profile_auto_freeze_qualifications` 进一步独立保存客户白名单、业务场景白名单和 `requires_customer_confirmation` 开关;Run 结果落库后按已确认 Bill-to 客户与当前业务场景刷新 `auto_freeze_policy_json`。在自动冻结执行入口接入前,该策略仍 fail-closed。确定性订单直接由该 Profile 的当前解析行生成,绝不借用其他 accepted layout 候选。Dify 输出在进入持久化前还会校验冻结 field_id 白名单、Unit document_id 和 quote 的逐字可验证性。 - **坐标 Profile 治理审计**:`shipping_order_document_profiles` 增加 `template_mode`、`training_sample_count` 与无正文 `match_strategy_summary_json`;`shipping_order_document_profile_samples` 仅绑定 Document/Table/角色,`shipping_order_document_profile_audits` 只记录对象身份、事件和计数/checksum 摘要。样本、区域、字段绑定、盲测和版本事件使用同一追加式审计表,禁止保存锚点文本、坐标、PDF、HTML、MinIO URL 或凭据。 - **受控坐标预览**:页面授权写入 Redis,key 为随机令牌且 TTL 120 秒;每个 token 固定管理员、Profile、Document、page_no,并通过 `GETDEL` 原子消费。Redis 不可用时预览 fail-closed。PDF 只在后端渲染低清单页 PNG;文本候选和局部预览按 Profile 样本关联再次鉴权,响应设置 `Cache-Control: private, no-store`。OCR 只能经绑定样本的显式管理员请求生成,EML 复用 HTML 白名单清洗结果且不渲染可执行 DOM。 - **订单客户指纹与冻结门禁**:`ShippingOrderCustomerMatch` 保留 Bill-to/Ship-to 原文、标准化组件、`order-customer-fingerprint.v1` 指纹、候选快照和确认理由。只有 `bill_to.status=confirmed` 且存在客户/简码/指纹/规则版本时 `order_freeze_service` 才冻结 Snapshot;冻结服务不接受外部 `customer_id` 或 `customer_short_code`。Snapshot 的 `rule_versions_json.ordering_customer` 保存匹配 ID、指纹、规则版本、确认方法和人员时间,避免主数据变化改写历史履约事实。 diff --git a/docs/test_plan_matrix.md b/docs/test_plan_matrix.md index 405f67f7..fde1404b 100644 --- a/docs/test_plan_matrix.md +++ b/docs/test_plan_matrix.md @@ -39,27 +39,28 @@ | **报表监控** | **数据导出** | 管理员导出用户、日志等数据为 Excel/CSV。 | 模拟 Admin GET `/api/admin/database/{table_name}`。 | URL Path: `/api/admin/database/chat_logs` | HTTP 200 OK; 返回完整数据列表。 | | **发货通知** | **建单幂等** | 相同 `create_idempotency_key` 重复请求返回同一批次,不重复启动 orchestrator。 | `test_shipping_notice_batches.py`:Workspace API 双次 POST;断言 `idempotent_replay`、任务数、orchestrator 调用次数。 | Header `Idempotency-Key` + 相同 notice 文件 | 第二次 `batch_no` 相同;`idempotent_replay=true`;DB 仅 1 批次。 | | **发货通知** | **同请求文件去重** | 同一次上传中内容相同文件只建 1 个任务。 | `test_notice_intake.py` / `test_shipping_notice_batches.py`:2 个同字节不同文件名。 | 2× 相同内容 PDF | `duplicate_count=1`;`tasks` 长度 1。 | -| **发货通知** | **上传只预处理** | 上传 EML 后只落 Intake/Document/派生附件资产,不调用 LLM、不生成 Candidate。 | `test_shipping_notice_intakes.py::test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candidates` | 1 EML + 3 PDF | `document_count=4`、`candidate_count=0`、`order_extraction_status=not_started`;重试不膨胀。 | +| **发货通知** | **上传快览与发送后物化** | 上传只落 Intake 快览:普通文件仅元信息;EML 仅邮件头、正文白名单快览和附件目录。点击发送才由 Worker 按选择计划创建 Document/派生资产并深度解析。 | `test_shipping_notice_intakes.py`、`test_shipping_order_extraction_runs.py::test_create_run_freezes_lightweight_input_without_sync_materialization`、`test_shipping_order_extraction_worker.py` | 普通 PDF/Word/Excel/图片、1 EML + 多附件 | 上传不读附件全文、不调度 OCR/布局、不创建附件 Document/派生资产或 Candidate;发送请求立即入队,Worker 首轮物化且重试不膨胀。 | +| **发货通知** | **上传批次、附件预算与自动冻结闭环** | 每次文件选择以独立 `upload_batch_id` 隔离;Worker 首轮实际并发最多 2、按需每轮扩展 2、总数最多 6,原始输入最多 30MB、总时限 5 分钟;自动冻结只消费模板资格和全部 Run/Task 门禁都放行的结果。 | `test_shipping_notice_upload_batch_migration.py`、`test_shipping_order_extraction_runs.py`、`test_shipping_notice_intakes.py::test_selected_normal_files_use_global_bounded_parallel_extraction`、`test_shipping_order_auto_freeze_policy.py` | 多次文件选择、跨批次伪造请求、两个独立普通文件、多附件 EML、超字节/超时、技术失败、Unit 复核、客户/场景越界 | 旧批次不得混入;峰值不超过 2 且主线程按输入顺序持久化;预算停止/复核/失败一律人工处理;自动冻结默认关闭,只有唯一授权模板、已确认白名单客户与场景、无任何阻断时才创建并冻结 Task。 | | **发货通知** | **订单抽取前端 Run 切流与恢复** | parsed Intake 发送只创建订单抽取 Run,不进入普通 Chatflow;新会话、刷新、断网和切会话均由 Run 状态恢复。 | `useChatShippingSendHandler.spec.ts`、`useShippingOrderExtractionRuns.spec.ts`、`useShippingNoticeIntakes.spec.ts` | 新会话、同状态重复轮询、列表请求失败、旧会话迟到响应、Run failed | `sendMessage` 未调用;URL 使用返回的 conversation;稳定 formId 原位更新;无变化不重复写 ChatLog;旧响应不污染当前会话;失败附件可重试。 | -| **发货通知** | **订单抽取能力显式绑定** | 货代 Agent 只能绑定启用的 internal Dify Workflow;无绑定、停用或类型不符时不创建 Run/Job。 | `test_agent_runtime_bindings.py`、`test_agent_runtime_binding_migration.py` | 无绑定、Chatflow/workspace Provider、停用 Provider、合法 Workflow | 非法配置返回稳定错误码;合法绑定安全序列化且不泄露 API Key;内部 Provider 不进入用户 Agent 列表。 | -| **发货通知** | **订单抽取可靠性与健康监控** | Run 健康端点聚合积压、失败、重试和四段时延;Worker 日志安全;浏览器 GET 可超时/取消。 | `test_shipping_order_extraction_runs.py`、`test_agent_runtime_bindings.py`、`useShippingOrderExtractionRuns.spec.ts` | queued/running 超阈值、终态失败、Provider 成功后 DB 失败、挂起 GET、切会话 abort、普通用户/非法参数 | health 正确 degraded/healthy;缓存结果不重复调用 Dify;日志/API 不含正文和 Provider;GET abort 不取消 Run、不伪造失败且继续退避。 | -| **发货通知** | **版本化重新识别** | 终态未消费 Run 使用当前发布规则创建新版本;失败 Run 的执行重试保持原冻结快照。 | `test_shipping_order_extraction_runs.py`、`useShippingOrderExtractionRuns.spec.ts`、前端 build | 终态/运行中/跨用户 Run、无效原因、重复点击、新版成功/失败、候选建单、当前 Schema/Profile/layout 变化 | 新 `run_no` 有来源谱系且无 Provider 缓存;同一活跃后继幂等复用;旧候选在新版执行期间不能建单;新版失败精确恢复旧候选选择状态;仅当前版本 Candidate 可建单;用户 API 仅输出脱敏版本关系与规则/布局差异摘要。 | -| **发货通知** | **订单抽取优化阶段 0 进度基础** | Dify 原生生命周期事件写入独立短事务并投影通用阶段;用户摘要/时间线按白名单展示;迁移可往返。 | `test_shipping_order_extraction_progress.py`、`test_order_extraction_progress_migration.py`、`test_shipping_order_extraction_runs.py`、`useShippingOrderExtractionRuns.spec.ts` | 重复/迟到/并行节点、自定义敏感节点标题、跨用户读取、阶段变化但 Run 状态不变、upgrade/downgrade | 事件幂等;终态及 HXOPS 落库阶段不回退;节点标题不持久化;用户仅见阶段/状态/时间;进度版本变化触发卡片更新;迁移无残留回滚;不展示虚假百分比。 | +| **发货通知** | **订单抽取本地执行边界** | Run、计划与 Worker 只执行本地确定性解析,不依赖应用管理、内部执行器、Runtime Binding 或 Dify Workflow。 | `test_order_extraction_deterministic_migration.py`、`test_shipping_order_extraction_runs.py`、静态依赖搜索 | 无应用绑定、Dify 不可用、Worker 重启、历史普通 Agent 记录 | Run/Job 可创建并完成;Worker 不发起 Dify 网络请求;用户 Agent 列表不含隐藏执行器概念。 | +| **发货通知** | **订单抽取可靠性与健康监控** | Run 健康端点聚合积压、失败、重试和本地解析时延;Worker 日志安全;浏览器 GET 可超时/取消。 | `test_shipping_order_extraction_runs.py`、`useShippingOrderExtractionRuns.spec.ts` | queued/running 超阈值、终态失败、解析持久化失败、挂起 GET、切会话 abort、普通用户/非法参数 | health 正确 degraded/healthy;重试复用已完成单元结果;日志/API 不含正文和解析快照;GET abort 不取消 Run、不伪造失败且继续退避。 | +| **发货通知** | **版本化重新识别** | 终态未消费 Run 使用当前发布解析规则创建新版本;失败 Run 的执行重试保持原冻结快照。 | `test_shipping_order_extraction_runs.py`、`useShippingOrderExtractionRuns.spec.ts`、前端 build | 终态/运行中/跨用户 Run、无效原因、重复点击、新版成功/失败、候选建单、当前 Schema/Profile/layout 变化 | 新 `run_no` 有来源谱系且无远程执行缓存;同一活跃后继幂等复用;旧候选在新版执行期间不能建单;新版失败精确恢复旧候选选择状态;仅当前版本 Candidate 可建单;用户 API 仅输出脱敏版本关系与规则/布局差异摘要。 | +| **发货通知** | **订单抽取进度基础** | HXOPS Run/Job 生命周期写入独立短事务并投影通用阶段;用户摘要/时间线按白名单展示。 | `test_shipping_order_extraction_progress.py`、`test_order_extraction_progress_facts_migration.py`、`test_shipping_order_extraction_runs.py`、`useShippingOrderExtractionRuns.spec.ts` | 重复/迟到/并行 Job、跨用户读取、阶段变化但 Run 状态不变、迁移 upgrade | 事件幂等;终态及结果持久化阶段不回退;用户仅见阶段/状态/时间;进度版本变化触发卡片更新;不展示虚假百分比。 | | **发货通知** | **订单抽取优化阶段 1 动态表格契约** | Run 冻结 Schema 的字段编码、显示名、别名、规范化器和校验器驱动确定性表格解析;后端安全规则不可由管理员覆盖。 | `test_order_schema_table_contract.py`、`test_shipping_order_schema_runtime.py`、`test_shipping_notice_extract.py` | 未配置别名、禁用/不支持字段、标准化别名碰撞、Reservation 禁用表头、重复列、retired 冻结版本、文档级 Reservation、未配置 UOM/币种/金额 | 无契约不猜列;碰撞/禁用表头阻止保存发布;重复列进入复核;旧冻结版本可重放;不扫描任意单元格、不广播 Reservation、不注入未启用字段。 | -| **发货通知** | **订单抽取优化阶段 2 抽取计划与文档单元** | Run 创建时持久化唯一计划;正文关系和附件分别成为冻结、可恢复的局部状态单元。 | `test_order_extraction_plan_migration.py`、`test_shipping_order_extraction_runs.py`、`test_agent_runtime_bindings.py` | 重复创建、邮件正文+附件顺序、跨 Intake 文档、局部成功/失败、非法状态跃迁、失败回到 pending、Worker 恢复、迁移往返 | 计划/单元幂等;复合外键阻止错挂;成功结果不被其他失败清除;计划准确汇总 partial_failed;重启可复用;迁移无残留回滚。 | -| **发货通知** | **订单抽取优化阶段 3 确定性优先与紧凑契约** | 每个单元先确定性解析;仅不完整单元以唯一单文档 Manifest 调用无状态 Dify。 | `test_agent_runtime_bindings.py`、`test_order_schema_table_contract.py`、`test_shipping_order_schema_runtime.py` | 完整表格、缺必填字段、兄弟附件敏感文本、伪造 sibling document_id、冻结只读提示、Provider 结果重放 | 完整表格 Dify 调用为零;模型输入只有当前 Document;跨单元 Intake/主文档/Observation 被拒;确定性和模型结果均通过统一 Schema/证据裁决。 | -| **发货通知** | **订单抽取优化阶段 4 并行与局部重试** | Dify 单元按冻结配置受控并行;失败只重试对应单元,主线程串行持久化并按 position 汇总。 | `test_agent_runtime_bindings.py`、前端 i18n parity/build | 峰值并发、首次超时后成功、成功单元复用、SQLite/线程隔离、配置边界、完成乱序 | 峰值不超过 2–4 配置且实际并行;单元 attempts/latency 可审计;线程不共享 ORM;已成功单元不重跑;四语言和构建通过。 | -| **发货通知** | **订单抽取优化阶段 5 跨文档合并与部分成功** | HXOPS 以唯一 PO 或强行身份合并 Observation;弱身份拆分,冲突阻断,失败单元不抹除成功结果。 | `test_order_extraction_merge.py`、`test_agent_runtime_bindings.py`、`test_shipping_order_schema_runtime.py` | 同 PO 数量冲突、同料号不同 Reservation、无可靠身份、一个单元永久失败 | 同订单只生成一个合并候选且保留双方证据;冲突不覆盖;弱身份不误合并;成功单元继续提交,Run needs_review 并显示失败单元数。 | -| **发货通知** | **订单抽取优化阶段 6 运行治理** | 冻结模型预算、Provider 进程级限流/熔断,并在管理员诊断中展示脱敏单元指标。 | `test_order_extraction_provider_guard.py`、`test_agent_runtime_bindings.py`、`test_shipping_order_extraction_runs.py`、前端 i18n/build | 模型单元超预算、连续失败开路、成功复位、跨 Run 并发、管理员/普通用户、诊断正文泄露 | 超预算零请求;熔断快速失败且可恢复;Provider 合计并发受限;管理员只见单元状态/attempt/duration/error_code,访问留痕;用户 API 不变。 | -| **发货通知** | **订单抽取优化阶段 7 影子验收与自动建单门禁** | 默认只落可审核 Candidate;明确开启后仍须通过所有现有业务与安全门禁。 | `test_shipping_notice_order_extraction.py`、`test_agent_runtime_bindings.py`、静态 v1 扫描、真实脱敏样本人工验收 | 默认关闭、显式开启、低置信/缺证据/冲突/重复、旧 v1 残留、100+ 脱敏 Run | 影子期合格 Candidate ready 但零 Task;开启后仅全门禁通过者建单;错误建单为 0;核心字段精确率≥99.5%、召回率≥98%;代码/手册无旧 v1。 | +| **发货通知** | **订单抽取优化阶段 2 抽取计划与文档单元** | Run 创建时持久化唯一计划;正文关系和附件分别成为冻结、可恢复的局部状态单元。 | `test_order_extraction_plan_migration.py`、`test_shipping_order_extraction_runs.py` | 重复创建、邮件正文+附件顺序、跨 Intake 文档、局部成功/失败、非法状态跃迁、失败回到 pending、Worker 恢复、迁移 upgrade | 计划/单元幂等;复合外键阻止错挂;成功结果不被其他失败清除;计划准确汇总 partial_failed;重启可复用。 | +| **发货通知** | **订单抽取优化阶段 3 确定性解析与紧凑结果** | 每个单元使用冻结 Schema/Profile 执行本地确定性解析,并将证据受控写入候选。 | `test_order_schema_table_contract.py`、`test_shipping_order_schema_runtime.py` | 完整表格、缺必填字段、兄弟附件敏感文本、伪造 sibling document_id、冻结只读提示、结果重放 | 完整表格不调用远程模型;跨单元 Intake/主文档/Observation 被拒;结果均通过统一 Schema/证据裁决。 | +| **发货通知** | **订单抽取优化阶段 4 并行与局部重试** | 本地单元按冻结配置受控并行;失败只重试对应单元,主线程串行持久化并按 position 汇总。 | `test_shipping_order_extraction_runs.py`、前端 i18n parity/build | 峰值并发、首次失败后成功、成功单元复用、SQLite/线程隔离、配置边界、完成乱序 | 峰值不超过配置且实际并行;单元 attempts/latency 可审计;线程不共享 ORM;已成功单元不重跑;四语言和构建通过。 | +| **发货通知** | **订单抽取优化阶段 5 跨文档合并与部分成功** | HXOPS 以唯一 PO 或强身份合并 Observation;弱身份拆分,冲突阻断,失败单元不抹除成功结果。 | `test_order_extraction_merge.py`、`test_shipping_order_schema_runtime.py` | 同 PO 数量冲突、同料号不同 Reservation、无可靠身份、一个单元永久失败 | 同订单只生成一个合并候选且保留双方证据;冲突不覆盖;弱身份不误合并;成功单元继续提交,Run needs_review 并显示失败单元数。 | +| **发货通知** | **订单抽取优化阶段 6 运行治理** | 冻结解析预算、Worker 进程级限流/熔断,并在管理员诊断中展示脱敏单元指标。 | `test_shipping_order_extraction_runs.py`、前端 i18n/build | 单元超预算、连续失败开路、成功复位、跨 Run 并发、管理员/普通用户、诊断正文泄露 | 超预算不执行;熔断快速失败且可恢复;Worker 合计并发受限;管理员只见单元状态/attempt/duration/error_code,访问留痕;用户 API 不变。 | +| **发货通知** | **订单抽取优化阶段 7 影子验收与自动建单门禁** | 默认只落可审核 Candidate;明确开启后仍须通过所有现有业务与安全门禁。 | `test_shipping_notice_order_extraction.py`、`test_shipping_order_extraction_quality_gate.py`、静态依赖扫描、真实脱敏样本人工验收 | 默认关闭、显式开启、低置信/缺证据/冲突/重复、旧路径残留、100+ 脱敏 Run | 影子期合格 Candidate ready 但零 Task;开启后仅全门禁通过者建单;错误建单为 0;核心字段精确率≥99.5%、召回率≥98%;代码/手册无旧执行器路径。 | | **发货通知** | **文档版面结构化 L0 契约与评测基线** | 用 `shipping_document_layout.v1` 统一页、真实坐标、词元、表格、行列、单元格、跨页关系和质量问题;人工真值与候选结果按 content hash 和 bbox IoU 评测;MinerU 仅输出经能力审计的候选。 | `test_shipping_document_layout_contract.py`、`test_shipping_document_layout_evaluation.py`、`test_shipping_document_layout_mineru.py`、至少 30 份脱敏文档人工真值 Review | 越界/零面积 bbox、标准化坐标越界、未知 token、重复 ID、跨度重叠、单元格超出表格、悬空/前向 continuation、blocking issue 冒充 accepted、真值哈希漂移、漏表/漏单元格/字段错配、MinerU 字符串 JSON/多文件/超大响应/Provider 错误、HTML 表格无或缺少 cell bbox | 契约和评测测试通过;ID/checksum 稳定;检测/归行归列/字段映射指标分离;MinerU 无完整 cell bbox 时确定性证据必须为 false;真实样本不进仓库/日志;原生与扫描 PDF、EML HTML、跨页、表头后置、多表等类别全部有人工真值后,L0 才可通过。 | | **发货通知** | **文档版面结构化 L0 MinerU 批量结构审计** | 使用 pipeline 对 30 个真实 PDF 做匿名结构与容量审计,验证页、bbox、HTML 表格和适配器坐标空间。 | `test_shipping_document_layout_mineru.py`、30 PDF 只读审计记录 | content bbox 0..1000 坐标转换、并发连接中断、顺序重试、无表格、无 cell bbox、响应大小 | 30/30 最终可解析;并发失败可分类且顺序复测成功;初始生产并发低于服务上限并使用异步任务;无完整 cell bbox 时不得接受高风险字段。 | | **发货通知** | **文档版面结构化 L1 版本与独立 Job 生命周期** | Intake 只调度布局,独立 Worker 按 Document 版本执行 MinerU;当前成功引用与失败历史隔离。 | `test_shipping_document_layout_lifecycle.py`、`test_shipping_document_layout_lifecycle_migration.py`、`test_shipping_document_layout_job.py`、`test_admin_shipping_document_layouts.py`、`test_shipping_notice_intakes.py` | 相同 parser 幂等、revision 漂移、旧 JSON 回填、超大 payload、Provider 异常、重试耗尽、超时回收、旧 lease 回写、Document 删除、管理员越权/隐私 | Intake 不内联调用 MinerU;迁移可往返且旧快照标记 legacy;活动版本唯一;失败不覆盖 current;旧 Worker 无法回写;Job/版本同步终结;诊断无 HTML/bbox/全文/内部异常;人工真值延期不影响生命周期测试但不得转化为准确率结论。 | | **发货通知** | **文档版面结构化 L2 原生 PDF 候选** | PDFium 提取真实字符坐标;MinerU HTML 仅通过唯一文本或严格有框表双门禁形成 layout.v1 cell/token 候选。 | `test_shipping_document_layout_native_pdf.py`、`test_shipping_document_layout_text_cell_alignment.py`、`test_shipping_document_layout_opencv_table.py`、`test_shipping_document_layout_runtime.py` | 真实空白 PDF、唯一/重复文本、跨行/重叠 glyph、有框/无框表、文本不一致、坏表与好表同页、PDFium 失败、revision v1→v2 | 不伪造扫描文本;cell 可追溯 token;歧义零 cell;逐表隔离;候选失败不丢 MinerU HTML;layout 固定 needs_review 且不进入 Dify。人工真值延期时只判工程测试,不判召回率/归行归列准确率/P95。 | | **发货通知** | **文档版面结构化 L3 OCR 与 EML HTML** | RapidOCR 保留多边形坐标;扫描表必须通过 OCR+OpenCV+全文本门禁。EML HTML 经白名单清理后按 DOM 网格输出同一 layout.v1。 | `test_shipping_document_layout_ocr_pdf.py`、`test_shipping_document_layout_html_layout.py`、`test_shipping_document_layout_native_pdf.py`、`test_shipping_notice_extract.py`、`test_shipping_notice_intakes.py` | OCR 坐标缩放、低置信、引擎缺失、有框/无框、OCR cell token;script/style/img/事件/链接、rowspan/colspan、坏表、plain 不变 HTML 变化、摘要泄漏 | OCR 无坐标或全文本不一致零 cell;HTML 主动内容清零;DOM 合并格不重叠;正文 hash 覆盖清洗表格;临时/原始 HTML 不入摘要/Dify;全部候选 needs_review。人工真值延期时不判真实 OCR 字符质量、跨度准确率和 10 页 P95。 | -| **发货通知** | **文档版面结构化 L4 冻结 Schema 证据映射** | layout.v1 Table 直接按 Run 冻结 Schema 映射,字段证据必须引用真实 cell/token;跨页只接受显式 continuation。 | `test_shipping_document_layout_schema_mapping.py`、`test_shipping_document_layout_html_table.py`、`test_shipping_order_extraction_runs.py`、`test_agent_runtime_bindings.py` | 后置表头、重复目标列、Qty=0、真实 cell/token/evidence_ref、显式/缺失 continuation、Run 后 Schema 漂移、Manifest 泄漏 | 映射复用既有安全规则;重复列全 ambiguous;零 Qty 删除;Run v3冻结候选不漂移;needs_review 只标 candidate且不进 Dify/确定性执行。人工真值延期时不判真实字段映射准确率,但错误自动接受数必须为 0。 | +| **发货通知** | **文档版面结构化 L4 冻结 Schema 证据映射** | layout.v1 Table 直接按 Run 冻结 Schema 映射,字段证据必须引用真实 cell/token;跨页只接受显式 continuation。 | `test_shipping_document_layout_schema_mapping.py`、`test_shipping_document_layout_html_table.py`、`test_shipping_order_extraction_runs.py` | 后置表头、重复目标列、Qty=0、真实 cell/token/evidence_ref、显式/缺失 continuation、Run 后 Schema 漂移 | 映射复用既有安全规则;重复列全 ambiguous;零 Qty 删除;Run 冻结候选不漂移;`needs_review` 只标候选且不进入自动建单。人工真值延期时不判真实字段映射准确率,但错误自动接受数必须为 0。 | | **发货通知** | **订单文档模板 Profile 纯契约** | 以表头网格精确结构指纹选择固定列规则,允许模板级字段语义覆盖全局 Schema;只运行注册解析器。 | `test_shipping_order_document_profile.py` | `Part Number -> customer_part_number`、`Vendor Item# -> part_number`、复合料号 cell、零 Qty、结构漂移、MinerU 行关系丢失、自由解析器注入 | 精确命中时模板映射原样生效;零 Qty 行删除;结构变化不做相似匹配;行关系丢失显式阻断;未知解析器或非法目标字段拒绝保存。 | -| **发货通知** | **订单文档 Profile 发布与运行锁定** | Profile 绑定不可变 Schema/稳定 field_id,版本化发布;Run 冻结完整 Profile 与 MinerU 紧凑布局,Worker 只执行唯一精确匹配。 | `test_shipping_order_document_profile_service.py`、`test_order_document_profile_migration.py`、`test_shipping_document_layout_runtime.py`、`test_agent_runtime_bindings.py`、`test_shipping_order_extraction_runs.py` | 并发草稿覆盖、新版发布、字段退役、Provider 失败、多附件预算、多表/多 Profile、零 Qty、Decimal JSON、布局 HTML 泄漏 Dify、Run 后配置变化 | 乐观锁与单 published 唯一索引生效;字段引用阻断退役;Run 快照不漂移;Provider 失败安全回退;唯一完整表跳过 Dify;多表不自动合并;HTML/bbox/field_code 不进入 Dify;零 Qty 删除。 | +| **发货通知** | **订单文档 Profile 发布与运行锁定** | Profile 绑定不可变 Schema/稳定 field_id,版本化发布;Run 冻结完整 Profile 与 MinerU 紧凑布局,Worker 只执行唯一精确匹配。 | `test_shipping_order_document_profile_service.py`、`test_order_document_profile_migration.py`、`test_shipping_document_layout_runtime.py`、`test_shipping_order_extraction_runs.py` | 并发草稿覆盖、新版发布、字段退役、解析失败、多附件预算、多表/多 Profile、零 Qty、Decimal JSON、Run 后配置变化 | 乐观锁与单 published 唯一索引生效;字段引用阻断退役;Run 快照不漂移;解析失败安全进入复核;唯一完整表可确定性解析;多表不自动合并;零 Qty 删除。 | | **发货通知** | **阶段 4 模板资格独立门禁** | 模板发布和自动冻结资格分别治理;首版只能人工确认。 | `test_shipping_document_profile_quality.py`、`test_profile_auto_freeze_qualification_migration.py` | 未盲测发布、盲测批准、模板新版本、checksum 变化、单模板暂停 | 发布模板可供解析但只生成 `manual_confirmation`;盲测不会自动开启冻结;资格按 Profile 版本/checksum 独立;暂停一个模板不影响其他模板;样本不足时 `auto_freeze_enabled=false`。 | | **发货通知** | **阶段 5 人工复核证据闭环** | 所有人工改单/冲突解决都提交结构化证据和订单版本。 | `test_shipping_task_field_reconciliation.py`、前端生产构建 | 手工输入、伪造 document_cell、跨订单 Observation、过期版本、行增删改、冲突解决 | 仅当前 Task/Extraction/Document 的 Observation 可用;手工输入须有原因;证据校验在写值前执行;审计保存前后值、字段/行、操作者与结构化证据;过期版本拒绝覆盖。 | | **发货通知** | **订单坐标 Profile v2 契约治理** | 模板以文档静态锚点、相对表区、独立表头/明细物理行、字段区域、受控解析器、排除/终止/跨页规则表达;字段绑定必须冻结 Schema field_id 且获坐标来源授权。 | `test_shipping_order_document_profile.py`、`test_shipping_order_document_profile_service.py`、前端生产构建 | 坐标越界/重叠、重复字段、物理行错序、未注册解析器、浏览器伪造 field_id、未授权 PDF/OCR 来源、旧网格行/列定义、过期 lock | 后端拒绝非法几何与歧义定义;表头布局和明细布局相互独立;字段 ID 后端重写;Schema 未授权来源阻断;新 Profile 不接收 HTML 网格、行号或固定列规则;乐观锁与不可变发布版本生效。 | @@ -67,13 +68,13 @@ | **发货通知** | **坐标修复模板闭环** | 结构污染 PDF 由管理员确认列边界后重建,确认结果随 Profile 与 Run 冻结。 | `test_shipping_coordinate_table_reconstruction.py`、`test_shipping_order_document_profile_service.py`、前端生产构建 | 表头混入首条明细、无文本层 PDF、非法边界、未确认候选、盲测与 Run 证据缺失 | 浏览器只看到候选网格;边界必须从 0 到 1 严格递增;重建固定待审核且须显式确认;Profile/Run/盲测只用冻结坐标证据,任何缺失均阻断,不回退原始错误网格或 Dify。 | | **发货通知** | **订单模板页样本上传** | 管理员可从订单文档模板页直接上传 PDF/EML,建立隔离样本 Intake 并复用异步预解析和布局 Job。 | `test_shipping_order_document_profile_service.py`、前端生产构建、Alembic upgrade | PDF、EML 正文 HTML、多附件 EML、非 PDF/EML、样本解析中/失败、业务 Intake 混入 | 样本 Intake purpose 固定为 `order_document_profile_sample`,不绑定会话,不创建 Candidate/Task/指纹或 Dify 调用;仅解析完成的单 Document 表格可配置 Profile;文件类型前后端均拒绝;样本状态不泄露正文、HTML 或 bbox。 | | **发货通知** | **订单模板样本治理与版本识别** | 样本可按文件名搜索并展示时间/状态;当前发布版本可辨识;专用样本受控删除。 | `test_shipping_order_document_profile_service.py`、前端生产构建 | 同名样本、历史业务附件、解析中样本、盲测引用、资产共享、多个版本 | 选择器标明文件名/时间/状态/表格数;同编码 published 版本标记当前生效;仅 `order_document_profile_sample` 的已解析、未盲测引用且未共享资产样本可删除;删除同步回收源文件和布局,历史业务附件及盲测证据不可删除。 | -| **发货通知** | **订单文档 Profile 独立盲测资格** | 发布 Profile 与确定性自动建单资格分离;盲测真值、执行摘要和批准状态绑定 checksum。 | `test_shipping_document_profile_quality.py`、`test_shipping_document_profile_quality_migration.py`、`test_agent_runtime_bindings.py` | 缺训练样本、复用 annotation/training 文档、少于 3 样本、无表头少于 5 样本、无多明细、缺跨页续页、真值不匹配、批准后编辑、checksum 漂移、未知/多模板、Dify 不可用 | 发布前至少 1 训练样本;盲测与建模样本完全独立,常规模板至少 3 个、无表头至少 5 个,含至少 1 个多明细及所需跨页续页样本;全通过且管理员批准后,草稿 hash 原子提升为正式 checksum 凭证;批准样本不可改;唯一已批准 Profile 直接生成确定性订单,其他情形回退 Dify/人工。 | -| **发货通知** | **Workflow 结果缓存与重试** | Dify 成功后先独立保存结构化 orders;即使无 workflow_run_id,HXOPS 落库失败重试也不得再次调用 Dify。 | `test_agent_runtime_bindings.py::test_worker_caches_provider_output_and_does_not_call_dify_twice` | 首次 Provider 成功、后续 DB 暂时失败 | Dify 调用 1 次、持久化尝试 2 次,Run 最终 completed。 | -| **发货通知** | **Provider 变更与密钥轮换** | App ID/Base URL 漂移阻断旧 Run;API Key 轮换允许旧 Run 使用新密钥继续。 | `test_agent_runtime_bindings.py` Provider drift / key rotation 用例 | 排队后修改 App ID、Base URL 或 API Key | 前两者 Run/Job failed 且不调用 Dify;密钥轮换成功完成。 | -| **发货通知** | **Run 安全视图与事务原子性** | 用户 API 不返回正文、Provider 快照/原始结果/配置;Agent 与 binding 保存同事务。 | `test_shipping_order_extraction_runs.py`、`tests/services/admin/test_agent_service.py` | 查询 Run;创建/更新时绑定校验失败 | 响应无敏感快照;失败后 Agent 字段和 binding 均不留下半成品。 | -| **发货通知** | **订单抽取断流与并发门禁** | 同一 Intake 只允许一个未释放 Run;Provider 结果缓存后 HXOPS 重试不得再次调用 Dify。 | test_shipping_order_extraction_runs.py、test_agent_runtime_bindings.py、useShippingOrderExtractionRuns.spec.ts | 重复创建、Provider 成功后落库失败、浏览器轮询中断 | 返回同一 Run;重试复用 Provider 结果;浏览器中断不取消后台 Run。 | +| **发货通知** | **订单文档 Profile 独立盲测资格** | 发布 Profile 与确定性自动建单资格分离;盲测真值、执行摘要和批准状态绑定 checksum。 | `test_shipping_document_profile_quality.py`、`test_shipping_document_profile_quality_migration.py` | 缺训练样本、复用 annotation/training 文档、少于 3 样本、无表头少于 5 样本、无多明细、缺跨页续页、真值不匹配、批准后编辑、checksum 漂移、未知/多模板 | 发布前至少 1 训练样本;盲测与建模样本完全独立,常规模板至少 3 个、无表头至少 5 个,含至少 1 个多明细及所需跨页续页样本;全通过且管理员批准后,草稿 hash 原子提升为正式 checksum 凭证;批准样本不可改;唯一已批准 Profile 直接生成确定性订单,其他情形进入人工复核。 | +| **发货通知** | **本地结果持久化与重试** | 单元解析完成后先独立保存结构化结果;HXOPS 落库失败重试不得重复解析已完成单元。 | `test_shipping_order_extraction_runs.py` | 首次单元成功、后续 DB 暂时失败 | 单元解析 1 次、持久化尝试 2 次,Run 最终 completed。 | +| **发货通知** | **本地解析版本冻结** | 解析器和策略版本漂移阻断旧 Run;无外部 App、URL 或密钥依赖。 | `test_order_extraction_deterministic_migration.py`、`test_shipping_order_extraction_runs.py` | 排队后修改解析器版本或策略 | Run/Job 使用冻结事实或安全失败;不调用远程服务。 | +| **发货通知** | **Run 安全视图与事务原子性** | 用户 API 不返回正文、解析快照或内部配置;Run、计划和 Job 的创建保持原子性。 | `test_shipping_order_extraction_runs.py` | 查询 Run;创建计划或 Job 失败 | 响应无敏感快照;失败后不留下半成品 Run/计划/Job。 | +| **发货通知** | **订单抽取断流与并发门禁** | 同一 Intake 只允许一个未释放 Run;已完成单元结果可在 HXOPS 重试中复用。 | `test_shipping_order_extraction_runs.py`、`useShippingOrderExtractionRuns.spec.ts` | 重复创建、单元成功后落库失败、浏览器轮询中断 | 返回同一 Run;重试复用单元结果;浏览器中断不取消后台 Run。 | | **发货通知** | **一附件多订单与部分成功** | 一个 Document 可形成多个 Candidate;高置信订单自动建 Task,低置信订单保留。 | `test_shipping_notice_order_extraction.py::test_persist_order_extraction_result_supports_multiple_orders_partial_success_and_replay` | 同一附件 2 个订单,其中 1 个低置信 | 2 Candidate、1 Task、1 pending;Intake=`partially_completed`;重放不重复建单。 | -| **发货通知** | **订单抽取快照与权限** | Run 冻结用户、会话、Schema、邮件上下文和 Document;排队期间来源变化必须拒绝。 | test_shipping_order_extraction_runs.py、test_agent_runtime_bindings.py、test_shipping_order_schema_runtime.py | 越权读取、App/Base URL 漂移、正文或确定性上下文变化 | 用户态不泄密;执行身份漂移和来源变化返回稳定错误码;不创建 Candidate。 | +| **发货通知** | **订单抽取快照与权限** | Run 冻结用户、会话、Schema、邮件上下文、Document 及解析版本;排队期间来源变化必须拒绝。 | `test_shipping_order_extraction_runs.py`、`test_shipping_order_schema_runtime.py` | 越权读取、解析版本漂移、正文或确定性上下文变化 | 用户态不泄密;执行版本漂移和来源变化返回稳定错误码;不创建 Candidate。 | | **发货通知** | **自动建单与流程字段门禁** | 分类、`part_number`/Qty 置信度与原文证据达标即建 Task;缺 Reservation 仍建单但禁止库存链;`inventory_source_hint` 仅作可选路由线索。 | `test_shipping_notice_order_extraction.py` / `test_shipping_notice_tools.py` | 高置信 `part_number`+Qty,Reservation 为空、库存源线索可选 | Task=`pending_review/rsv_req`;`auto_progress` 返回 needs_human 且禁止库存/匹配/Excel;库存源线索缺失不单独阻断。 | | **发货通知** | **字段分层、冻结与 Reservation 全局唯一(阶段 1)** | 57 个预置字段为版本化标准目录;固定滚动策略只校验当前最小履约字段与已确认客户,Reservation 按单列全局唯一绑定客户 PO。 | `test_shipping_order_snapshot.py`、`test_shipping_rolling_fulfillment.py`、`test_shipping_reservation_global_unique_migration.py`、`test_shipping_inventory_routing_engine.py` | 仅最小字段、缺任一字段、正/零/负 Decimal、未确认客户、同快照重复、跨 PO、同 PO 变更、有效 Artifact/上传、PO 大小写/空格、缺 PO | 不要求全部 57 字段;`customer_po_number` 用于 PO 判定;Snapshot 冻结策略和 field_id;路由只读 Snapshot;同 PO 变更返回前后差异并要求人工确认;不同 PO、重复 Reservation 和锁定修订阻断。 | | **发货通知** | **字段能力绑定与策略快照(阶段 2)** | 履约角色由受控策略而非 `business_purpose` 决定,自定义字段可按 scope/type 绑定能力。 | `test_shipping_fulfillment_policy.py`、`test_shipping_order_field_purposes.py`、`test_shipping_order_snapshot.py` | 自定义预约单字段、范围/类型错误、缺最低能力、新旧策略发布、冻结后策略变更 | 仅注册能力可绑定;错误绑定/无发布策略 fail closed;冻结保存完整策略定义,历史 Snapshot 不被新策略重解释。 | @@ -116,17 +117,17 @@ | **发货通知** | **试点容量、恢复与逐模板发布(阶段 7)** | 请求级/文件级/EML 级限制必须配置化;试点逐模板盲测、记录性能并验证 Worker 与备份恢复。 | `test_shipping_notice_batches.py::test_workspace_create_batch_rejects_configured_file_limit_before_intake`、既有 EML 限制/Job recovery/Profile blind-test 回归、运维演练记录 | 超过批量数、超过文件/附件限制、Worker 重启、同文件重试、3–5 个模板、数据库/RPA 共享目录恢复 | 超限无临时文件、无 Batch/Task;重启可恢复且不重复建单;每模板独立盲测通过;健康指标与 RPA 耗时形成试点记录;备份恢复核对 Artifact/Attempt/Reservation/审计,失败时自动建单/上传保持关闭。 | | **发货通知** | **字段对账与冲突门禁** | Candidate 空字段可补齐;双方非空不同落冲突;未解决冲突阻断库存/RPA/匹配/导出;改单带版本。 | `test_shipping_task_field_reconciliation.py` | open_existing 补 Reservation;多行同字段冲突;行重建后冲突存活 | applied/conflicted 可区分;下游入口无副作用;resolve 后重算 Gate。 | | **发货通知** | **唯一订单 Schema 发布门禁与版本治理** | 全局单 Schema;完整 JSON 定义是草稿/发布唯一真相;保存/发布使用乐观锁;发布事件追加审计。 | `test_shipping_order_schema.py`、`test_shipping_order_schema_version_governance_migration.py` | 动态字段、草稿、过期锁、连续发布、审计快照、迁移清理草稿、Profile/模板跨域字段引用、下游引用字段被新版本移除 | 契约 checksum 稳定;仅一个 published Schema 版本;过期锁返回 409;审计事件保留前后快照;字段退役和 Schema 发布均不可留下下游悬空引用。 | -| **发货通知** | **通用上下文字段来源与运行门禁** | 通用字段仅允许 Header 确定性采集;数据库目录必须命中代码注册表;Run/Extraction 冻结邮件上下文并写入统一值链。 | `test_context_fields_service.py`、`test_shipping_context_field_catalog_migration.py`、`test_shipping_order_schema_runtime.py`、`test_shipping_order_extraction_runs.py::test_run_submission_rejects_changed_frozen_mail_context`、`test_agent_runtime_bindings.py::test_workflow_inputs_use_frozen_extraction_contract_only` | From 邮箱/域名、非 ASCII 显示名、公共域名、缺失/非法/多地址、Reply-To/正文伪线索、重入、多 Intake、审计详情、Run 后元数据漂移、Dify 隔离、迁移往返 | 仅返回受控来源;任意 selector 无法保存;每个 Extraction 独立产生 Observation→Decision→FieldValue;missing 重入不重复;公共域名保留;漂移阻断;审计可重建;Workflow 不收到或回传通用确定性字段。 | +| **发货通知** | **通用上下文字段来源与运行门禁** | 通用字段仅允许 Header 确定性采集;数据库目录必须命中代码注册表;Run/Extraction 冻结邮件上下文并写入统一值链。 | `test_context_fields_service.py`、`test_shipping_context_field_catalog_migration.py`、`test_shipping_order_schema_runtime.py`、`test_shipping_order_extraction_runs.py::test_run_submission_rejects_changed_frozen_mail_context` | From 邮箱/域名、非 ASCII 显示名、公共域名、缺失/非法/多地址、Reply-To/正文伪线索、重入、多 Intake、审计详情、Run 后元数据漂移、迁移 upgrade | 仅返回受控来源;任意 selector 无法保存;每个 Extraction 独立产生 Observation→Decision→FieldValue;missing 重入不重复;公共域名保留;漂移阻断;审计可重建;本地解析不接受外部回传通用字段。 | | **发货通知** | **订单 Schema 历史版本浏览** | 版本列表分页加载,历史详情按需读取不可变快照,业务版本号可恢复 URL 查看位置。 | `test_admin_shipping_order_schema_history.py` | 管理员/普通用户权限、分页概要、指定版本定位、发布人展示、字段重命名后的历史快照 | 列表不返回完整定义;详情只读且保留当时 field_code/display_name;普通用户 403;`?version=V` 精确打开 V。 | | **发货通知** | **订单 Schema 版本差异与配置审计** | 后端按稳定 `field_id` 计算任意两个版本的属性级差异;审计时间线安全分页展示追加事件。 | `test_shipping_order_schema_diff.py` | 系统标识重命名、集合顺序、纳入状态、版本过滤、管理员/普通用户权限 | 重命名为 modified 而非删除/新增;数组返回增删和顺序变化;差异/时间线拒绝普通用户;审计接口不回传完整前后快照。 | | **发货通知** | **订单 Schema 运行追溯与历史复制** | 版本使用统计关联真实 `ShippingOrderExtraction`;单次解析展示锁定契约、冻结输入、LLM、裁决和值;不可变版本可复制为新草稿。 | `test_shipping_order_schema_runtime_audit.py`、`test_shipping_order_schema_runtime_audit_migration.py` | 多版本解析、状态分布、管理员/普通用户权限、Observation/Decision/Value 证据、字段改名、草稿源复制、迁移往返 | 使用统计不混入其他版本且可分页;审计详情不回读当前字段目录;输入/LLM/校验/证据完整;草稿不能作复制源;快照列和索引可 upgrade/downgrade。 | | **发货通知** | **动态字段数据库约束** | Header/Line 的 Observation、Decision 和 Value 可审计且目标唯一。 | `test_shipping_order_schema.py` | 同一 Extraction 重复 Header FieldValue | 数据库唯一索引拒绝重复值。 | | **发货通知** | **订单 Schema 迁移往返** | 阶段一新增表和 Task 当前解析引用可独立 upgrade/downgrade。 | `test_shipping_order_schema_migration.py` | SQLite 最小上一版本基线 | 核心表和列完整新增并完整移除。 | | **发货通知** | **动态 Schema 订单解析** | published 契约驱动 EML/PDF 同字段 Observation 与后端裁决。 | `test_shipping_order_schema_runtime.py`、`test_shipping_notice_order_extraction.py` | 跨 Document 一致、冲突、缺证据、Schema checksum 漂移 | 一致值 corroborated;冲突/缺证据阻断;accepted 值生成类型化投影。 | -| **发货通知** | **订单抽取异步 Run 阶段 1 历史门禁** | 独立 API 创建/查询领域 Run,冻结入口 Agent、会话、Intake/Document 正文和 published Schema;阶段 1 验收时不创建 Job。 | `test_shipping_order_extraction_runs.py`、`test_shipping_order_extraction_run_migration.py` | 正常创建、重复请求、活跃 Intake 冲突、无权限/跨用户、未解析/消费/过期、空 Document、迁移往返、结果落库后超时回退 | 阶段 2 扩展后 POST 仍返回 202 queued 且同步持有 Job;其余快照、幂等、双活跃、隐私与状态机门禁持续成立。 | +| **发货通知** | **订单抽取 Run/Unit 事实进度与工作台投影** | 订单解析进度只来自后端持久化的 Run / PDF Unit / Progress Event 事实;工作台按 `summary/current_activity/documents/available_actions` 渲染,不再猜测 Workflow 阶段。 | `test_shipping_order_extraction_runs.py`、`test_shipping_order_extraction_progress.py`、`test_order_extraction_progress_facts_migration.py`、`useShippingOrderExtractionRuns.spec.ts`、`useChat.spec.ts`、`ShippingOrderExtractionCard.spec.ts` | 单 PDF 成功、多 PDF 部分成功、全部业务拒识、技术失败、跨用户读取、页面刷新恢复、历史消息恢复、网络失败、详情抽屉、键盘关闭、服务端动作按钮 | Run 计数与文档结果一致;`completed + processing + review_required + failed + pending = total`;当前活动与事件码来自数据库事实;聊天卡片和详情抽屉不出现 Workflow/LLM/Provider 文案;页面刷新、重新登录和 Worker 重启后可恢复同一事实视图。 | | **发货通知** | **上传与订单版面准备状态一致性** | 文本预解析完成后继续汇总并轮询独立布局任务,活动布局不得过早创建订单识别 Run。 | `test_shipping_notice_intakes.py::test_intake_status_exposes_layout_lifecycle_without_blocking_terminal_fallback`、`useShippingNoticeIntakes.spec.ts`、`attachmentCard.utils.spec.ts` | 无布局任务、queued/running、ready、failed/unsupported、刷新恢复、直接点击发送、四语言错误码 | `not_required` 与终态允许发送;`processing` 持续轮询并显示版面处理中;后端仍返回稳定门禁;失败布局可走文本/Dify 兜底且不永久卡住。 | | **发货通知** | **订单模板路由决策审计** | 每个 Unit 在后端确定性解析或人工复核前持久化脱敏路由事实;重试只追加不覆盖。 | `test_shipping_order_profile_matcher.py`、`test_shipping_order_extraction_stage0.py`、迁移 upgrade/downgrade 测试 | 缺失锚点、分差歧义、证据不足、未批准模板、多表、无有效行、Job 重试、Run 删除、管理员详情与普通用户访问 | 缺失项仅输出 `anchor_id`;稳定原因码完整;`unit_id + job_id + attempt_no` 唯一;审计先于结果写入;业务拒识为 `skipped/needs_review`;DTO/页面无正文、字段值、quote、坐标、Prompt 或凭据。 | -| **发货通知** | **阶段 0 统一状态与追加式审计** | 路由结果统一为 `deterministic/review_required/skipped`;业务拒识不计技术失败;Run 状态变化与路由结果追加至统一审计账本。 | `test_shipping_audit_event.py`、`test_shipping_audit_event_migration.py`、路由/Run 状态测试 | 未命中模板、模板歧义、技术异常、状态变化、敏感元数据、ORM 更新/删除、迁移升级回退 | 业务拒识进入 `needs_review`;技术故障才进入 `failed`;审计含 actor/request/correlation/状态哈希,且拒绝正文、凭据、更新和删除。 | +| **发货通知** | **阶段 0 统一状态与追加式审计** | 路由结果统一为 `deterministic/review_required/skipped`;业务拒识不计技术失败;Run 状态变化与路由结果追加至统一审计账本。 | `test_shipping_audit_event.py`、`test_shipping_audit_event_migration.py`、路由/Run 状态测试 | 未命中模板、模板歧义、技术异常、状态变化、敏感元数据、ORM 更新/删除、迁移升级回退 | 业务拒识进入 `review_required` 或 `partially_completed`,不会伪装为技术失败;技术故障才进入 `failed`;审计含 actor/request/correlation/状态哈希,且拒绝正文、凭据、更新和删除。 | | **发货通知** | **确定性订单 Run 与迁移一致性(阶段 1)** | 订单 Run 不再保存或依赖 Provider、Dify Workflow、质量批次或 Runtime Binding;版本、结果和人工冻结策略是新的冻结事实。 | `test_order_extraction_deterministic_migration.py`、`test_shipping_order_extraction_runs.py`、数据库 inspector 冒烟检查 | 从阶段 0 revision upgrade/downgrade;无 Runtime Binding 创建/重试/重新识别 Run;Dify 不可用 | 迁移往返通过;Alembic 为唯一 head;旧 Provider 列不存在;创建和 Worker 均不触发 Dify 网络调用;模型和数据库一致。 | | **发货通知** | **EML 正文补充表(阶段 2)** | 正文 HTML 表是 PO 级补充事实,不创建订单 Unit;只可按安全关联补 Reservation/Allocation/来源字段。 | `test_email_supplement_merge.py`、`test_shipping_order_extraction_runs.py` | `PO + MPN`、唯一 Reservation 的 PO 降级、多 Reservation、HTML 单元格证据、正文数量与 PDF 数量冲突 | 正文不生成独立订单;PDF 数量不被覆盖;每个补充值可追溯到正文表格/行/列/DOM cell;任何歧义稳定进入 `needs_review`。 | | **发货通知** | **PDF 模板 PO 拆分与拒识(阶段 3)** | 单 PDF 仅在逐行 PO 证据完整时拆分;四类表计数由 Route Decision 审计。 | `test_order_extraction_pdf_po_split.py`、`test_order_route_table_counter_migration.py` | 两个逐行 PO、未证明第二 PO、表级多 PO、多个业务表、模板歧义/漂移 | 逐行 PO 自动拆为独立订单;无可证明归属不猜测;真实表数不被匹配数替代;审核投影不泄露订单值或坐标。 | @@ -145,6 +146,6 @@ | **发货通知** | **共享库存文件解析方案** | 多库存站点共享版本化文件结构和订单匹配定义。 | `test_inventory_parsing_profile.py`、`test_shipping_inventory_service.py` | 结构化目录、published 绑定、禁用站点分步配置、多版本并存、退役引用、当前订单模板字段门禁 | 同方案可绑定多站点;新版本不破坏旧绑定;引用中版本不可退役;定义 checksum 不可变。 | | **发货通知** | **版本化 Excel 模板与 Artifact** | 库存源选择 published 模板,按稳定动态字段与 Profile match_keys 生成并锁定完整输入版本。 | `test_shipping_excel_template.py`、`test_shipping_template_migrations.py` | MinIO 替身、真实 xlsx、反序库存、歧义多命中、Header/Line、多 Source、迁移往返、提交失败 | 模板不依赖本机磁盘;行序不影响匹配;冲突阻断且无孤立文件;Artifact 含模板、Schema、Profile、checksum。 | | **发货通知** | **批次 ZIP 下载** | 工作台按批次或显式勾选任务集合下载每票当前可信 Artifact。 | `test_shipping_export_archive.py`、`exportSelection.spec.ts` | 同名、失效引用、缺失文件、损坏 checksum、越权、API attachment、选择去重/取消/可见范围/100 票上限 | 当前有效文件均包含且不覆盖;旧失效 Artifact 排除;manifest 完整;越权整体拒绝;返回 application/zip;显式选择不会携带筛选后不可见任务。 | -| **发货通知** | **唯一 Manifest 与紧凑候选** | Run 冻结唯一 Manifest;模型输入不含版面原始载荷。 | `test_agent_runtime_bindings.py`、前端 `npm run build` | Binding 运行中改动、needs_review/accepted 候选、完整 accepted 表 | 只含稳定字段候选;HTML/bbox/token/cell/evidence/field_code 不泄漏;accepted 值不可覆盖;完整 accepted 表零 Provider。人工真值与 95% 质量指标延期。 | +| **发货通知** | **冻结执行清单与紧凑候选** | Run 冻结本地解析所需的文档、Schema、Profile、解析器和策略版本;候选不携带版面原始载荷。 | `test_shipping_order_extraction_runs.py`、前端 `npm run build` | 运行中规则改动、needs_review/accepted 候选、完整 accepted 表 | 只含稳定字段候选;HTML/bbox/token/cell/evidence/field_code 不进入用户 API;accepted 值不可覆盖。人工真值与 95% 质量指标延期。 | | **发货通知** | **L6 可追溯证据裁决** | accepted Observation 必须有稳定证据引用;无 cell 纯文本表格不可冒充 verified;跨文档不得按 Qty 串值。 | `test_shipping_order_schema_runtime.py`、`test_shipping_notice_order_extraction.py`、`test_shipping_order_extraction_runs.py`、`test_shipping_order_layout_evidence_migration.py` | accepted cell 补字段、layout/LLM 冲突、纯文本表格、同 Qty 多附件、迁移往返、诊断隐私、UI 原因码 | accepted layout 保存 Document/Page/Table/Row/Column/Cell;文本与邮件头也有引用;needs_review 原因机器可读;管理员只见计数/原因码;无值、quote、cell ID 泄漏。真实质量统计延期 L7。 | -| **发货通知** | **L7 启用准备与旧路径清理** | 零 Provider 只允许 accepted layout;Profile/纯文本不得自动生成订单;无批准质量批次不得开启自动建单。 | `test_agent_runtime_bindings.py`、`test_shipping_order_extraction_quality_gate.py`、质量迁移往返、前端 `npm run build`、静态代码搜索 | 完整纯文本表、精确 Profile、accepted layout、双人一致/分歧标签、同人双批准、首次批准后改标签、当前 Schema 漂移、Run/Worker 批次漂移、管理 API 脱敏、启用 UI | 纯文本/Profile 均调用 Provider;accepted layout 仍可零 Provider;自动建单要求当前 Schema、100 个达标一致样本、不同业务/技术批准和 Run 冻结批次,Worker 执行前复核。人工真值延期时没有批准批次、UI/后端均保持关闭;100+20 真实 Run和Dify实配缺失时 L7 明确未通过。 | +| **发货通知** | **L7 启用准备与旧路径清理** | 自动建单只允许 accepted layout;Profile/纯文本不得绕过质量门禁;无批准质量批次不得开启自动建单。 | `test_shipping_order_extraction_quality_gate.py`、质量迁移检查、前端 `npm run build`、静态代码搜索 | 完整纯文本表、精确 Profile、accepted layout、双人一致/分歧标签、同人双批准、首次批准后改标签、当前 Schema 漂移、Run/Worker 批次漂移、管理 API 脱敏、启用 UI | 自动建单要求当前 Schema、100 个达标一致样本、不同业务/技术批准和 Run 冻结批次,Worker 执行前复核。人工真值延期时没有批准批次、UI/后端均保持关闭;100+20 真实 Run 缺失时 L7 明确未通过。 | diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 0d168b1b..95342586 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -26,8 +26,10 @@ "devDependencies": { "@types/node": "^24.10.1", "@vitejs/plugin-vue": "^6.0.2", + "@vue/test-utils": "^2.4.11", "@vue/tsconfig": "^0.8.1", "autoprefixer": "^10.4.24", + "jsdom": "^29.1.1", "postcss": "^8.5.6", "tailwindcss": "^3.4.17", "typescript": "~5.9.3", @@ -48,6 +50,57 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/@asamuzakjp/css-color": { + "version": "5.1.11", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.11.tgz", + "integrity": "sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/generational-cache": "^1.0.1", + "@csstools/css-calc": "^3.2.0", + "@csstools/css-color-parser": "^4.1.0", + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/@asamuzakjp/dom-selector": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-7.1.1.tgz", + "integrity": "sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/generational-cache": "^1.0.1", + "@asamuzakjp/nwsapi": "^2.3.9", + "bidi-js": "^1.0.3", + "css-tree": "^3.2.1", + "is-potential-custom-element-name": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/@asamuzakjp/generational-cache": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@asamuzakjp/generational-cache/-/generational-cache-1.0.1.tgz", + "integrity": "sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/@asamuzakjp/nwsapi": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz", + "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==", + "dev": true, + "license": "MIT" + }, "node_modules/@babel/helper-string-parser": { "version": "7.27.1", "resolved": "https://mirrors.tencent.com/npm/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", @@ -94,6 +147,159 @@ "node": ">=6.9.0" } }, + "node_modules/@bramus/specificity": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz", + "integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-tree": "^3.0.0" + }, + "bin": { + "specificity": "bin/cli.js" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.0.tgz", + "integrity": "sha512-064IFJdjTfUqnjpCVpMOdbr8FLQBhinbZj6yRv2An2E41O/pLEXqfFRWqGq/SxlE5PEUYTlvWsG2r8MswAVvkg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@csstools/css-calc": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.3.0.tgz", + "integrity": "sha512-c5ihYsPkdG6JCkU2zTMm4+k6r7RXuGxtWYhu5DHMIiF1FHzrfmHL5so11AoFpUv/tu61xfcmT4AmKoFfMPoqdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.1.10.tgz", + "integrity": "sha512-UZhQLIUyJaaMepqehrCODwCg2KW25vFvLWBmqYFaPclYvvxzj/sG8LBOhBFCp11i9uE7t1EyS+RAoV9tztPFyw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^6.1.0", + "@csstools/css-calc": "^3.3.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz", + "integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^4.0.0" + } + }, + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.7.tgz", + "integrity": "sha512-fQ+05118eQS1cofO3aJpB5efgpBZMvIzwr/sbC8kDLVA5XLG8q1kJV5yzrUAI1f7lvhPnm8fgIjzFB8/O/5Dig==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "peerDependencies": { + "css-tree": "^3.2.1" + }, + "peerDependenciesMeta": { + "css-tree": { + "optional": true + } + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.0.tgz", + "integrity": "sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + } + }, "node_modules/@emnapi/core": { "version": "1.8.1", "resolved": "https://mirrors.tencent.com/npm/@emnapi/core/-/core-1.8.1.tgz", @@ -128,6 +334,24 @@ "tslib": "^2.4.0" } }, + "node_modules/@exodus/bytes": { + "version": "1.15.1", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.1.tgz", + "integrity": "sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, "node_modules/@intlify/core-base": { "version": "11.2.8", "resolved": "https://mirrors.tencent.com/npm/@intlify/core-base/-/core-base-11.2.8.tgz", @@ -172,6 +396,24 @@ "url": "https://github.com/sponsors/kazupon" } }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://mirrors.tencent.com/npm/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", @@ -259,6 +501,13 @@ "node": ">= 8" } }, + "node_modules/@one-ini/wasm": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@one-ini/wasm/-/wasm-0.1.1.tgz", + "integrity": "sha512-XuySG1E38YScSJoMlqovLru4KTUNSjgVTIjyh7qMX6aNN5HY5Ct5LhRJdxO79JtTzKfzV/bnWpz+zquYrISsvw==", + "dev": true, + "license": "MIT" + }, "node_modules/@oxc-project/runtime": { "version": "0.114.0", "resolved": "https://mirrors.tencent.com/npm/@oxc-project/runtime/-/runtime-0.114.0.tgz", @@ -279,6 +528,17 @@ "url": "https://github.com/sponsors/Boshen" } }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, "node_modules/@rolldown/binding-android-arm64": { "version": "1.0.0-rc.5", "resolved": "https://mirrors.tencent.com/npm/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.5.tgz", @@ -946,6 +1206,27 @@ "integrity": "sha512-cfWa1fCGBxrvaHRhvV3Is0MgmrbSCxYTXCSCau2I0a1Xw1N1pHAvkWCiXPRAqjvToILvguNyEwjevUqAuBQWvQ==", "license": "MIT" }, + "node_modules/@vue/test-utils": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/@vue/test-utils/-/test-utils-2.4.11.tgz", + "integrity": "sha512-GDqaqZsA6m2E5vNzej0aYiIb6BX8xV9pNSbbbXKOfEYwg7ZNblVX8suyqmUBThq8VIrgAJNxn+z72hVtUeiWHA==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-beautify": "^1.14.9", + "vue-component-type-helpers": "^3.0.0" + }, + "peerDependencies": { + "@vue/compiler-dom": "3.x", + "@vue/server-renderer": "3.x", + "vue": "3.x" + }, + "peerDependenciesMeta": { + "@vue/server-renderer": { + "optional": true + } + } + }, "node_modules/@vue/tsconfig": { "version": "0.8.1", "resolved": "https://mirrors.tencent.com/npm/@vue/tsconfig/-/tsconfig-0.8.1.tgz", @@ -965,6 +1246,16 @@ } } }, + "node_modules/abbrev": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-2.0.0.tgz", + "integrity": "sha512-6/mh1E2u2YgEsCHdY0Yx5oW+61gZU+1vXaoiHHrpKeuRNNgFvS+/jrwHiQhB5apAf5oB7UB7E19ol2R2LKH8hQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, "node_modules/adler-32": { "version": "1.3.1", "resolved": "https://mirrors.tencent.com/npm/adler-32/-/adler-32-1.3.1.tgz", @@ -981,6 +1272,32 @@ "dev": true, "license": "MIT" }, + "node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, "node_modules/any-promise": { "version": "1.3.0", "resolved": "https://mirrors.tencent.com/npm/any-promise/-/any-promise-1.3.0.tgz", @@ -1065,6 +1382,13 @@ "postcss": "^8.1.0" } }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, "node_modules/baseline-browser-mapping": { "version": "2.10.0", "resolved": "https://mirrors.tencent.com/npm/baseline-browser-mapping/-/baseline-browser-mapping-2.10.0.tgz", @@ -1078,6 +1402,16 @@ "node": ">=6.0.0" } }, + "node_modules/bidi-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz", + "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" + } + }, "node_modules/binary-extensions": { "version": "2.3.0", "resolved": "https://mirrors.tencent.com/npm/binary-extensions/-/binary-extensions-2.3.0.tgz", @@ -1099,6 +1433,16 @@ "url": "https://github.com/sponsors/antfu" } }, + "node_modules/brace-expansion": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.2.tgz", + "integrity": "sha512-w5JZcKgdhDOgOwm8H+KgbosopHMuGcl6qbulwjtz3SM7I7P3yW1eAjzMPLrIE+NQ9vjgANKHWeMHnrT0OXW1oA==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, "node_modules/braces": { "version": "3.0.3", "resolved": "https://mirrors.tencent.com/npm/braces/-/braces-3.0.3.tgz", @@ -1243,6 +1587,26 @@ "node": ">=0.8" } }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, "node_modules/commander": { "version": "4.1.1", "resolved": "https://mirrors.tencent.com/npm/commander/-/commander-4.1.1.tgz", @@ -1252,6 +1616,17 @@ "node": ">= 6" } }, + "node_modules/config-chain": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/config-chain/-/config-chain-1.1.13.tgz", + "integrity": "sha512-qj+f8APARXHrM0hraqXYb2/bOVSV4PvJQlNZ/DVj0QrmNM2q2euizkeuVckQ57J+W0mRH6Hvi+k50M4Jul2VRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ini": "^1.3.4", + "proto-list": "~1.2.1" + } + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -1298,6 +1673,35 @@ "node": ">=18" } }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, "node_modules/cssesc": { "version": "3.0.0", "resolved": "https://mirrors.tencent.com/npm/cssesc/-/cssesc-3.0.0.tgz", @@ -1316,6 +1720,27 @@ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "license": "MIT" }, + "node_modules/data-urls": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz", + "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^16.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://mirrors.tencent.com/npm/detect-libc/-/detect-libc-2.1.2.tgz", @@ -1338,6 +1763,42 @@ "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", "license": "MIT" }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "dev": true, + "license": "MIT" + }, + "node_modules/editorconfig": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/editorconfig/-/editorconfig-1.0.7.tgz", + "integrity": "sha512-e0GOtq/aTQhVdNyDU9e02+wz9oDDM+SIOQxWME2QRjzRX5yyLAuHDE+0aE8vHb9XRC8XD37eO2u57+F09JqFhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@one-ini/wasm": "0.1.1", + "commander": "^10.0.0", + "minimatch": "^9.0.1", + "semver": "^7.5.3" + }, + "bin": { + "editorconfig": "bin/editorconfig" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/editorconfig/node_modules/commander": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-10.0.1.tgz", + "integrity": "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + } + }, "node_modules/electron-to-chromium": { "version": "1.5.302", "resolved": "https://mirrors.tencent.com/npm/electron-to-chromium/-/electron-to-chromium-1.5.302.tgz", @@ -1345,6 +1806,13 @@ "dev": true, "license": "ISC" }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true, + "license": "MIT" + }, "node_modules/entities": { "version": "7.0.1", "resolved": "https://mirrors.tencent.com/npm/entities/-/entities-7.0.1.tgz", @@ -1456,6 +1924,23 @@ "node": ">=8" } }, + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "dev": true, + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/frac": { "version": "1.1.2", "resolved": "https://mirrors.tencent.com/npm/frac/-/frac-1.1.2.tgz", @@ -1502,6 +1987,28 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/glob": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz", + "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/glob-parent": { "version": "6.0.2", "resolved": "https://mirrors.tencent.com/npm/glob-parent/-/glob-parent-6.0.2.tgz", @@ -1541,6 +2048,26 @@ "integrity": "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==", "license": "MIT" }, + "node_modules/html-encoding-sniffer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz", + "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.6.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "dev": true, + "license": "ISC" + }, "node_modules/is-binary-path": { "version": "2.1.0", "resolved": "https://mirrors.tencent.com/npm/is-binary-path/-/is-binary-path-2.1.0.tgz", @@ -1577,6 +2104,16 @@ "node": ">=0.10.0" } }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/is-glob": { "version": "4.0.3", "resolved": "https://mirrors.tencent.com/npm/is-glob/-/is-glob-4.0.3.tgz", @@ -1598,6 +2135,13 @@ "node": ">=0.12.0" } }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, "node_modules/is-what": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/is-what/-/is-what-5.5.0.tgz", @@ -1610,6 +2154,29 @@ "url": "https://github.com/sponsors/mesqueeb" } }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, "node_modules/jiti": { "version": "1.21.7", "resolved": "https://mirrors.tencent.com/npm/jiti/-/jiti-1.21.7.tgz", @@ -1619,6 +2186,76 @@ "jiti": "bin/jiti.js" } }, + "node_modules/js-beautify": { + "version": "1.15.4", + "resolved": "https://registry.npmjs.org/js-beautify/-/js-beautify-1.15.4.tgz", + "integrity": "sha512-9/KXeZUKKJwqCXUdBxFJ3vPh467OCckSBmYDwSK/EtV090K+iMJ7zx2S3HLVDIWFQdqMIsZWbnaGiba18aWhaA==", + "dev": true, + "license": "MIT", + "dependencies": { + "config-chain": "^1.1.13", + "editorconfig": "^1.0.4", + "glob": "^10.4.2", + "js-cookie": "^3.0.5", + "nopt": "^7.2.1" + }, + "bin": { + "css-beautify": "js/bin/css-beautify.js", + "html-beautify": "js/bin/html-beautify.js", + "js-beautify": "js/bin/js-beautify.js" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/js-cookie": { + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.8.tgz", + "integrity": "sha512-yeJd4aNAdYZQjaon2bpD/Gb0B/omw7HQOsynXXcOiWVCacbBcPlgn8S/d1X6blFSaHao7ozqtW7NZW19xpCtIw==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "29.1.1", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-29.1.1.tgz", + "integrity": "sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^5.1.11", + "@asamuzakjp/dom-selector": "^7.1.1", + "@bramus/specificity": "^2.4.2", + "@csstools/css-syntax-patches-for-csstree": "^1.1.3", + "@exodus/bytes": "^1.15.0", + "css-tree": "^3.2.1", + "data-urls": "^7.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^6.0.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.3.5", + "parse5": "^8.0.1", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^6.0.1", + "undici": "^7.25.0", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^16.0.1", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24.0.0" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, "node_modules/lightningcss": { "version": "1.31.1", "resolved": "https://mirrors.tencent.com/npm/lightningcss/-/lightningcss-1.31.1.tgz", @@ -1898,6 +2535,16 @@ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "license": "MIT" }, + "node_modules/lru-cache": { + "version": "11.5.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz", + "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/lucide-vue-next": { "version": "0.575.0", "resolved": "https://mirrors.tencent.com/npm/lucide-vue-next/-/lucide-vue-next-0.575.0.tgz", @@ -1937,6 +2584,13 @@ "node": ">= 20" } }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "dev": true, + "license": "CC0-1.0" + }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://mirrors.tencent.com/npm/merge2/-/merge2-1.4.1.tgz", @@ -1980,6 +2634,32 @@ "mini-svg-data-uri": "cli.js" } }, + "node_modules/minimatch": { + "version": "9.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", + "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.2" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, "node_modules/mitt": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz", @@ -2029,6 +2709,22 @@ "dev": true, "license": "MIT" }, + "node_modules/nopt": { + "version": "7.2.1", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-7.2.1.tgz", + "integrity": "sha512-taM24ViiimT/XntxbPyJQzCG+p4EKOpgD3mxFwW38mGjVUrfERQOeY4EDHjdnptttfHuHQXFx+lTP08Q+mLa/w==", + "dev": true, + "license": "ISC", + "dependencies": { + "abbrev": "^2.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://mirrors.tencent.com/npm/normalize-path/-/normalize-path-3.0.0.tgz", @@ -2070,6 +2766,39 @@ "node": ">=12.20.0" } }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, + "node_modules/parse5": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz", + "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^8.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5/node_modules/entities": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz", + "integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/path-browserify": { "version": "1.0.1", "resolved": "https://mirrors.tencent.com/npm/path-browserify/-/path-browserify-1.0.1.tgz", @@ -2077,12 +2806,46 @@ "dev": true, "license": "MIT" }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/path-parse": { "version": "1.0.7", "resolved": "https://mirrors.tencent.com/npm/path-parse/-/path-parse-1.0.7.tgz", "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", "license": "MIT" }, + "node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-scurry/node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, "node_modules/pathe": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", @@ -2311,6 +3074,23 @@ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", "license": "MIT" }, + "node_modules/proto-list": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/proto-list/-/proto-list-1.2.4.tgz", + "integrity": "sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==", + "dev": true, + "license": "ISC" + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://mirrors.tencent.com/npm/queue-microtask/-/queue-microtask-1.2.3.tgz", @@ -2364,6 +3144,16 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/resolve": { "version": "1.22.11", "resolved": "https://mirrors.tencent.com/npm/resolve/-/resolve-1.22.11.tgz", @@ -2479,6 +3269,55 @@ "queue-microtask": "^1.2.2" } }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/siginfo": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", @@ -2486,6 +3325,19 @@ "dev": true, "license": "ISC" }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/source-map-js": { "version": "1.2.1", "resolved": "https://mirrors.tencent.com/npm/source-map-js/-/source-map-js-1.2.1.tgz", @@ -2530,6 +3382,110 @@ "dev": true, "license": "MIT" }, + "node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/string-width-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/sucrase": { "version": "3.35.1", "resolved": "https://mirrors.tencent.com/npm/sucrase/-/sucrase-3.35.1.tgz", @@ -2576,6 +3532,13 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, "node_modules/tailwindcss": { "version": "3.4.17", "resolved": "https://mirrors.tencent.com/npm/tailwindcss/-/tailwindcss-3.4.17.tgz", @@ -2677,6 +3640,26 @@ "node": ">=14.0.0" } }, + "node_modules/tldts": { + "version": "7.4.9", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.9.tgz", + "integrity": "sha512-3kZ8wQQ/k5DrChD4X4FVvr2D7E5uoRgAqkPyLpSCGUvqOvqu+JEdr3mwMUaVWb+vMHZaKhF5fp2PBigKsui7hA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.4.9" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.4.9", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.9.tgz", + "integrity": "sha512-DxKfPBI52p2msTEu7MPhdpdDTBhhVQg1a/8PjQckeyAvO13eMYElX545grIp6nnTGIMZlRvFZPvFhvI/WIz2Vg==", + "dev": true, + "license": "MIT" + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://mirrors.tencent.com/npm/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -2689,6 +3672,32 @@ "node": ">=8.0" } }, + "node_modules/tough-cookie": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz", + "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz", + "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/ts-interface-checker": { "version": "0.1.13", "resolved": "https://mirrors.tencent.com/npm/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", @@ -2717,6 +3726,16 @@ "node": ">=14.17" } }, + "node_modules/undici": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz", + "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, "node_modules/undici-types": { "version": "7.16.0", "resolved": "https://mirrors.tencent.com/npm/undici-types/-/undici-types-7.16.0.tgz", @@ -2958,6 +3977,13 @@ } } }, + "node_modules/vue-component-type-helpers": { + "version": "3.3.8", + "resolved": "https://registry.npmjs.org/vue-component-type-helpers/-/vue-component-type-helpers-3.3.8.tgz", + "integrity": "sha512-troqCMmQodQDqUqn63NQaFi+CDSclSe7sc8VEBFqf5GFLqmGR2Ph3P2WEC7qwpRVyEWsTi/aAr4vyOe/B1hU3g==", + "dev": true, + "license": "MIT" + }, "node_modules/vue-demi": { "version": "0.14.10", "resolved": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.10.tgz", @@ -3037,6 +4063,70 @@ "typescript": ">=5.0.0" } }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-url": { + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz", + "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.11.0", + "tr46": "^6.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/why-is-node-running": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", @@ -3072,6 +4162,104 @@ "node": ">=0.8" } }, + "node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/xlsx": { "version": "0.18.5", "resolved": "https://mirrors.tencent.com/npm/xlsx/-/xlsx-0.18.5.tgz", @@ -3093,6 +4281,23 @@ "node": ">=0.8" } }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, "node_modules/yaml": { "version": "2.8.2", "resolved": "https://mirrors.tencent.com/npm/yaml/-/yaml-2.8.2.tgz", diff --git a/frontend/package.json b/frontend/package.json index b8eb7f01..dade38ed 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -28,8 +28,10 @@ "devDependencies": { "@types/node": "^24.10.1", "@vitejs/plugin-vue": "^6.0.2", + "@vue/test-utils": "^2.4.11", "@vue/tsconfig": "^0.8.1", "autoprefixer": "^10.4.24", + "jsdom": "^29.1.1", "postcss": "^8.5.6", "tailwindcss": "^3.4.17", "typescript": "~5.9.3", diff --git a/frontend/src/features/admin/api/admin.api.ts b/frontend/src/features/admin/api/admin.api.ts index ff024bcf..181a6a32 100644 --- a/frontend/src/features/admin/api/admin.api.ts +++ b/frontend/src/features/admin/api/admin.api.ts @@ -68,17 +68,30 @@ export type ShippingInventoryValidationBatch = { runs: ShippingInventoryConfigurationTest[]; }; +export type ShippingOrderExtractionDiagnosticAutoFreezePolicy = { + mode: string; + enabled: boolean; + selected_profile_code?: string | null; + qualification_status?: string | null; + customer_scope_status?: string | null; + business_scenario_status?: string | null; + customer_confirmation_required: boolean; + evaluated_from_run: boolean; + blocking_reason_codes: string[]; +}; + export type ShippingOrderExtractionDiagnosticRun = { - run_no: string; status: string; phase: string; conversation_id: string; workflow_run_id?: string | null; - attempt_count: number; current_stage_code?: string | null; created_at?: string | null; started_at?: string | null; - finished_at?: string | null; error_code?: string | null; durations_ms: Record; + run_no: string; status: string; phase: string; conversation_id: string; + attempt_count: number; current_event_code?: string | null; created_at?: string | null; started_at?: string | null; + candidate_materialized_at?: string | null; finished_at?: string | null; error_code?: string | null; durations_ms: Record; result_counts: Record; + auto_freeze_policy: ShippingOrderExtractionDiagnosticAutoFreezePolicy; }; export type ShippingOrderExtractionDiagnosticDetail = { run: ShippingOrderExtractionDiagnosticRun; job_attempts: Array<{ job_id: number; status: string; attempts: number; max_attempts: number; created_at?: string | null; started_at?: string | null; finished_at?: string | null; duration_ms?: number | null }>; - units: Array<{ unit_id: number; position: number; unit_type: string; document_type: string; status: string; attempt_count: number; duration_ms?: number | null; error_code?: string | null; route_decisions: Array<{ attempt_no: number; execution_mode: 'deterministic' | 'dify' | 'blocked'; match_status: string; selected_profile_code?: string | null; selected_profile_version?: number | null; auto_create_approved?: boolean | null; candidate_count: number; table_count: number; approved_table_count: number; candidates: Array<{ profile_code: string; version: number; score: number; hard_match: boolean; reason_codes: string[]; missing_required_anchor_ids?: string[] }>; fallback_reason_codes: string[] }> }>; - progress_events: Array<{ event_type: string; node_type?: string | null; stage_code?: string | null; status?: string | null; workflow_run_id?: string | null; node_execution_id?: string | null; occurred_at?: string | null }>; + units: Array<{ unit_id: number; position: number; unit_type: string; document_type: string; status: string; attempt_count: number; duration_ms?: number | null; error_code?: string | null; route_decisions: Array<{ attempt_no: number; execution_mode: 'deterministic' | 'review_required' | 'skipped'; match_status: string; selected_profile_code?: string | null; selected_profile_version?: number | null; auto_create_approved?: boolean | null; candidate_count: number; table_count: number; approved_table_count: number; candidates: Array<{ profile_code: string; version: number; score: number; hard_match: boolean; reason_codes: string[]; missing_required_anchor_ids?: string[] }>; fallback_reason_codes: string[] }> }>; + progress_events: Array<{ sequence_no: number; visibility: 'workspace' | 'admin'; event_code: string; status?: string | null; unit_id?: number | null; document_id?: number | null; reason_code?: string | null; summary?: Record | null; occurred_at?: string | null }>; }; export const listShippingOrderExtractionDiagnosticRuns = (page = 1, pageSize = 25, status = '') => { const params = new URLSearchParams({ page: String(page), page_size: String(pageSize) }); @@ -429,7 +442,6 @@ export interface AdminAgentRegistrySchema { runtime_providers: string[]; conversation_modes: string[]; dify_app_types: string[]; - exposure_modes: string[]; suggested_questions_styles: string[]; default_capabilities: Record; tool_run_progress_defaults: { @@ -451,14 +463,6 @@ export interface AdminAgentRegistrySchema { default_intent_routes?: string[]; progress_contract?: Record | null; handler_config_schema?: Record; - required_runtime_capabilities?: Record; }>; handler_config_schemas: Record; content_profile_keys: string[]; @@ -501,30 +505,11 @@ export interface AdminContentProfileOption { export const listAdminContentProfiles = () => requestJson('/api/admin/agents/content-profiles', auth()); -export const listAdminAgents = (scope?: 'applications' | 'executors') => requestJson( - `/api/admin/agents${scope ? `?scope=${scope}` : ''}`, - auth(), -); +export const listAdminAgents = () => requestJson('/api/admin/agents', auth()); export const createAdminAgent = (payload: Record) => requestJson('/api/admin/agents', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) }); export const updateAdminAgent = (id: number, payload: Record) => requestJson(`/api/admin/agents/${id}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) }); -export const listAdminAgentRuntimeBindings = (agentId: number) => - requestJson( - `/api/admin/agents/${agentId}/runtime-bindings`, auth(), - ); -export const listApprovedOrderExtractionQualityBatches = (ownerAgentId: number) => - requestJson( - `/api/admin/shipping-notice/order-extraction-quality-batches?owner_agent_id=${ownerAgentId}`, auth(), - ); -export const saveAdminAgentRuntimeBinding = ( - agentId: number, - capabilityCode: string, - payload: { provider_agent_id: number; enabled: boolean; config: Record }, -) => requestJson( - `/api/admin/agents/${agentId}/runtime-bindings/${capabilityCode}`, - { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) }, -); export const deleteAdminAgent = (id: number) => requestJson(`/api/admin/agents/${id}`, { method: 'DELETE', ...auth() }); diff --git a/frontend/src/features/admin/modules/agents/AgentsPage.vue b/frontend/src/features/admin/modules/agents/AgentsPage.vue index 98a3bd68..9321ff1e 100644 --- a/frontend/src/features/admin/modules/agents/AgentsPage.vue +++ b/frontend/src/features/admin/modules/agents/AgentsPage.vue @@ -73,25 +73,14 @@ const { resetColumnWidths, } = useAgentsTableColumnResize(); -const tableHeaderColumns = computed(() => ( - activeManagementTab.value === 'executors' - ? [ - { key: 'name', label: t('admin.agent.headers.name'), align: 'left' as const }, - { key: 'executorType', label: t('admin.agent.headers.executorType'), align: 'left' as const }, - { key: 'protocol', label: t('admin.agent.headers.runtimeProtocol'), align: 'left' as const }, - { key: 'config', label: t('admin.agent.headers.config'), align: 'left' as const }, - { key: 'status', label: t('admin.agent.headers.status'), align: 'left' as const }, - { key: 'actions', label: t('admin.agent.headers.actions'), align: 'right' as const }, - ] - : [ - { key: 'name', label: t('admin.agent.headers.name'), align: 'left' as const }, - { key: 'type', label: t('admin.agent.headers.type'), align: 'left' as const }, - { key: 'aggregation', label: t('admin.agent.headers.aggregation'), align: 'left' as const }, - { key: 'config', label: t('admin.agent.headers.config'), align: 'left' as const }, - { key: 'status', label: t('admin.agent.headers.status'), align: 'left' as const }, - { key: 'actions', label: t('admin.agent.headers.actions'), align: 'right' as const }, - ] -)); +const tableHeaderColumns = computed(() => [ + { key: 'name', label: t('admin.agent.headers.name'), align: 'left' as const }, + { key: 'type', label: t('admin.agent.headers.type'), align: 'left' as const }, + { key: 'aggregation', label: t('admin.agent.headers.aggregation'), align: 'left' as const }, + { key: 'config', label: t('admin.agent.headers.config'), align: 'left' as const }, + { key: 'status', label: t('admin.agent.headers.status'), align: 'left' as const }, + { key: 'actions', label: t('admin.agent.headers.actions'), align: 'right' as const }, +]); const formatAgentCode = (agent: AgentRow) => agent.agent_code || 'generic'; @@ -144,17 +133,6 @@ const formatRuntimeProviderLabel = (agent: AgentRow) => { }; const showFormDialog = ref(false); -const activeManagementTab = ref<'applications' | 'executors'>('applications'); -const visibleAgents = computed(() => agents.value.filter((agent) => ( - activeManagementTab.value === 'executors' - ? agent.exposure_mode === 'internal' - : agent.exposure_mode !== 'internal' -))); -const emptyStateText = computed(() => ( - activeManagementTab.value === 'executors' - ? t('admin.agent.executor.empty') - : t('admin.agent.noAgents') -)); /** * 打开新建应用弹窗并重置表单状态。 @@ -165,16 +143,6 @@ const openCreateDialog = (): void => { showFormDialog.value = true; }; -const formatExecutorProtocol = (agent: AgentRow) => ( - `${formatRuntimeProviderLabel(agent)} · ${agent.dify_app_type === 'workflow' ? 'Workflow' : 'Chatflow'}` -); - -/** 打开内部执行器专用注册入口,预置 Dify Workflow 与 internal 可见性。 */ -const openCreateInternalExecutorDialog = (): void => { - resetForm('internal_executor'); - showFormDialog.value = true; -}; - /** * 打开编辑应用弹窗并载入当前行数据。 * 核心逻辑:复用 selectAgent 的表单映射逻辑,确保列表行、权限弹窗和保存接口使用同一份状态。 @@ -210,41 +178,16 @@ onMounted(() => {

{{ t('admin.agent.title') }}

{{ t('admin.agent.subtitle') }}

-
- - -
- - -
- -
-
+
-

{{ emptyStateText }}

+

{{ t('admin.agent.noAgents') }}

{ {
-

- {{ activeManagementTab === 'executors' ? t('admin.agent.executor.workflowExecutor') : formatAgentTypeLabel(agent) }} +

+ {{ formatAgentTypeLabel(agent) }}

- {{ activeManagementTab === 'executors' ? t('admin.agent.executor.internalOnly') : formatRuntimeProviderLabel(agent) }} + {{ formatRuntimeProviderLabel(agent) }}

-
-

- {{ formatExecutorProtocol(agent) }} -

-

{{ t('admin.agent.executor.internalOnly') }}

-
-
+

{ {{ t('admin.edit') }}

-
+
-
+
-
+
-
-

{{ t('admin.agent.runtimeBinding.executorGovernance') }}

-
-
-
-
-
-
- -
+
-
+